xref: /freebsd/usr.sbin/bsdinstall/scripts/zfsboot (revision 22cf89c938886d14f5796fc49f9f020c23ea8eaf)
1#!/bin/sh
2#-
3# Copyright (c) 2013-2016 Allan Jude
4# Copyright (c) 2013-2018 Devin Teske
5# All rights reserved.
6#
7# Redistribution and use in source and binary forms, with or without
8# modification, are permitted provided that the following conditions
9# are met:
10# 1. Redistributions of source code must retain the above copyright
11#    notice, this list of conditions and the following disclaimer.
12# 2. Redistributions in binary form must reproduce the above copyright
13#    notice, this list of conditions and the following disclaimer in the
14#    documentation and/or other materials provided with the distribution.
15#
16# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19# ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26# SUCH DAMAGE.
27#
28#
29############################################################ INCLUDES
30
31BSDCFG_SHARE="/usr/share/bsdconfig"
32. $BSDCFG_SHARE/common.subr || exit 1
33f_dprintf "%s: loading includes..." "$0"
34f_include $BSDCFG_SHARE/device.subr
35f_include $BSDCFG_SHARE/dialog.subr
36f_include $BSDCFG_SHARE/password/password.subr
37f_include $BSDCFG_SHARE/variable.subr
38
39############################################################ CONFIGURATION
40
41#
42# Default name of the boot-pool
43#
44: ${ZFSBOOT_POOL_NAME:=zroot}
45
46#
47# Default pool size is optional
48#
49: ${ZFSBOOT_POOL_SIZE=}
50
51#
52# Default options to use when creating zroot pool
53#
54: ${ZFSBOOT_POOL_CREATE_OPTIONS:=-O compress=lz4 -O atime=off}
55
56#
57# Default name for the boot environment parent dataset
58#
59: ${ZFSBOOT_BEROOT_NAME:=ROOT}
60
61#
62# Default name for the primary boot environment
63#
64: ${ZFSBOOT_BOOTFS_NAME:=default}
65
66#
67# Default Virtual Device (vdev) type to create
68#
69: ${ZFSBOOT_VDEV_TYPE:=stripe}
70
71#
72# Should we use sysctl(8) vfs.zfs.min_auto_ashift=12 to force 4K sectors?
73#
74: ${ZFSBOOT_FORCE_4K_SECTORS:=1}
75
76#
77# Should we use geli(8) to encrypt the drives?
78# NB: Automatically enables ZFSBOOT_BOOT_POOL
79#
80: ${ZFSBOOT_GELI_ENCRYPTION=}
81
82#
83# Default path to the geli(8) keyfile used in drive encryption
84#
85: ${ZFSBOOT_GELI_KEY_FILE:=/boot/encryption.key}
86
87#
88# Create a separate boot pool?
89# NB: Automatically set when using geli(8) or MBR
90#
91: ${ZFSBOOT_BOOT_POOL=}
92
93#
94# Options to use when creating separate boot pool (if any)
95#
96: ${ZFSBOOT_BOOT_POOL_CREATE_OPTIONS:=}
97
98#
99# Default name for boot pool when enabled (e.g., geli(8) or MBR)
100#
101: ${ZFSBOOT_BOOT_POOL_NAME:=bootpool}
102
103#
104# Default size for boot pool when enabled (e.g., geli(8) or MBR)
105#
106: ${ZFSBOOT_BOOT_POOL_SIZE:=2g}
107
108#
109# Default disks to use (always empty unless being scripted)
110#
111: ${ZFSBOOT_DISKS:=}
112
113#
114# Default partitioning scheme to use on disks
115#
116: ${ZFSBOOT_PARTITION_SCHEME:=}
117
118#
119# Default boot type to use on disks
120#
121: ${ZFSBOOT_BOOT_TYPE:=}
122
123#
124# How much swap to put on each block device in the boot zpool
125# NOTE: Value passed to gpart(8); which supports SI unit suffixes.
126#
127: ${ZFSBOOT_SWAP_SIZE:=2g}
128
129#
130# Should we use geli(8) to encrypt the swap?
131#
132: ${ZFSBOOT_SWAP_ENCRYPTION=}
133
134#
135# Should we use gmirror(8) to mirror the swap?
136#
137: ${ZFSBOOT_SWAP_MIRROR=}
138
139#
140# Default ZFS datasets for root zpool
141#
142# NOTE: Requires /tmp, /var/tmp, /$ZFSBOOT_BOOTFS_NAME/$ZFSBOOT_BOOTFS_NAME
143# NOTE: Anything after pound/hash character [#] is ignored as a comment.
144#
145f_isset ZFSBOOT_DATASETS || ZFSBOOT_DATASETS="
146	# DATASET	OPTIONS (comma or space separated; or both)
147
148	# Boot Environment [BE] root and default boot dataset
149	/$ZFSBOOT_BEROOT_NAME				mountpoint=none
150	/$ZFSBOOT_BEROOT_NAME/$ZFSBOOT_BOOTFS_NAME	mountpoint=/
151
152	# Home directories separated so they are common to all BEs
153	/home		mountpoint=/home
154
155	# Compress /tmp, allow exec but not setuid
156	/tmp		mountpoint=/tmp,exec=on,setuid=off
157
158	# Don't mount /usr so that 'base' files go to the BEROOT
159	/usr		mountpoint=/usr,canmount=off
160
161	# Ports tree
162	/usr/ports	setuid=off
163
164	# Source tree (compressed)
165	/usr/src
166
167	# Create /var and friends
168	/var		mountpoint=/var,canmount=off
169	/var/audit	exec=off,setuid=off
170	/var/crash	exec=off,setuid=off
171	/var/log	exec=off,setuid=off
172	/var/mail	atime=on
173	/var/tmp	setuid=off
174" # END-QUOTE
175
176#
177# If interactive and the user has not explicitly chosen a vdev type or disks,
178# make the user confirm scripted/default choices when proceeding to install.
179#
180: ${ZFSBOOT_CONFIRM_LAYOUT:=1}
181
182############################################################ GLOBALS
183
184#
185# Format of a line in printf(1) syntax to add to fstab(5)
186#
187FSTAB_FMT="%s\t\t%s\t%s\t%s\t\t%s\t%s\n"
188
189#
190# Command strings for various tasks
191#
192COPY='cp "%s" "%s"'
193CHMOD_MODE='chmod %s "%s"'
194DD_WITH_OPTIONS='dd if="%s" of="%s" %s'
195ECHO_APPEND='echo "%s" >> "%s"'
196ECHO_OVERWRITE='echo "%s" > "%s"'
197GELI_ATTACH='geli attach -j - -k "%s" "%s"'
198GELI_ATTACH_NOKEY='geli attach -j - "%s"'
199GELI_DETACH_F='geli detach -f "%s"'
200GELI_PASSWORD_INIT='geli init -b -B "%s" -e %s -J - -K "%s" -l 256 -s 4096 "%s"'
201GELI_PASSWORD_GELIBOOT_INIT='geli init -bg -e %s -J - -l 256 -s 4096 "%s"'
202GPART_ADD_ALIGN='gpart add %s -t %s "%s"'
203GPART_ADD_ALIGN_INDEX='gpart add %s -i %s -t %s "%s"'
204GPART_ADD_ALIGN_INDEX_WITH_SIZE='gpart add %s -i %s -t %s -s %s "%s"'
205GPART_ADD_ALIGN_LABEL='gpart add %s -l %s -t %s "%s"'
206GPART_ADD_ALIGN_LABEL_WITH_SIZE='gpart add %s -l %s -t %s -s %s "%s"'
207GPART_BOOTCODE='gpart bootcode -b "%s" "%s"'
208GPART_BOOTCODE_PART='gpart bootcode -b "%s" -p "%s" -i %s "%s"'
209GPART_BOOTCODE_PARTONLY='gpart bootcode -p "%s" -i %s "%s"'
210GPART_CREATE='gpart create -s %s "%s"'
211GPART_DESTROY_F='gpart destroy -F "%s"'
212GPART_SET_ACTIVE='gpart set -a active -i %s "%s"'
213GPART_SET_LENOVOFIX='gpart set -a lenovofix "%s"'
214GPART_SET_PMBR_ACTIVE='gpart set -a active "%s"'
215GRAID_DELETE='graid delete "%s"'
216KLDLOAD='kldload %s'
217LN_SF='ln -sf "%s" "%s"'
218MKDIR_P='mkdir -p "%s"'
219MOUNT_TYPE='mount -t %s "%s" "%s"'
220NEWFS_ESP='newfs_msdos "%s"'
221PRINTF_CONF="printf '%s=\"%%s\"\\\n' %s >> \"%s\""
222PRINTF_FSTAB='printf "$FSTAB_FMT" "%s" "%s" "%s" "%s" "%s" "%s" >> "%s"'
223SHELL_TRUNCATE=':> "%s"'
224SWAP_GMIRROR_LABEL='gmirror label swap %s'
225SYSCTL_ZFS_MIN_ASHIFT_12='sysctl vfs.zfs.min_auto_ashift=12'
226UMOUNT='umount "%s"'
227ZFS_CREATE_WITH_OPTIONS='zfs create %s "%s"'
228ZFS_MOUNT='zfs mount "%s"'
229ZFS_SET='zfs set "%s" "%s"'
230ZFS_UNMOUNT='zfs unmount "%s"'
231ZPOOL_CREATE_WITH_OPTIONS='zpool create %s "%s" %s %s'
232ZPOOL_DESTROY='zpool destroy "%s"'
233ZPOOL_EXPORT='zpool export "%s"'
234ZPOOL_EXPORT_F='zpool export -f "%s"'
235ZPOOL_IMPORT_WITH_OPTIONS='zpool import %s "%s"'
236ZPOOL_LABELCLEAR_F='zpool labelclear -f "%s"'
237ZPOOL_SET='zpool set %s "%s"'
238
239#
240# Strings that should be moved to an i18n file and loaded with f_include_lang()
241#
242hline_alnum_arrows_punc_tab_enter="Use alnum, arrows, punctuation, TAB or ENTER"
243hline_arrows_space_tab_enter="Use arrows, SPACE, TAB or ENTER"
244hline_arrows_tab_enter="Press arrows, TAB or ENTER"
245msg_an_unknown_error_occurred="An unknown error occurred"
246msg_back="Back"
247msg_cancel="Cancel"
248msg_change_selection="Change Selection"
249msg_configure_options="Configure Options:"
250msg_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"
251msg_disk_info="Disk Info"
252msg_disk_info_help="Get detailed information on disk device(s)"
253msg_disk_plural="disks"
254msg_disk_singular="disk"
255msg_encrypt_disks="Encrypt Disks?"
256msg_encrypt_disks_help="Use geli(8) to encrypt all data partitions"
257msg_error="Error"
258msg_force_4k_sectors="Force 4K Sectors?"
259msg_force_4k_sectors_help="Align partitions to 4K sector boundries and set vfs.zfs.min_auto_ashift=12"
260msg_freebsd_installer="$OSNAME Installer"
261msg_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"
262msg_geli_setup="Initializing encryption on selected disks,\n this will take several seconds per disk"
263msg_install="Install"
264msg_install_desc="Proceed with Installation"
265msg_install_help="Create ZFS boot pool with displayed options"
266msg_invalid_boot_pool_size="Invalid boot pool size \`%s'"
267msg_invalid_disk_argument="Invalid disk argument \`%s'"
268msg_invalid_index_argument="Invalid index argument \`%s'"
269msg_invalid_pool_size="Invalid pool size \`%s'"
270msg_invalid_swap_size="Invalid swap size \`%s'"
271msg_invalid_virtual_device_type="Invalid Virtual Device type \`%s'"
272msg_last_chance_are_you_sure="Last Chance! Are you sure you want to destroy\nthe current contents of the following disks:\n\n   %s"
273msg_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'
274msg_mirror_desc="Mirror - n-Way Mirroring"
275msg_mirror_help="[2+ Disks] Mirroring provides the best performance, but the least storage"
276msg_missing_disk_arguments="missing disk arguments"
277msg_missing_one_or_more_scripted_disks="Missing one or more scripted disks!"
278msg_no="NO"
279msg_no_disks_present_to_configure="No disk(s) present to configure"
280msg_no_disks_selected="No disks selected."
281msg_not_enough_disks_selected="Not enough disks selected. (%u < %u minimum)"
282msg_null_disk_argument="NULL disk argument"
283msg_null_index_argument="NULL index argument"
284msg_null_poolname="NULL poolname"
285msg_odd_disk_selected="An even number of disks must be selected to create a RAID 1+0. (%u selected)"
286msg_ok="OK"
287msg_partition_scheme="Partition Scheme"
288msg_partition_scheme_help="Select partitioning scheme. GPT is recommended."
289msg_please_enter_a_name_for_your_zpool="Please enter a name for your zpool:"
290msg_please_enter_amount_of_swap_space="Please enter amount of swap space (SI-Unit suffixes\nrecommended; e.g., \`2g' for 2 Gigabytes):"
291msg_please_select_one_or_more_disks="Please select one or more disks to create a zpool:"
292msg_pool_name="Pool Name"
293msg_pool_name_cannot_be_empty="Pool name cannot be empty."
294msg_pool_name_help="Customize the name of the zpool to be created (Required)"
295msg_pool_type_disks="Pool Type/Disks:"
296msg_pool_type_disks_help="Choose type of ZFS Virtual Device and disks to use (Required)"
297msg_processing_selection="Processing selection..."
298msg_raid10_desc="RAID 1+0 - n x 2-Way Mirrors"
299msg_raid10_help="[4+ Disks] Striped Mirrors provides the best performance, but the least storage"
300msg_raidz1_desc="RAID-Z1 - Single Redundant RAID"
301msg_raidz1_help="[3+ Disks] Withstand failure of 1 disk. Recommended for: 3, 5 or 9 disks"
302msg_raidz2_desc="RAID-Z2 - Double Redundant RAID"
303msg_raidz2_help="[4+ Disks] Withstand failure of 2 disks. Recommended for: 4, 6 or 10 disks"
304msg_raidz3_desc="RAID-Z3 - Triple Redundant RAID"
305msg_raidz3_help="[5+ Disks] Withstand failure of 3 disks. Recommended for: 5, 7 or 11 disks"
306msg_rescan_devices="Rescan Devices"
307msg_rescan_devices_help="Scan for device changes"
308msg_select="Select"
309msg_select_a_disk_device="Select a disk device"
310msg_select_virtual_device_type="Select Virtual Device type:"
311msg_stripe_desc="Stripe - No Redundancy"
312msg_stripe_help="[1+ Disks] Striping provides maximum storage but no redundancy"
313msg_swap_encrypt="Encrypt Swap?"
314msg_swap_encrypt_help="Encrypt swap partitions with temporary keys, discarded on reboot"
315msg_swap_invalid="The selected swap size (%s) is invalid. Enter a number optionally followed by units. Example: 2G"
316msg_swap_mirror="Mirror Swap?"
317msg_swap_mirror_help="Mirror swap partitions for redundancy, breaks crash dumps"
318msg_swap_size="Swap Size"
319msg_swap_size_help="Customize how much swap space is allocated to each selected disk"
320msg_swap_toosmall="The selected swap size (%s) is too small. Please enter a value greater than 100MB or enter 0 for no swap"
321msg_these_disks_are_too_small="These disks are smaller than the amount of requested\nswap (%s) and/or geli(8) (%s) partitions, which would\ntake 100%% or more of each of the following selected disks:\n\n  %s\n\nRecommend changing partition size(s) and/or selecting a\ndifferent set of disks."
322msg_unable_to_get_disk_capacity="Unable to get disk capacity of \`%s'"
323msg_unsupported_partition_scheme="%s is an unsupported partition scheme"
324msg_user_cancelled="User Cancelled."
325msg_yes="YES"
326msg_zfs_configuration="ZFS Configuration"
327
328############################################################ FUNCTIONS
329
330# dialog_menu_main
331#
332# Display the dialog(1)-based application main menu.
333#
334dialog_menu_main()
335{
336	local title="$DIALOG_TITLE"
337	local btitle="$DIALOG_BACKTITLE"
338	local prompt="$msg_configure_options"
339	local force4k="$msg_no"
340	local usegeli="$msg_no"
341	local swapgeli="$msg_no"
342	local swapmirror="$msg_no"
343	[ "$ZFSBOOT_FORCE_4K_SECTORS" ] && force4k="$msg_yes"
344	[ "$ZFSBOOT_GELI_ENCRYPTION" ] && usegeli="$msg_yes"
345	[ "$ZFSBOOT_SWAP_ENCRYPTION" ] && swapgeli="$msg_yes"
346	[ "$ZFSBOOT_SWAP_MIRROR" ] && swapmirror="$msg_yes"
347	local disks n disks_grammar
348	f_count n $ZFSBOOT_DISKS
349	{ [ $n -eq 1 ] && disks_grammar=$msg_disk_singular; } ||
350		disks_grammar=$msg_disk_plural # grammar
351	local menu_list="
352		'>>> $msg_install'      '$msg_install_desc'
353		                        '$msg_install_help'
354		'T $msg_pool_type_disks'
355		               '$ZFSBOOT_VDEV_TYPE: $n $disks_grammar'
356		               '$msg_pool_type_disks_help'
357		'- $msg_rescan_devices' '*'
358		                        '$msg_rescan_devices_help'
359		'- $msg_disk_info'      '*'
360		                        '$msg_disk_info_help'
361		'N $msg_pool_name'      '$ZFSBOOT_POOL_NAME'
362		                        '$msg_pool_name_help'
363		'4 $msg_force_4k_sectors'
364		                        '$force4k'
365		                        '$msg_force_4k_sectors_help'
366		'E $msg_encrypt_disks'  '$usegeli'
367		                        '$msg_encrypt_disks_help'
368		'P $msg_partition_scheme'
369		               '$ZFSBOOT_PARTITION_SCHEME ($ZFSBOOT_BOOT_TYPE)'
370		               '$msg_partition_scheme_help'
371		'S $msg_swap_size'      '$ZFSBOOT_SWAP_SIZE'
372		                        '$msg_swap_size_help'
373		'M $msg_swap_mirror'    '$swapmirror'
374		                        '$msg_swap_mirror_help'
375		'W $msg_swap_encrypt'   '$swapgeli'
376		                        '$msg_swap_encrypt_help'
377	" # END-QUOTE
378	local defaultitem= # Calculated below
379	local hline="$hline_alnum_arrows_punc_tab_enter"
380
381	local height width rows
382	eval f_dialog_menu_with_help_size height width rows \
383		\"\$title\" \"\$btitle\" \"\$prompt\" \"\$hline\" $menu_list
384
385	# Obtain default-item from previously stored selection
386	f_dialog_default_fetch defaultitem
387
388	local menu_choice
389	menu_choice=$( eval $DIALOG \
390		--title \"\$title\"              \
391		--backtitle \"\$btitle\"         \
392		--hline \"\$hline\"              \
393		--item-help                      \
394		--ok-label \"\$msg_select\"      \
395		--cancel-label \"\$msg_cancel\"  \
396		--default-item \"\$defaultitem\" \
397		--menu \"\$prompt\"              \
398		$height $width $rows             \
399		$menu_list                       \
400		2>&1 >&$DIALOG_TERMINAL_PASSTHRU_FD
401	)
402	local retval=$?
403	f_dialog_data_sanitize menu_choice
404	f_dialog_menutag_store "$menu_choice"
405
406	# Only update default-item on success
407	[ $retval -eq $DIALOG_OK ] && f_dialog_default_store "$menu_choice"
408
409	return $retval
410}
411
412# dialog_last_chance $disks ...
413#
414# Display a list of the disks that the user is about to destroy. The default
415# action is to return error status unless the user explicitly (non-default)
416# selects "Yes" from the noyes dialog.
417#
418dialog_last_chance()
419{
420	local title="$DIALOG_TITLE"
421	local btitle="$DIALOG_BACKTITLE"
422	local prompt # Calculated below
423	local hline="$hline_arrows_tab_enter"
424
425	local height=8 width=50 prefix="   "
426	local plen=${#prefix} list= line=
427	local max_width=$(( $width - 3 - $plen ))
428
429	local yes no defaultno extra_args format
430	if [ "$USE_XDIALOG" ]; then
431		yes=ok no=cancel defaultno=default-no
432		extra_args="--wrap --left"
433		format="$msg_last_chance_are_you_sure"
434	else
435		yes=yes no=no defaultno=defaultno
436		extra_args="--colors --cr-wrap"
437		format="$msg_last_chance_are_you_sure_color"
438	fi
439
440	local disk line_width
441	for disk in $*; do
442		if [ "$line" ]; then
443			line_width=${#line}
444		else
445			line_width=$plen
446		fi
447		line_width=$(( $line_width + 1 + ${#disk} ))
448		# Add newline before disk if it would exceed max_width
449		if [ $line_width -gt $max_width ]; then
450			list="$list$line\n"
451			line="$prefix"
452			height=$(( $height + 1 ))
453		fi
454		# Add the disk to the list
455		line="$line $disk"
456	done
457	# Append the left-overs
458	if [ "${line#$prefix}" ]; then
459		list="$list$line"
460		height=$(( $height + 1 ))
461	fi
462
463	# Add height for Xdialog(1)
464	[ "$USE_XDIALOG" ] && height=$(( $height + $height / 5 + 3 ))
465
466	prompt=$( printf "$format" "$list" )
467	f_dprintf "%s: Last Chance!" "$0"
468	$DIALOG \
469		--title "$title"        \
470		--backtitle "$btitle"   \
471		--hline "$hline"        \
472		--$defaultno            \
473		--$yes-label "$msg_yes" \
474		--$no-label "$msg_no"   \
475		$extra_args             \
476		--yesno "$prompt" $height $width
477}
478
479# dialog_menu_layout
480#
481# Configure Virtual Device type and disks to use for the ZFS boot pool. User
482# must select enough disks to satisfy the chosen vdev type.
483#
484dialog_menu_layout()
485{
486	local funcname=dialog_menu_layout
487	local title="$DIALOG_TITLE"
488	local btitle="$DIALOG_BACKTITLE"
489	local vdev_prompt="$msg_select_virtual_device_type"
490	local disk_prompt="$msg_please_select_one_or_more_disks"
491	local vdev_menu_list="
492		'stripe' '$msg_stripe_desc' '$msg_stripe_help'
493		'mirror' '$msg_mirror_desc' '$msg_mirror_help'
494		'raid10' '$msg_raid10_desc' '$msg_raid10_help'
495		'raidz1' '$msg_raidz1_desc' '$msg_raidz1_help'
496		'raidz2' '$msg_raidz2_desc' '$msg_raidz2_help'
497		'raidz3' '$msg_raidz3_desc' '$msg_raidz3_help'
498	" # END-QUOTE
499	local disk_check_list= # Calculated below
500	local vdev_hline="$hline_arrows_tab_enter"
501	local disk_hline="$hline_arrows_space_tab_enter"
502
503	# Warn the user if vdev type is not valid
504	case "$ZFSBOOT_VDEV_TYPE" in
505	stripe|mirror|raid10|raidz1|raidz2|raidz3) : known good ;;
506	*)
507		f_dprintf "%s: Invalid virtual device type \`%s'" \
508			  $funcname "$ZFSBOOT_VDEV_TYPE"
509		f_show_err "$msg_invalid_virtual_device_type" \
510			   "$ZFSBOOT_VDEV_TYPE"
511		f_interactive || return $FAILURE
512	esac
513
514	# Calculate size of vdev menu once only
515	local vheight vwidth vrows
516	eval f_dialog_menu_with_help_size vheight vwidth vrows \
517		\"\$title\" \"\$btitle\" \"\$vdev_prompt\" \"\$vdev_hline\" \
518		$vdev_menu_list
519
520	# Get a list of probed disk devices
521	local disks=
522	debug= f_device_find "" $DEVICE_TYPE_DISK disks
523
524	# Prune out mounted md(4) devices that may be part of the boot process
525	local disk name new_list=
526	for disk in $disks; do
527		debug= $disk get name name
528		case "$name" in
529		md[0-9]*) f_mounted -b "/dev/$name" && continue ;;
530		esac
531		new_list="$new_list $disk"
532	done
533	disks="${new_list# }"
534
535	# Prune out disks that are not available to install to
536	local avail_disks=
537	for disk in $disks; do
538		debug= $disk get name name
539		geom disk list $name | awk '$1 == "Mode:" && $2 != "r0w0e0" { exit 1 }'
540		[ $? -eq 0 ] && avail_disks="$avail_disks $disk"
541	done
542	disks="${avail_disks# }"
543
544	# Debugging
545	if [ "$debug" ]; then
546		local disk_names=
547		for disk in $disks; do
548			debug= $disk get name name
549			disk_names="$disk_names $name"
550		done
551		f_dprintf "$funcname: disks=[%s]" "${disk_names# }"
552	fi
553
554	if [ ! "$disks" ]; then
555		f_dprintf "No disk(s) present to configure"
556		f_show_err "$msg_no_disks_present_to_configure"
557		return $FAILURE
558	fi
559
560	# Lets sort the disks array to be more user friendly
561	f_device_sort_by name disks disks
562
563	#
564	# Operate in a loop so we can (if interactive) repeat if not enough
565	# disks are selected to satisfy the chosen vdev type or user wants to
566	# back-up to the previous menu.
567	#
568	local vardisk ndisks onoff selections vdev_choice breakout device
569	local valid_disks all_valid want_disks desc height width rows
570	while :; do
571		#
572		# Confirm the vdev type that was selected
573		#
574		if f_interactive && [ "$ZFSBOOT_CONFIRM_LAYOUT" ]; then
575			vdev_choice=$( eval $DIALOG \
576				--title \"\$title\"              \
577				--backtitle \"\$btitle\"         \
578				--hline \"\$vdev_hline\"         \
579				--ok-label \"\$msg_ok\"          \
580				--cancel-label \"\$msg_cancel\"  \
581				--item-help                      \
582				--default-item \"\$ZFSBOOT_VDEV_TYPE\" \
583				--menu \"\$vdev_prompt\"         \
584				$vheight $vwidth $vrows          \
585				$vdev_menu_list                  \
586				2>&1 >&$DIALOG_TERMINAL_PASSTHRU_FD
587			) || return $?
588				# Exit if user pressed ESC or chose Cancel/No
589			f_dialog_data_sanitize vdev_choice
590
591			ZFSBOOT_VDEV_TYPE="$vdev_choice"
592			f_dprintf "$funcname: ZFSBOOT_VDEV_TYPE=[%s]" \
593			          "$ZFSBOOT_VDEV_TYPE"
594		fi
595
596		# Determine the number of disks needed for this vdev type
597		want_disks=0
598		case "$ZFSBOOT_VDEV_TYPE" in
599		stripe) want_disks=1 ;;
600		mirror) want_disks=2 ;;
601		raid10) want_disks=4 ;;
602		raidz1) want_disks=3 ;;
603		raidz2) want_disks=4 ;;
604		raidz3) want_disks=5 ;;
605		esac
606
607		#
608		# Warn the user if any scripted disks are invalid
609		#
610		valid_disks= all_valid=${ZFSBOOT_DISKS:+1} # optimism
611		for disk in $ZFSBOOT_DISKS; do
612			if debug= f_device_find -1 \
613				$disk $DEVICE_TYPE_DISK device
614			then
615				valid_disks="$valid_disks $disk"
616				continue
617			fi
618			f_dprintf "$funcname: \`%s' is not a real disk" "$disk"
619			all_valid=
620		done
621		if [ ! "$all_valid" ]; then
622			if [ "$ZFSBOOT_DISKS" ]; then
623				f_show_err \
624				    "$msg_missing_one_or_more_scripted_disks"
625			else
626				f_dprintf "No disks selected."
627				f_interactive ||
628					f_show_err "$msg_no_disks_selected"
629			fi
630			f_interactive || return $FAILURE
631		fi
632		ZFSBOOT_DISKS="${valid_disks# }"
633
634		#
635		# Short-circuit if we're running non-interactively
636		#
637		if ! f_interactive || [ ! "$ZFSBOOT_CONFIRM_LAYOUT" ]; then
638			f_count ndisks $ZFSBOOT_DISKS
639			[ $ndisks -ge $want_disks ] && break # to success
640
641			# Not enough disks selected
642			f_dprintf "$funcname: %s: %s (%u < %u minimum)" \
643				  "$ZFSBOOT_VDEV_TYPE" \
644				  "Not enough disks selected." \
645				  $ndisks $want_disks
646			f_interactive || return $FAILURE
647			msg_yes="$msg_change_selection" msg_no="$msg_cancel" \
648				f_yesno "%s: $msg_not_enough_disks_selected" \
649				"$ZFSBOOT_VDEV_TYPE" $ndisks $want_disks ||
650				return $FAILURE
651		fi
652
653		#
654		# Confirm the disks that were selected
655		# Loop until the user cancels or selects enough disks
656		#
657		breakout=
658		while :; do
659			# Loop over list of available disks, resetting state
660			for disk in $disks; do
661				f_isset _${disk}_status && setvar _${disk}_status
662			done
663
664			# Loop over list of selected disks and create temporary
665			# locals to map statuses onto up-to-date list of disks
666			for disk in $ZFSBOOT_DISKS; do
667				debug= f_device_find -1 \
668					$disk $DEVICE_TYPE_DISK disk
669				f_isset _${disk}_status ||
670					local _${disk}_status
671				setvar _${disk}_status on
672			done
673
674			# Create the checklist menu of discovered disk devices
675			disk_check_list=
676			for disk in $disks; do
677				desc=
678				$disk get name name
679				$disk get desc desc
680				f_shell_escape "$desc" desc
681				f_getvar _${disk}_status:-off onoff
682				disk_check_list="$disk_check_list
683					$name '$desc' $onoff"
684			done
685
686			eval f_dialog_checklist_size height width rows \
687				\"\$title\" \"\$btitle\" \"\$prompt\" \
688				\"\$hline\" $disk_check_list
689
690			selections=$( eval $DIALOG \
691				--title \"\$DIALOG_TITLE\"         \
692				--backtitle \"\$DIALOG_BACKTITLE\" \
693				--separate-output                  \
694				--hline \"\$hline\"                \
695				--ok-label \"\$msg_ok\"            \
696				--cancel-label \"\$msg_back\"      \
697				--checklist \"\$prompt\"           \
698				$height $width $rows               \
699				$disk_check_list                   \
700				2>&1 >&$DIALOG_TERMINAL_PASSTHRU_FD
701			) || break
702				# Loop if user pressed ESC or chose Cancel/No
703			f_dialog_data_sanitize selections
704
705			ZFSBOOT_DISKS="$selections"
706			f_dprintf "$funcname: ZFSBOOT_DISKS=[%s]" \
707			          "$ZFSBOOT_DISKS"
708
709			f_count ndisks $ZFSBOOT_DISKS
710
711			if [ "$ZFSBOOT_VDEV_TYPE" == "raid10" ] &&
712			    [ $(( $ndisks % 2 )) -ne 0 ]; then
713				f_dprintf "$funcname: %s: %s (%u %% 2 = %u)" \
714					  "$ZFSBOOT_VDEV_TYPE" \
715					  "Number of disks not even:" \
716					  $ndisks $(( $ndisks % 2 ))
717				msg_yes="$msg_change_selection" \
718					msg_no="$msg_cancel" \
719					f_yesno "%s: $msg_odd_disk_selected" \
720						"$ZFSBOOT_VDEV_TYPE" $ndisks ||
721						break
722				continue
723			fi
724
725			[ $ndisks -ge $want_disks ] &&
726				breakout=break && break
727
728			# Not enough disks selected
729			f_dprintf "$funcname: %s: %s (%u < %u minimum)" \
730				  "$ZFSBOOT_VDEV_TYPE" \
731			          "Not enough disks selected." \
732			          $ndisks $want_disks
733			msg_yes="$msg_change_selection" msg_no="$msg_cancel" \
734				f_yesno "%s: $msg_not_enough_disks_selected" \
735				"$ZFSBOOT_VDEV_TYPE" $ndisks $want_disks ||
736				break
737		done
738		[ "$breakout" = "break" ] && break
739		[ "$ZFSBOOT_CONFIRM_LAYOUT" ] || return $FAILURE
740	done
741
742	return $DIALOG_OK
743}
744
745# zfs_create_diskpart $disk $index
746#
747# For each block device to be used in the zpool, rather than just create the
748# zpool with the raw block devices (e.g., da0, da1, etc.) we create partitions
749# so we can have some real swap. This also provides wiggle room incase your
750# replacement drivers do not have the exact same sector counts.
751#
752# NOTE: $swapsize and $bootsize should be defined by the calling function.
753# NOTE: Sets $bootpart and $targetpart for the calling function.
754#
755zfs_create_diskpart()
756{
757	local funcname=zfs_create_diskpart
758	local disk="$1" index="$2"
759
760	# Check arguments
761	if [ ! "$disk" ]; then
762		f_dprintf "$funcname: NULL disk argument"
763		msg_error="$msg_error: $funcname" \
764			f_show_err "$msg_null_disk_argument"
765		return $FAILURE
766	fi
767	if [ "${disk#*[$IFS]}" != "$disk" ]; then
768		f_dprintf "$funcname: Invalid disk argument \`%s'" "$disk"
769		msg_error="$msg_error: $funcname" \
770			f_show_err "$msg_invalid_disk_argument" "$disk"
771		return $FAILURE
772	fi
773	if [ ! "$index" ]; then
774		f_dprintf "$funcname: NULL index argument"
775		msg_error="$msg_error: $funcname" \
776			f_show_err "$msg_null_index_argument"
777		return $FAILURE
778	fi
779	if ! f_isinteger "$index"; then
780		f_dprintf "$funcname: Invalid index argument \`%s'" "$index"
781		msg_error="$msg_error: $funcname" \
782			f_show_err "$msg_invalid_index_argument" "$index"
783		return $FAILURE
784	fi
785	f_dprintf "$funcname: disk=[%s] index=[%s]" "$disk" "$index"
786
787	# Check for unknown partition scheme before proceeding further
788	case "$ZFSBOOT_PARTITION_SCHEME" in
789	""|MBR|GPT*) : known good ;;
790	*)
791		f_dprintf "$funcname: %s is an unsupported partition scheme" \
792		          "$ZFSBOOT_PARTITION_SCHEME"
793		msg_error="$msg_error: $funcname" f_show_err \
794			"$msg_unsupported_partition_scheme" \
795			"$ZFSBOOT_PARTITION_SCHEME"
796		return $FAILURE
797	esac
798
799	#
800	# Destroy whatever partition layout is currently on disk.
801	# NOTE: `-F' required to destroy if partitions still exist.
802	# NOTE: Failure is ok here, blank disk will have nothing to destroy.
803	#
804	f_dprintf "$funcname: Exporting ZFS pools..."
805	zpool list -Ho name | while read z_name; do
806		f_eval_catch -d $funcname zpool "$ZPOOL_EXPORT_F" $z_name
807	done
808	f_dprintf "$funcname: Detaching all GELI providers..."
809	geli status | tail -n +2 | while read g_name g_status g_component; do
810		f_eval_catch -d $funcname geli "$GELI_DETACH_F" $g_name
811	done
812	f_dprintf "$funcname: Destroying all data/layouts on \`%s'..." "$disk"
813	f_eval_catch -d $funcname gpart "$GPART_DESTROY_F" $disk
814	f_eval_catch -d $funcname graid "$GRAID_DELETE" $disk
815	f_eval_catch -d $funcname zpool "$ZPOOL_LABELCLEAR_F" /dev/$disk
816
817	# Make doubly-sure backup GPT is destroyed
818	f_eval_catch -d $funcname gpart "$GPART_CREATE" gpt $disk
819	f_eval_catch -d $funcname gpart "$GPART_DESTROY_F" $disk
820
821	#
822	# Lay down the desired type of partition scheme
823	#
824	local setsize mbrindex align_small align_big
825	#
826	# If user has requested 4 K alignment, add these params to the
827	# gpart add calls. With GPT, we align large partitions to 1 M for
828	# improved performance on SSDs. MBR does not always play well with gaps
829	# between partitions, so all alignment is only 4k for that case.
830	# With MBR, we align the BSD partition that contains the MBR, otherwise
831	# the system fails to boot.
832	#
833	if [ "$ZFSBOOT_FORCE_4K_SECTORS" ]; then
834		align_small="-a 4k"
835		align_big="-a 1m"
836	fi
837
838	case "$ZFSBOOT_PARTITION_SCHEME" in
839	""|GPT*) f_dprintf "$funcname: Creating GPT layout..."
840		#
841		# 1. Create GPT layout using labels
842		#
843		f_eval_catch $funcname gpart "$GPART_CREATE" gpt $disk ||
844		             return $FAILURE
845
846		#
847		# Apply workarounds if requested by the user
848		#
849		if [ "$ZFSBOOT_PARTITION_SCHEME" = "GPT + Lenovo Fix" ]; then
850			f_eval_catch $funcname gpart "$GPART_SET_LENOVOFIX" \
851			             $disk || return $FAILURE
852		elif [ "$ZFSBOOT_PARTITION_SCHEME" = "GPT + Active" ]; then
853			f_eval_catch $funcname gpart "$GPART_SET_PMBR_ACTIVE" \
854			             $disk || return $FAILURE
855		fi
856
857		#
858		# 2. Add small freebsd-boot and/or efi partition
859		#
860		if [ "$ZFSBOOT_BOOT_TYPE" = "UEFI" -o \
861		     "$ZFSBOOT_BOOT_TYPE" = "BIOS+UEFI" ]
862		then
863			f_eval_catch -k justaddedpart $funcname gpart \
864			             "$GPART_ADD_ALIGN_LABEL_WITH_SIZE" \
865			             "$align_small" efiboot$index efi 260M \
866			             $disk || return $FAILURE
867
868			# We'll configure the ESP in bootconfig
869			if [ -z "$efibootpart" ]; then
870				efibootpart="/dev/gpt/efiboot$index"
871				f_dprintf "$funcname: configuring ESP at [%s]" \
872				          "${efibootpart}"
873
874				f_eval_catch $funcname newfs_msdos "$NEWFS_ESP"\
875				             "$efibootpart" \
876				             || return $FAILURE
877				f_eval_catch $funcname printf "$PRINTF_FSTAB" \
878					     $efibootpart /boot/efi msdosfs \
879				             rw 2 2 "$BSDINSTALL_TMPETC/fstab" \
880				             || return $FAILURE
881			fi
882		fi
883
884		if [ "$ZFSBOOT_BOOT_TYPE" = "BIOS" -o \
885		     "$ZFSBOOT_BOOT_TYPE" = "BIOS+UEFI" ]
886		then
887			f_eval_catch $funcname gpart \
888			             "$GPART_ADD_ALIGN_LABEL_WITH_SIZE" \
889			             "$align_small" gptboot$index \
890			             freebsd-boot 512k $disk || return $FAILURE
891			if [ "$ZFSBOOT_BOOT_TYPE" = "BIOS" ]; then
892				f_eval_catch $funcname gpart \
893				             "$GPART_BOOTCODE_PART" \
894				             /boot/pmbr /boot/gptzfsboot 1 \
895				             $disk || return $FAILURE
896			else
897				f_eval_catch $funcname gpart \
898				             "$GPART_BOOTCODE_PART" \
899				             /boot/pmbr /boot/gptzfsboot 2 \
900				             $disk || return $FAILURE
901			fi
902		fi
903
904		# NB: zpool will use the `zfs#' GPT labels
905		if [ "$ZFSBOOT_BOOT_TYPE" = "BIOS+UEFI" ]; then
906			if [ "$ZFSBOOT_BOOT_POOL" ]; then
907				bootpart=p3 swappart=p4 targetpart=p4
908				[ ${swapsize:-0} -gt 0 ] && targetpart=p5
909			else
910				# Bootpart unused
911				bootpart=p3 swappart=p3 targetpart=p3
912				[ ${swapsize:-0} -gt 0 ] && targetpart=p4
913			fi
914		else
915			if [ "$ZFSBOOT_BOOT_POOL" ]; then
916				bootpart=p2 swappart=p3 targetpart=p3
917				[ ${swapsize:-0} -gt 0 ] && targetpart=p4
918			else
919				# Bootpart unused
920				bootpart=p2 swappart=p2 targetpart=p2
921				[ ${swapsize:-0} -gt 0 ] && targetpart=p3
922			fi
923		fi
924
925		#
926		# Prepare boot pool if enabled (e.g., for geli(8))
927		#
928		if [ "$ZFSBOOT_BOOT_POOL" ]; then
929			f_eval_catch $funcname gpart \
930			             "$GPART_ADD_ALIGN_LABEL_WITH_SIZE" \
931			             "$align_big" boot$index freebsd-zfs \
932			             ${bootsize}b $disk || return $FAILURE
933			# Pedantically nuke any old labels
934			f_eval_catch -d $funcname zpool "$ZPOOL_LABELCLEAR_F" \
935			                /dev/$disk$bootpart
936			if [ "$ZFSBOOT_GELI_ENCRYPTION" ]; then
937				# Pedantically detach targetpart for later
938				f_eval_catch -d $funcname geli \
939				                "$GELI_DETACH_F" \
940				                /dev/$disk$targetpart
941			fi
942		fi
943
944		#
945		# 3. Add freebsd-swap partition labeled `swap#'
946		#
947		if [ ${swapsize:-0} -gt 0 ]; then
948			f_eval_catch $funcname gpart \
949			             "$GPART_ADD_ALIGN_LABEL_WITH_SIZE" \
950			             "$align_big" swap$index freebsd-swap \
951			             ${swapsize}b $disk || return $FAILURE
952			# Pedantically nuke any old labels on the swap
953			f_eval_catch -d $funcname zpool "$ZPOOL_LABELCLEAR_F" \
954			                /dev/$disk$swappart
955		fi
956
957		#
958		# 4. Add freebsd-zfs partition labeled `zfs#' for zroot
959		#
960		if [ "$ZFSBOOT_POOL_SIZE" ]; then
961			f_eval_catch $funcname gpart "$GPART_ADD_ALIGN_LABEL_WITH_SIZE" \
962					"$align_big" zfs$index freebsd-zfs $ZFSBOOT_POOL_SIZE $disk ||
963					return $FAILURE
964		else
965			f_eval_catch $funcname gpart "$GPART_ADD_ALIGN_LABEL" \
966					"$align_big" zfs$index freebsd-zfs $disk ||
967					return $FAILURE
968		fi
969		f_eval_catch -d $funcname zpool "$ZPOOL_LABELCLEAR_F" \
970		                /dev/$disk$targetpart
971		;;
972
973	MBR) f_dprintf "$funcname: Creating MBR layout..."
974		#
975		# Enable boot pool if encryption is desired
976		#
977		[ "$ZFSBOOT_GELI_ENCRYPTION" ] && ZFSBOOT_BOOT_POOL=1
978		#
979		# 1. Create MBR layout (no labels)
980		#
981		f_eval_catch $funcname gpart "$GPART_CREATE" mbr $disk ||
982		             return $FAILURE
983		f_eval_catch $funcname gpart "$GPART_BOOTCODE" /boot/mbr \
984		             $disk || return $FAILURE
985
986		#
987		# 2. Add freebsd slice with all available space
988		#
989		f_eval_catch $funcname gpart "$GPART_ADD_ALIGN" \
990		             "$align_small" freebsd $disk || return $FAILURE
991		f_eval_catch $funcname gpart "$GPART_SET_ACTIVE" 1 $disk ||
992		             return $FAILURE
993		# Pedantically nuke any old labels
994		f_eval_catch -d $funcname zpool "$ZPOOL_LABELCLEAR_F" \
995		                /dev/${disk}s1
996		# Pedantically nuke any old scheme
997		f_eval_catch -d $funcname gpart "$GPART_DESTROY_F" ${disk}s1
998
999		#
1000		# 3. Write BSD scheme to the freebsd slice
1001		#
1002		f_eval_catch $funcname gpart "$GPART_CREATE" BSD ${disk}s1 ||
1003		             return $FAILURE
1004
1005		# NB: zpool will use s1a (no labels)
1006		bootpart=s1a swappart=s1b targetpart=s1d mbrindex=4
1007
1008		#
1009		# Always prepare a boot pool on MBR
1010		# Do not align this partition, there must not be a gap
1011		#
1012		ZFSBOOT_BOOT_POOL=1
1013		f_eval_catch $funcname gpart \
1014		             "$GPART_ADD_ALIGN_INDEX_WITH_SIZE" \
1015		             "" 1 freebsd-zfs ${bootsize}b ${disk}s1 ||
1016		             return $FAILURE
1017		# Pedantically nuke any old labels
1018		f_eval_catch -d $funcname zpool "$ZPOOL_LABELCLEAR_F" \
1019		                /dev/$disk$bootpart
1020		if [ "$ZFSBOOT_GELI_ENCRYPTION" ]; then
1021			# Pedantically detach targetpart for later
1022			f_eval_catch -d $funcname geli \
1023			                "$GELI_DETACH_F" \
1024					/dev/$disk$targetpart
1025		fi
1026
1027		#
1028		# 4. Add freebsd-swap partition
1029		#
1030		if [ ${swapsize:-0} -gt 0 ]; then
1031			f_eval_catch $funcname gpart \
1032			             "$GPART_ADD_ALIGN_INDEX_WITH_SIZE" \
1033			             "$align_small" 2 freebsd-swap \
1034			             ${swapsize}b ${disk}s1 || return $FAILURE
1035			# Pedantically nuke any old labels on the swap
1036			f_eval_catch -d $funcname zpool "$ZPOOL_LABELCLEAR_F" \
1037			                /dev/${disk}s1b
1038		fi
1039
1040		#
1041		# 5. Add freebsd-zfs partition for zroot
1042		#
1043		if [ "$ZFSBOOT_POOL_SIZE" ]; then
1044			f_eval_catch $funcname gpart "$GPART_ADD_ALIGN_INDEX_WITH_SIZE" \
1045					"$align_small" $mbrindex freebsd-zfs $ZFSBOOT_POOL_SIZE ${disk}s1 || return $FAILURE
1046		else
1047			f_eval_catch $funcname gpart "$GPART_ADD_ALIGN_INDEX" \
1048					"$align_small" $mbrindex freebsd-zfs ${disk}s1 || return $FAILURE
1049		fi
1050		f_eval_catch -d $funcname zpool "$ZPOOL_LABELCLEAR_F" \
1051		                /dev/$disk$targetpart # Pedantic
1052		f_eval_catch $funcname dd "$DD_WITH_OPTIONS" \
1053		             /boot/zfsboot /dev/${disk}s1 count=1 ||
1054		             return $FAILURE
1055		;;
1056
1057	esac # $ZFSBOOT_PARTITION_SCHEME
1058
1059	# Update fstab(5)
1060	local swapsize
1061	f_expand_number "$ZFSBOOT_SWAP_SIZE" swapsize
1062	if [ "$isswapmirror" ]; then
1063		# This is not the first disk in the mirror, do nothing
1064	elif [ ${swapsize:-0} -eq 0 ]; then
1065		# If swap is 0 sized, don't add it to fstab
1066	elif [ "$ZFSBOOT_SWAP_ENCRYPTION" -a "$ZFSBOOT_SWAP_MIRROR" ]; then
1067		f_eval_catch $funcname printf "$PRINTF_FSTAB" \
1068		             /dev/mirror/swap.eli none swap sw 0 0 \
1069		             $BSDINSTALL_TMPETC/fstab || return $FAILURE
1070		isswapmirror=1
1071	elif [ "$ZFSBOOT_SWAP_MIRROR" ]; then
1072		f_eval_catch $funcname printf "$PRINTF_FSTAB" \
1073		             /dev/mirror/swap none swap sw 0 0 \
1074		             $BSDINSTALL_TMPETC/fstab || return $FAILURE
1075		isswapmirror=1
1076	elif [ "$ZFSBOOT_SWAP_ENCRYPTION" ]; then
1077		f_eval_catch $funcname printf "$PRINTF_FSTAB" \
1078		             /dev/$disk${swappart}.eli none swap sw 0 0 \
1079		             $BSDINSTALL_TMPETC/fstab || return $FAILURE
1080	else
1081		f_eval_catch $funcname printf "$PRINTF_FSTAB" \
1082		             /dev/$disk$swappart none swap sw 0 0 \
1083		             $BSDINSTALL_TMPETC/fstab || return $FAILURE
1084	fi
1085
1086	return $SUCCESS
1087}
1088
1089# zfs_create_boot $poolname $vdev_type $disks ...
1090#
1091# Creates boot pool and dataset layout. Returns error if something goes wrong.
1092# Errors are printed to stderr for collection and display.
1093#
1094zfs_create_boot()
1095{
1096	local funcname=zfs_create_boot
1097	local zroot_name="$1"
1098	local zroot_vdevtype="$2"
1099	local zroot_vdevs= # Calculated below
1100	local swap_devs= # Calculated below
1101	local boot_vdevs= # Used for geli(8) and/or MBR layouts
1102	shift 2 # poolname vdev_type
1103	local disks="$*" disk
1104	local isswapmirror
1105	local bootpart targetpart swappart # Set by zfs_create_diskpart() below
1106	local create_options
1107	local efibootpart
1108
1109	#
1110	# Pedantic checks; should never be seen
1111	#
1112	if [ ! "$zroot_name" ]; then
1113		f_dprintf "$funcname: NULL poolname"
1114		msg_error="$msg_error: $funcname" \
1115			f_show_err "$msg_null_poolname"
1116		return $FAILURE
1117	fi
1118	if [ $# -lt 1 ]; then
1119		f_dprintf "$funcname: missing disk arguments"
1120		msg_error="$msg_error: $funcname" \
1121			f_show_err "$msg_missing_disk_arguments"
1122		return $FAILURE
1123	fi
1124	f_dprintf "$funcname: poolname=[%s] vdev_type=[%s]" \
1125	          "$zroot_name" "$zroot_vdevtype"
1126
1127	#
1128	# Initialize fstab(5)
1129	#
1130	f_dprintf "$funcname: Initializing temporary fstab(5) file..."
1131	f_eval_catch $funcname sh "$SHELL_TRUNCATE" $BSDINSTALL_TMPETC/fstab ||
1132	             return $FAILURE
1133	f_eval_catch $funcname printf "$PRINTF_FSTAB" \
1134	             "# Device" Mountpoint FStype Options Dump "Pass#" \
1135	             $BSDINSTALL_TMPETC/fstab || return $FAILURE
1136
1137	#
1138	# Expand SI units in desired sizes
1139	#
1140	f_dprintf "$funcname: Expanding supplied size values..."
1141	local swapsize bootsize poolsize
1142	if ! f_expand_number "$ZFSBOOT_SWAP_SIZE" swapsize; then
1143		f_dprintf "$funcname: Invalid swap size \`%s'" \
1144		          "$ZFSBOOT_SWAP_SIZE"
1145		f_show_err "$msg_invalid_swap_size" "$ZFSBOOT_SWAP_SIZE"
1146		return $FAILURE
1147	fi
1148	if ! f_expand_number "$ZFSBOOT_BOOT_POOL_SIZE" bootsize; then
1149		f_dprintf "$funcname: Invalid boot pool size \`%s'" \
1150		          "$ZFSBOOT_BOOT_POOL_SIZE"
1151		f_show_err "$msg_invalid_boot_pool_size" \
1152		           "$ZFSBOOT_BOOT_POOL_SIZE"
1153		return $FAILURE
1154	fi
1155	if [ "$ZFSBOOT_POOL_SIZE" ]; then
1156		if ! f_expand_number "$ZFSBOOT_POOL_SIZE" poolsize; then
1157			f_dprintf "$funcname: Invalid pool size \`%s'" \
1158				  "$ZFSBOOT_POOL_SIZE"
1159			f_show_err "$msg_invalid_pool_size" \
1160				   "$ZFSBOOT_POOL_SIZE"
1161		fi
1162		f_dprintf "$funcname: ZFSBOOT_POOL_SIZE=[%s] poolsize=[%s]" \
1163			  "$ZFSBOOT_POOL_SIZE" "$poolsize"
1164	fi
1165	f_dprintf "$funcname: ZFSBOOT_SWAP_SIZE=[%s] swapsize=[%s]" \
1166	          "$ZFSBOOT_SWAP_SIZE" "$swapsize"
1167	f_dprintf "$funcname: ZFSBOOT_BOOT_POOL_SIZE=[%s] bootsize=[%s]" \
1168	          "$ZFSBOOT_BOOT_POOL_SIZE" "$bootsize"
1169
1170	#
1171	# Destroy the pool in-case this is our second time 'round (case of
1172	# failure and installer presented ``Retry'' option to come back).
1173	#
1174	# NB: If we don't destroy the pool, later gpart(8) destroy commands
1175	# that try to clear existing partitions (see zfs_create_diskpart())
1176	# will fail with a `Device Busy' error, leading to `GEOM exists'.
1177	#
1178	f_eval_catch -d $funcname zpool "$ZPOOL_DESTROY" "$zroot_name"
1179
1180	#
1181	# Prepare the disks and build pool device list(s)
1182	#
1183	f_dprintf "$funcname: Preparing disk partitions for ZFS pool..."
1184
1185	# Force 4K sectors using vfs.zfs.min_auto_ashift=12
1186	if [ "$ZFSBOOT_FORCE_4K_SECTORS" ]; then
1187		f_dprintf "$funcname: With 4K sectors..."
1188		f_eval_catch $funcname sysctl "$SYSCTL_ZFS_MIN_ASHIFT_12" \
1189		    || return $FAILURE
1190		sysctl kern.geom.part.mbr.enforce_chs=0
1191	fi
1192	local n=0
1193	for disk in $disks; do
1194		zfs_create_diskpart $disk $n || return $FAILURE
1195		# Now $bootpart, $targetpart, and $swappart are set (suffix
1196		# for $disk)
1197		if [ "$ZFSBOOT_BOOT_POOL" ]; then
1198			boot_vdevs="$boot_vdevs $disk$bootpart"
1199		fi
1200		zroot_vdevs="$zroot_vdevs $disk$targetpart"
1201		if [ "$ZFSBOOT_GELI_ENCRYPTION" ]; then
1202			zroot_vdevs="$zroot_vdevs.eli"
1203		fi
1204
1205		n=$(( $n + 1 ))
1206	done # disks
1207
1208	#
1209	# If we need/want a boot pool, create it
1210	#
1211	if [ "$ZFSBOOT_BOOT_POOL" ]; then
1212		local bootpool_vdevtype= # Calculated below
1213		local bootpool_options= # Calculated below
1214		local bootpool_name="$ZFSBOOT_BOOT_POOL_NAME"
1215		local bootpool="$BSDINSTALL_CHROOT/$bootpool_name"
1216		local zroot_key="${ZFSBOOT_GELI_KEY_FILE#/}"
1217
1218		f_dprintf "$funcname: Setting up boot pool..."
1219		[ "$ZFSBOOT_GELI_ENCRYPTION" ] &&
1220			f_dprintf "$funcname: For encrypted root disk..."
1221
1222		# Create parent directory for boot pool
1223		f_eval_catch -d $funcname umount "$UMOUNT" "$BSDINSTALL_CHROOT"
1224		f_eval_catch $funcname mount "$MOUNT_TYPE" tmpfs none \
1225		             $BSDINSTALL_CHROOT || return $FAILURE
1226
1227		# Create mirror across the boot partition on all disks
1228		local nvdevs
1229		f_count nvdevs $boot_vdevs
1230		[ $nvdevs -gt 1 ] && bootpool_vdevtype=mirror
1231
1232		create_options="$ZFSBOOT_BOOT_POOL_CREATE_OPTIONS"
1233		bootpool_options="-o altroot=$BSDINSTALL_CHROOT"
1234		bootpool_options="$bootpool_options $create_options"
1235		bootpool_options="$bootpool_options -m \"/$bootpool_name\" -f"
1236		f_eval_catch $funcname zpool "$ZPOOL_CREATE_WITH_OPTIONS" \
1237		             "$bootpool_options" "$bootpool_name" \
1238		             "$bootpool_vdevtype" "$boot_vdevs" ||
1239		             return $FAILURE
1240
1241		f_eval_catch $funcname mkdir "$MKDIR_P" "$bootpool/boot" ||
1242		             return $FAILURE
1243
1244		if [ "$ZFSBOOT_GELI_ENCRYPTION" ]; then
1245			# Generate an encryption key using random(4)
1246			f_eval_catch $funcname dd "$DD_WITH_OPTIONS" \
1247			             /dev/random "$bootpool/$zroot_key" \
1248			             "bs=4096 count=1" || return $FAILURE
1249			f_eval_catch $funcname chmod "$CHMOD_MODE" \
1250			             go-wrx "$bootpool/$zroot_key" ||
1251			             return $FAILURE
1252		fi
1253
1254	fi
1255
1256	#
1257	# Create the geli(8) GEOMS
1258	#
1259	if [ "$ZFSBOOT_GELI_ENCRYPTION" ]; then
1260		#
1261		# Load the AES-NI kernel module to accelerate encryption
1262		#
1263		f_eval_catch -d $funcname kldload "$KLDLOAD" "aesni"
1264		# Prompt user for password (twice)
1265		if ! msg_enter_new_password="$msg_geli_password" \
1266			f_dialog_input_password
1267		then
1268			f_dprintf "$funcname: User cancelled"
1269			f_show_err "$msg_user_cancelled"
1270			return $FAILURE
1271		fi
1272
1273		# Initialize geli(8) on each of the target partitions
1274		for disk in $disks; do
1275			f_dialog_info "$msg_geli_setup" \
1276				2>&1 >&$DIALOG_TERMINAL_PASSTHRU_FD
1277			if [ "$ZFSBOOT_BOOT_POOL" ]; then
1278				if ! echo "$pw_password" | f_eval_catch \
1279					$funcname geli "$GELI_PASSWORD_INIT" \
1280					"$bootpool/boot/$disk$targetpart.eli" \
1281					AES-XTS "$bootpool/$zroot_key" \
1282					$disk$targetpart
1283				then
1284					f_interactive || f_die
1285					unset pw_password # Sensitive info
1286					return $FAILURE
1287				fi
1288				if ! echo "$pw_password" | f_eval_catch \
1289					$funcname geli "$GELI_ATTACH" \
1290					"$bootpool/$zroot_key" $disk$targetpart
1291				then
1292					f_interactive || f_die
1293					unset pw_password # Sensitive info
1294					return $FAILURE
1295				fi
1296			else
1297				# With no bootpool, there is no place to store
1298				# the key files, use only a password
1299				if ! echo "$pw_password" | f_eval_catch \
1300					$funcname geli \
1301					"$GELI_PASSWORD_GELIBOOT_INIT" \
1302					AES-XTS $disk$targetpart
1303				then
1304					f_interactive || f_die
1305					unset pw_password # Sensitive info
1306					return $FAILURE
1307				fi
1308				if ! echo "$pw_password" | f_eval_catch \
1309					$funcname geli "$GELI_ATTACH_NOKEY" \
1310					$disk$targetpart
1311				then
1312					f_interactive || f_die
1313					unset pw_password # Sensitive info
1314					return $FAILURE
1315				fi
1316			fi
1317		done
1318		unset pw_password # Sensitive info
1319	fi
1320
1321	if [ "$ZFSBOOT_BOOT_POOL" ]; then
1322		# Clean up
1323		f_eval_catch $funcname zfs "$ZFS_UNMOUNT" "$bootpool_name" ||
1324			return $FAILURE
1325		# tmpfs
1326		f_eval_catch -d $funcname umount "$UMOUNT" "$BSDINSTALL_CHROOT"
1327	fi
1328
1329	#
1330	# Create the gmirror(8) GEOMS for swap
1331	#
1332	if [ ${swapsize:-0} -gt 0 -a "$ZFSBOOT_SWAP_MIRROR" ]; then
1333		for disk in $disks; do
1334			swap_devs="$swap_devs $disk$swappart"
1335		done
1336		f_eval_catch $funcname gmirror "$SWAP_GMIRROR_LABEL" \
1337			"$swap_devs" || return $FAILURE
1338	fi
1339
1340	#
1341	# Create the ZFS root pool with desired type and disk devices
1342	#
1343	f_dprintf "$funcname: Creating root pool..."
1344	create_options="$ZFSBOOT_POOL_CREATE_OPTIONS"
1345	if [ "$zroot_vdevtype" == "raid10" ]; then
1346		raid10_vdevs=""
1347		for vdev in $zroot_vdevs; do
1348			f_count nvdev $raid10_vdevs
1349			if [ $(( $nvdev % 3 )) -eq 0 ]; then
1350				raid10_vdevs="$raid10_vdevs mirror"
1351			fi
1352			raid10_vdevs="$raid10_vdevs $vdev"
1353		done
1354		f_eval_catch $funcname zpool "$ZPOOL_CREATE_WITH_OPTIONS" \
1355			"-o altroot=$BSDINSTALL_CHROOT $create_options -m none -f" \
1356			"$zroot_name" "" "$raid10_vdevs" || return $FAILURE
1357	else
1358		f_eval_catch $funcname zpool "$ZPOOL_CREATE_WITH_OPTIONS" \
1359			"-o altroot=$BSDINSTALL_CHROOT $create_options -m none -f" \
1360			"$zroot_name" "$zroot_vdevtype" "$zroot_vdevs" ||
1361			return $FAILURE
1362	fi
1363
1364	#
1365	# Create ZFS dataset layout within the new root pool
1366	#
1367	f_dprintf "$funcname: Creating ZFS datasets..."
1368	echo "$ZFSBOOT_DATASETS" | while read dataset options; do
1369		# Skip blank lines and comments
1370		case "$dataset" in "#"*|"") continue; esac
1371		# Remove potential inline comments in options
1372		options="${options%%#*}"
1373		# Replace tabs with spaces
1374		f_replaceall "$options" "	" " " options
1375		# Reduce contiguous runs of space to one single space
1376		oldoptions=
1377		while [ "$oldoptions" != "$options" ]; do
1378			oldoptions="$options"
1379			f_replaceall "$options" "  " " " options
1380		done
1381		# Replace both commas and spaces with ` -o '
1382		f_replaceall "$options" "[ ,]" " -o " options
1383		# Create the dataset with desired options
1384		f_eval_catch $funcname zfs "$ZFS_CREATE_WITH_OPTIONS" \
1385		             "${options:+-o $options}" "$zroot_name$dataset" ||
1386		             return $FAILURE
1387	done
1388
1389	#
1390	# Set a mountpoint for the root of the pool so newly created datasets
1391	# have a mountpoint to inherit
1392	#
1393	f_dprintf "$funcname: Setting mountpoint for root of the pool..."
1394	f_eval_catch $funcname zfs "$ZFS_SET" \
1395		"mountpoint=/$zroot_name" "$zroot_name" || return $FAILURE
1396
1397	# Touch up permissions on the tmp directories
1398	f_dprintf "$funcname: Modifying directory permissions..."
1399	local dir
1400	for dir in /tmp /var/tmp; do
1401		f_eval_catch $funcname mkdir "$MKDIR_P" \
1402		             $BSDINSTALL_CHROOT$dir || return $FAILURE
1403		f_eval_catch $funcname chmod "$CHMOD_MODE" 1777 \
1404		             $BSDINSTALL_CHROOT$dir || return $FAILURE
1405	done
1406
1407	# Set bootfs property
1408	local zroot_bootfs="$ZFSBOOT_BEROOT_NAME/$ZFSBOOT_BOOTFS_NAME"
1409	f_dprintf "$funcname: Setting bootfs property..."
1410	f_eval_catch $funcname zpool "$ZPOOL_SET" \
1411		"bootfs=\"$zroot_name/$zroot_bootfs\"" "$zroot_name" ||
1412		return $FAILURE
1413
1414	# MBR boot loader touch-up
1415	if [ "$ZFSBOOT_PARTITION_SCHEME" = "MBR" ]; then
1416		# Export the pool(s)
1417		f_dprintf "$funcname: Temporarily exporting ZFS pool(s)..."
1418		f_eval_catch $funcname zpool "$ZPOOL_EXPORT" "$zroot_name" ||
1419			     return $FAILURE
1420		if [ "$ZFSBOOT_BOOT_POOL" ]; then
1421			f_eval_catch $funcname zpool "$ZPOOL_EXPORT" \
1422				     "$bootpool_name" || return $FAILURE
1423		fi
1424
1425		f_dprintf "$funcname: Updating MBR boot loader on disks..."
1426		# Stick the ZFS boot loader in the "convenient hole" after
1427		# the ZFS internal metadata
1428		for disk in $disks; do
1429			f_eval_catch $funcname dd "$DD_WITH_OPTIONS" \
1430			             /boot/zfsboot /dev/$disk$bootpart \
1431			             "skip=1 seek=1024" || return $FAILURE
1432		done
1433
1434		# Re-import the ZFS pool(s)
1435		f_dprintf "$funcname: Re-importing ZFS pool(s)..."
1436		f_eval_catch $funcname zpool "$ZPOOL_IMPORT_WITH_OPTIONS" \
1437			     "-o altroot=\"$BSDINSTALL_CHROOT\"" \
1438			     "$zroot_name" || return $FAILURE
1439		if [ "$ZFSBOOT_BOOT_POOL" ]; then
1440			# Import the bootpool, but do not mount it yet
1441			f_eval_catch $funcname zpool \
1442				     "$ZPOOL_IMPORT_WITH_OPTIONS" \
1443				     "-o altroot=\"$BSDINSTALL_CHROOT\" -N" \
1444				     "$bootpool_name" || return $FAILURE
1445		fi
1446	fi
1447
1448	# Remount bootpool and create symlink(s)
1449	if [ "$ZFSBOOT_BOOT_POOL" ]; then
1450		f_eval_catch $funcname zfs "$ZFS_MOUNT" "$bootpool_name" ||
1451			return $FAILURE
1452		f_dprintf "$funcname: Creating /boot symlink for boot pool..."
1453		f_eval_catch $funcname ln "$LN_SF" "$bootpool_name/boot" \
1454		             $BSDINSTALL_CHROOT/boot || return $FAILURE
1455	fi
1456
1457	# zpool.cache is required to mount more than one pool at boot time
1458	f_dprintf "$funcname: Configuring zpool.cache for zroot..."
1459	f_eval_catch $funcname mkdir "$MKDIR_P" $BSDINSTALL_CHROOT/boot/zfs ||
1460	             return $FAILURE
1461	f_eval_catch $funcname zpool "$ZPOOL_SET" \
1462	             "cachefile=\"$BSDINSTALL_CHROOT/boot/zfs/zpool.cache\"" \
1463	             "$zroot_name" || return $FAILURE
1464
1465	if [ "$ZFSBOOT_BOOT_POOL" ]; then
1466		f_eval_catch $funcname printf "$PRINTF_CONF" \
1467			vfs.root.mountfrom \
1468			"\"zfs:$zroot_name/$zroot_bootfs\"" \
1469			$BSDINSTALL_TMPBOOT/loader.conf.root || return $FAILURE
1470	fi
1471	#
1472	# Set canmount=noauto so that the default Boot Environment (BE) does
1473	# not get mounted if a different BE is selected from the beastie menu
1474	#
1475	f_dprintf "$funcname: Set canmount=noauto for any datasets under the BE..."
1476	echo "$ZFSBOOT_DATASETS" | while read dataset options; do
1477		# Skip blank lines and comments
1478		case "$dataset" in "#"*|"") continue; esac
1479		options="${options%%#*}"
1480		#
1481		case "$dataset" in "/$ZFSBOOT_BEROOT_NAME/$ZFSBOOT_BOOTFS_NAME"*)
1482			f_eval_catch $funcname zfs "$ZFS_SET" "canmount=noauto" \
1483				"$zroot_name$dataset" || return $FAILURE ;;
1484		*) continue ;;
1485		esac
1486	done
1487
1488	# Last, but not least... required lines for rc.conf(5)/loader.conf(5)
1489	# NOTE: We later concatenate these into their destination
1490	f_dprintf "%s: Configuring rc.conf(5)/loader.conf(5) additions..." \
1491	          "$funcname"
1492	f_eval_catch $funcname echo "$ECHO_APPEND" 'zfs_enable=\"YES\"' \
1493	             $BSDINSTALL_TMPETC/rc.conf.zfs || return $FAILURE
1494	f_eval_catch $funcname echo "$ECHO_APPEND" \
1495	             'kern.geom.label.disk_ident.enable=\"0\"' \
1496	             $BSDINSTALL_TMPBOOT/loader.conf.zfs || return $FAILURE
1497	f_eval_catch $funcname echo "$ECHO_APPEND" \
1498	             'kern.geom.label.gptid.enable=\"0\"' \
1499	             $BSDINSTALL_TMPBOOT/loader.conf.zfs || return $FAILURE
1500
1501	if [ "$ZFSBOOT_FORCE_4K_SECTORS" ]; then
1502		f_eval_catch $funcname echo "$ECHO_APPEND" \
1503	             'vfs.zfs.min_auto_ashift=12' \
1504	             $BSDINSTALL_TMPETC/sysctl.conf.zfs || return $FAILURE
1505	fi
1506
1507	if [ "$ZFSBOOT_SWAP_MIRROR" ]; then
1508		f_eval_catch $funcname echo "$ECHO_APPEND" \
1509		             'geom_mirror_load=\"YES\"' \
1510		             $BSDINSTALL_TMPBOOT/loader.conf.gmirror ||
1511		             return $FAILURE
1512	fi
1513
1514	# We're all done unless we should go on to do encryption
1515	[ "$ZFSBOOT_GELI_ENCRYPTION" ] || return $SUCCESS
1516
1517	#
1518	# Configure geli(8)-based encryption
1519	#
1520	f_dprintf "$funcname: Configuring disk encryption..."
1521	f_eval_catch $funcname echo "$ECHO_APPEND" 'aesni_load=\"YES\"' \
1522		$BSDINSTALL_TMPBOOT/loader.conf.aesni || return $FAILURE
1523	f_eval_catch $funcname echo "$ECHO_APPEND" 'geom_eli_load=\"YES\"' \
1524		$BSDINSTALL_TMPBOOT/loader.conf.geli || return $FAILURE
1525
1526	# We're all done unless we should go on for boot pool
1527	[ "$ZFSBOOT_BOOT_POOL" ] || return $SUCCESS
1528
1529	for disk in $disks; do
1530		f_eval_catch $funcname printf "$PRINTF_CONF" \
1531			geli_%s_keyfile0_load "$disk$targetpart YES" \
1532			$BSDINSTALL_TMPBOOT/loader.conf.$disk$targetpart ||
1533			return $FAILURE
1534		f_eval_catch $funcname printf "$PRINTF_CONF" \
1535			geli_%s_keyfile0_type \
1536			"$disk$targetpart $disk$targetpart:geli_keyfile0" \
1537			$BSDINSTALL_TMPBOOT/loader.conf.$disk$targetpart ||
1538			return $FAILURE
1539		f_eval_catch $funcname printf "$PRINTF_CONF" \
1540			geli_%s_keyfile0_name \
1541			"$disk$targetpart \"$ZFSBOOT_GELI_KEY_FILE\"" \
1542			$BSDINSTALL_TMPBOOT/loader.conf.$disk$targetpart ||
1543			return $FAILURE
1544	done
1545
1546	# Set cachefile for boot pool so it auto-imports at system start
1547	f_dprintf "$funcname: Configuring zpool.cache for boot pool..."
1548	f_eval_catch $funcname zpool "$ZPOOL_SET" \
1549	             "cachefile=\"$BSDINSTALL_CHROOT/boot/zfs/zpool.cache\"" \
1550	             "$bootpool_name" || return $FAILURE
1551
1552	# Some additional geli(8) requirements for loader.conf(5)
1553	for option in \
1554		'zpool_cache_load=\"YES\"' \
1555		'zpool_cache_type=\"/boot/zfs/zpool.cache\"' \
1556		'zpool_cache_name=\"/boot/zfs/zpool.cache\"' \
1557		'geom_eli_passphrase_prompt=\"YES\"' \
1558	; do
1559		f_eval_catch $funcname echo "$ECHO_APPEND" "$option" \
1560		             $BSDINSTALL_TMPBOOT/loader.conf.zfs ||
1561		             return $FAILURE
1562	done
1563	return $SUCCESS
1564}
1565
1566# dialog_menu_diskinfo
1567#
1568# Prompt the user to select a disk and then provide detailed info on it.
1569#
1570dialog_menu_diskinfo()
1571{
1572	local device disk
1573
1574	#
1575	# Break from loop when user cancels disk selection
1576	#
1577	while :; do
1578		device=$( msg_cancel="$msg_back" f_device_menu \
1579			"$DIALOG_TITLE" "$msg_select_a_disk_device" "" \
1580			$DEVICE_TYPE_DISK 2>&1 ) || break
1581		$device get name disk
1582
1583		# Show gpart(8) `show' and camcontrol(8) `inquiry' data
1584		f_show_msg "$msg_detailed_disk_info" \
1585			"$disk" "$( gpart show $disk 2> /dev/null )" \
1586			"$disk" "$( camcontrol inquiry $disk 2> /dev/null )" \
1587			"$disk" "$( camcontrol identify $disk 2> /dev/null )"
1588	done
1589
1590	return $SUCCESS
1591}
1592
1593dialog_zpool_name()
1594{
1595	local prompt="$* is already taken, please enter a name for the ZFS pool \
1596	(Or confirm using the same name by just pressing enter)"
1597	local hline=
1598	local value="$*"
1599	local height width
1600
1601	f_dialog_inputbox_size height width \
1602		"$DIALOG_TITLE" "$DIALOG_BACKTITLE" "$prompt" "$value" "$hline"
1603
1604	$DIALOG \
1605		--title "$DIALOG_TITLE"         \
1606		--backtitle "$DIALOG_BACKTITLE" \
1607		--hline "$hline"                \
1608		--ok-label "Ok"                 \
1609		--no-cancel                     \
1610		--inputbox "$prompt"            \
1611		$height $width "$value"         \
1612		2>&1 >&$DIALOG_TERMINAL_PASSTHRU_FD
1613}
1614
1615############################################################ MAIN
1616
1617#
1618# Initialize
1619#
1620f_dialog_title "$msg_zfs_configuration"
1621f_dialog_backtitle "$msg_freebsd_installer"
1622
1623# User may have specifically requested ZFS-related operations be interactive
1624! f_interactive && f_zfsinteractive && unset $VAR_NONINTERACTIVE
1625
1626#
1627# Debugging
1628#
1629f_dprintf "BSDINSTALL_CHROOT=[%s]" "$BSDINSTALL_CHROOT"
1630f_dprintf "BSDINSTALL_TMPETC=[%s]" "$BSDINSTALL_TMPETC"
1631f_dprintf "FSTAB_FMT=[%s]" "$FSTAB_FMT"
1632
1633pools=$(zpool import | awk '$1 == "pool:" { print $2}')
1634for pool in ${pools}; do
1635	f_dprintf "Checking ${pool} against ${ZFSBOOT_POOL_NAME}"
1636	if [ "${pool}" = "${ZFSBOOT_POOL_NAME}" ]; then
1637		f_dprintf "Pool ${pool} already taken"
1638		ZFSBOOT_POOL_NAME=$(dialog_zpool_name "${ZFSBOOT_POOL_NAME}")
1639		break
1640	fi
1641done
1642
1643#
1644# Determine default boot type
1645#
1646case $(uname -m) in
1647arm64|riscv)
1648	# We support only UEFI boot for arm64 and riscv.
1649	: ${ZFSBOOT_BOOT_TYPE:=UEFI}
1650	: ${ZFSBOOT_PARTITION_SCHEME:=GPT}
1651	;;
1652*)
1653	# If the system was booted with UEFI, set the default boot type to UEFI
1654	bootmethod=$( sysctl -n machdep.bootmethod )
1655	f_dprintf "machdep.bootmethod=[%s]" "$bootmethod"
1656	if [ "$bootmethod" = "UEFI" ]; then
1657		: ${ZFSBOOT_BOOT_TYPE:=BIOS+UEFI}
1658		: ${ZFSBOOT_PARTITION_SCHEME:=GPT}
1659	else
1660		: ${ZFSBOOT_BOOT_TYPE:=BIOS}
1661		: ${ZFSBOOT_PARTITION_SCHEME:=GPT}
1662	fi
1663	;;
1664esac
1665
1666#
1667# Loop over the main menu until we've accomplished what we came here to do
1668#
1669while :; do
1670	if ! f_interactive; then
1671		retval=$DIALOG_OK
1672		mtag=">>> $msg_install"
1673	else
1674		dialog_menu_main
1675		retval=$?
1676		f_dialog_menutag_fetch mtag
1677	fi
1678
1679	f_dprintf "retval=%u mtag=[%s]" $retval "$mtag"
1680	[ $retval -eq $DIALOG_OK ] || f_die
1681
1682	case "$mtag" in
1683	">>> $msg_install")
1684		#
1685		# First, validate the user's selections
1686		#
1687
1688		# Make sure they gave us a name for the pool
1689		if [ ! "$ZFSBOOT_POOL_NAME" ]; then
1690			f_dprintf "Pool name cannot be empty."
1691			f_show_err "$msg_pool_name_cannot_be_empty"
1692			continue
1693		fi
1694
1695		# Validate vdev type against number of disks selected/scripted
1696		# (also validates that ZFSBOOT_DISKS are real [probed] disks)
1697		# NB: dialog_menu_layout supports running non-interactively
1698		dialog_menu_layout || continue
1699
1700		# Make sure each disk will have room for ZFS
1701		if f_expand_number "$ZFSBOOT_SWAP_SIZE" swapsize &&
1702		   f_expand_number "$ZFSBOOT_BOOT_POOL_SIZE" bootsize &&
1703		   f_expand_number "1g" zpoolmin
1704		then
1705			minsize=$swapsize teeny_disks=
1706			if [ "$ZFSBOOT_POOL_SIZE" ]; then
1707				f_expand_number "$ZFSBOOT_POOL_SIZE" poolsize
1708				minsize=$(( $minsize + $poolsize ))
1709			fi
1710			[ "$ZFSBOOT_BOOT_POOL" ] &&
1711				minsize=$(( $minsize + $bootsize ))
1712			for disk in $ZFSBOOT_DISKS; do
1713				debug= f_device_find -1 \
1714					$disk $DEVICE_TYPE_DISK device
1715				$device get capacity disksize || continue
1716				[ ${disksize:-0} -ge 0 ] || disksize=0
1717				[ $disksize -lt $minsize ] &&
1718					teeny_disks="$teeny_disks $disk"
1719			done
1720			if [ "$teeny_disks" ]; then
1721				f_dprintf "swapsize=[%s] bootsize[%s] %s" \
1722				          "$ZFSBOOT_SWAP_SIZE" \
1723				          "$ZFSBOOT_BOOT_POOL_SIZE" \
1724				          "minsize=[$minsize]"
1725				f_dprintf "These disks are too small: %s" \
1726				          "$teeny_disks"
1727				f_show_err "$msg_these_disks_are_too_small" \
1728				           "$ZFSBOOT_SWAP_SIZE" \
1729				           "$ZFSBOOT_BOOT_POOL_SIZE" \
1730				           "$teeny_disks"
1731				continue
1732			fi
1733		fi
1734
1735		#
1736		# Last Chance!
1737		#
1738		if f_interactive; then
1739			dialog_last_chance $ZFSBOOT_DISKS || continue
1740		fi
1741
1742		#
1743		# Let's do this
1744		#
1745
1746		vdev_type="$ZFSBOOT_VDEV_TYPE"
1747
1748		# Blank the vdev type for the default layout
1749		[ "$vdev_type" = "stripe" ] && vdev_type=
1750
1751		zfs_create_boot "$ZFSBOOT_POOL_NAME" \
1752		                "$vdev_type" $ZFSBOOT_DISKS || continue
1753
1754		# To be reused by bootconfig
1755		echo "$ZFSBOOT_DISKS" > ${TMPDIR:-"/tmp"}/bsdinstall-zfsboot
1756
1757		break # to success
1758		;;
1759	?" $msg_pool_type_disks")
1760		ZFSBOOT_CONFIRM_LAYOUT=1
1761		dialog_menu_layout
1762		# User has poked settings, disable later confirmation
1763		ZFSBOOT_CONFIRM_LAYOUT=
1764		;;
1765	"- $msg_rescan_devices") f_device_rescan ;;
1766	"- $msg_disk_info") dialog_menu_diskinfo ;;
1767	?" $msg_pool_name")
1768		# Prompt the user to input/change the name for the new pool
1769		f_dialog_input input \
1770			"$msg_please_enter_a_name_for_your_zpool" \
1771			"$ZFSBOOT_POOL_NAME" &&
1772			ZFSBOOT_POOL_NAME="$input"
1773		;;
1774	?" $msg_force_4k_sectors")
1775		# Toggle the variable referenced both by the menu and later
1776		if [ "$ZFSBOOT_FORCE_4K_SECTORS" ]; then
1777			ZFSBOOT_FORCE_4K_SECTORS=
1778		else
1779			ZFSBOOT_FORCE_4K_SECTORS=1
1780		fi
1781		;;
1782	?" $msg_encrypt_disks")
1783		# Toggle the variable referenced both by the menu and later
1784		if [ "$ZFSBOOT_GELI_ENCRYPTION" ]; then
1785			ZFSBOOT_GELI_ENCRYPTION=
1786		else
1787			ZFSBOOT_FORCE_4K_SECTORS=1
1788			ZFSBOOT_GELI_ENCRYPTION=1
1789		fi
1790		;;
1791	?" $msg_partition_scheme")
1792		# Toggle between GPT (BIOS), GPT (UEFI) and MBR
1793		if [ "$ZFSBOOT_PARTITION_SCHEME" = "GPT" -a \
1794		     "$ZFSBOOT_BOOT_TYPE" = "BIOS" ]
1795		then
1796			ZFSBOOT_PARTITION_SCHEME="GPT"
1797			ZFSBOOT_BOOT_TYPE="UEFI"
1798		elif [ "$ZFSBOOT_PARTITION_SCHEME" = "GPT" -a \
1799		       "$ZFSBOOT_BOOT_TYPE" = "UEFI" ]
1800		then
1801			ZFSBOOT_PARTITION_SCHEME="GPT"
1802			ZFSBOOT_BOOT_TYPE="BIOS+UEFI"
1803		elif [ "$ZFSBOOT_PARTITION_SCHEME" = "GPT" ]; then
1804			ZFSBOOT_PARTITION_SCHEME="MBR"
1805			ZFSBOOT_BOOT_TYPE="BIOS"
1806		elif [ "$ZFSBOOT_PARTITION_SCHEME" = "MBR" ]; then
1807			ZFSBOOT_PARTITION_SCHEME="GPT + Active"
1808			ZFSBOOT_BOOT_TYPE="BIOS"
1809		elif [ "$ZFSBOOT_PARTITION_SCHEME" = "GPT + Active" ]; then
1810			ZFSBOOT_PARTITION_SCHEME="GPT + Lenovo Fix"
1811			ZFSBOOT_BOOT_TYPE="BIOS"
1812		else
1813			ZFSBOOT_PARTITION_SCHEME="GPT"
1814			ZFSBOOT_BOOT_TYPE="BIOS"
1815		fi
1816		;;
1817	?" $msg_swap_size")
1818		# Prompt the user to input/change the swap size for each disk
1819		while :; do
1820		    f_dialog_input input \
1821			    "$msg_please_enter_amount_of_swap_space" \
1822			    "$ZFSBOOT_SWAP_SIZE" &&
1823			    ZFSBOOT_SWAP_SIZE="${input:-0}"
1824		    if f_expand_number "$ZFSBOOT_SWAP_SIZE" swapsize
1825		    then
1826			if [ $swapsize -ne 0 -a $swapsize -lt 104857600 ]; then
1827			    f_show_err "$msg_swap_toosmall" \
1828				       "$ZFSBOOT_SWAP_SIZE"
1829			    continue
1830			else
1831			    break
1832			fi
1833		    else
1834			f_show_err "$msg_swap_invalid" \
1835				   "$ZFSBOOT_SWAP_SIZE"
1836			continue
1837		    fi
1838		done
1839		;;
1840	?" $msg_swap_mirror")
1841		# Toggle the variable referenced both by the menu and later
1842		if [ "$ZFSBOOT_SWAP_MIRROR" ]; then
1843			ZFSBOOT_SWAP_MIRROR=
1844		else
1845			ZFSBOOT_SWAP_MIRROR=1
1846		fi
1847		;;
1848	?" $msg_swap_encrypt")
1849		# Toggle the variable referenced both by the menu and later
1850		if [ "$ZFSBOOT_SWAP_ENCRYPTION" ]; then
1851			ZFSBOOT_SWAP_ENCRYPTION=
1852		else
1853			ZFSBOOT_SWAP_ENCRYPTION=1
1854		fi
1855		;;
1856	esac
1857done
1858
1859exit $SUCCESS
1860
1861################################################################################
1862# END
1863################################################################################
1864