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# $FreeBSD$
29#
30############################################################ INCLUDES
31
32BSDCFG_SHARE="/usr/share/bsdconfig"
33. $BSDCFG_SHARE/common.subr || exit 1
34f_dprintf "%s: loading includes..." "$0"
35f_include $BSDCFG_SHARE/device.subr
36f_include $BSDCFG_SHARE/dialog.subr
37f_include $BSDCFG_SHARE/password/password.subr
38f_include $BSDCFG_SHARE/variable.subr
39
40############################################################ CONFIGURATION
41
42#
43# Default name of the boot-pool
44#
45: ${ZFSBOOT_POOL_NAME:=zroot}
46
47#
48# Default pool size is optional
49#
50: ${ZFSBOOT_POOL_SIZE=}
51
52#
53# Default options to use when creating zroot pool
54#
55: ${ZFSBOOT_POOL_CREATE_OPTIONS:=-O compress=lz4 -O atime=off}
56
57#
58# Default name for the boot environment parent dataset
59#
60: ${ZFSBOOT_BEROOT_NAME:=ROOT}
61
62#
63# Default name for the primary boot environment
64#
65: ${ZFSBOOT_BOOTFS_NAME:=default}
66
67#
68# Default Virtual Device (vdev) type to create
69#
70: ${ZFSBOOT_VDEV_TYPE:=stripe}
71
72#
73# Should we use sysctl(8) vfs.zfs.min_auto_ashift=12 to force 4K sectors?
74#
75: ${ZFSBOOT_FORCE_4K_SECTORS:=1}
76
77#
78# Should we use geli(8) to encrypt the drives?
79# NB: Automatically enables ZFSBOOT_BOOT_POOL
80#
81: ${ZFSBOOT_GELI_ENCRYPTION=}
82
83#
84# Default path to the geli(8) keyfile used in drive encryption
85#
86: ${ZFSBOOT_GELI_KEY_FILE:=/boot/encryption.key}
87
88#
89# Create a separate boot pool?
90# NB: Automatically set when using geli(8) or MBR
91#
92: ${ZFSBOOT_BOOT_POOL=}
93
94#
95# Options to use when creating separate boot pool (if any)
96#
97: ${ZFSBOOT_BOOT_POOL_CREATE_OPTIONS:=}
98
99#
100# Default name for boot pool when enabled (e.g., geli(8) or MBR)
101#
102: ${ZFSBOOT_BOOT_POOL_NAME:=bootpool}
103
104#
105# Default size for boot pool when enabled (e.g., geli(8) or MBR)
106#
107: ${ZFSBOOT_BOOT_POOL_SIZE:=2g}
108
109#
110# Default disks to use (always empty unless being scripted)
111#
112: ${ZFSBOOT_DISKS:=}
113
114#
115# Default partitioning scheme to use on disks
116#
117: ${ZFSBOOT_PARTITION_SCHEME:=}
118
119#
120# Default boot type to use on disks
121#
122: ${ZFSBOOT_BOOT_TYPE:=}
123
124#
125# How much swap to put on each block device in the boot zpool
126# NOTE: Value passed to gpart(8); which supports SI unit suffixes.
127#
128: ${ZFSBOOT_SWAP_SIZE:=2g}
129
130#
131# Should we use geli(8) to encrypt the swap?
132#
133: ${ZFSBOOT_SWAP_ENCRYPTION=}
134
135#
136# Should we use gmirror(8) to mirror the swap?
137#
138: ${ZFSBOOT_SWAP_MIRROR=}
139
140#
141# Default ZFS datasets for root zpool
142#
143# NOTE: Requires /tmp, /var/tmp, /$ZFSBOOT_BOOTFS_NAME/$ZFSBOOT_BOOTFS_NAME
144# NOTE: Anything after pound/hash character [#] is ignored as a comment.
145#
146f_isset ZFSBOOT_DATASETS || ZFSBOOT_DATASETS="
147	# DATASET	OPTIONS (comma or space separated; or both)
148
149	# Boot Environment [BE] root and default boot dataset
150	/$ZFSBOOT_BEROOT_NAME				mountpoint=none
151	/$ZFSBOOT_BEROOT_NAME/$ZFSBOOT_BOOTFS_NAME	mountpoint=/
152
153	# Compress /tmp, allow exec but not setuid
154	/tmp		mountpoint=/tmp,exec=on,setuid=off
155
156	# Don't mount /usr so that 'base' files go to the BEROOT
157	/usr		mountpoint=/usr,canmount=off
158
159	# Home directories separated so they are common to all BEs
160	/usr/home	# NB: /home is a symlink to /usr/home
161
162	# Ports tree
163	/usr/ports	setuid=off
164
165	# Source tree (compressed)
166	/usr/src
167
168	# Create /var and friends
169	/var		mountpoint=/var,canmount=off
170	/var/audit	exec=off,setuid=off
171	/var/crash	exec=off,setuid=off
172	/var/log	exec=off,setuid=off
173	/var/mail	atime=on
174	/var/tmp	setuid=off
175" # END-QUOTE
176
177#
178# If interactive and the user has not explicitly chosen a vdev type or disks,
179# make the user confirm scripted/default choices when proceeding to install.
180#
181: ${ZFSBOOT_CONFIRM_LAYOUT:=1}
182
183############################################################ GLOBALS
184
185#
186# Format of a line in printf(1) syntax to add to fstab(5)
187#
188FSTAB_FMT="%s\t\t%s\t%s\t%s\t\t%s\t%s\n"
189
190#
191# Command strings for various tasks
192#
193COPY='cp "%s" "%s"'
194CHMOD_MODE='chmod %s "%s"'
195DD_WITH_OPTIONS='dd if="%s" of="%s" %s'
196ECHO_APPEND='echo "%s" >> "%s"'
197ECHO_OVERWRITE='echo "%s" > "%s"'
198GELI_ATTACH='geli attach -j - -k "%s" "%s"'
199GELI_ATTACH_NOKEY='geli attach -j - "%s"'
200GELI_DETACH_F='geli detach -f "%s"'
201GELI_PASSWORD_INIT='geli init -b -B "%s" -e %s -J - -K "%s" -l 256 -s 4096 "%s"'
202GELI_PASSWORD_GELIBOOT_INIT='geli init -bg -e %s -J - -l 256 -s 4096 "%s"'
203GPART_ADD_ALIGN='gpart add %s -t %s "%s"'
204GPART_ADD_ALIGN_INDEX='gpart add %s -i %s -t %s "%s"'
205GPART_ADD_ALIGN_INDEX_WITH_SIZE='gpart add %s -i %s -t %s -s %s "%s"'
206GPART_ADD_ALIGN_LABEL='gpart add %s -l %s -t %s "%s"'
207GPART_ADD_ALIGN_LABEL_WITH_SIZE='gpart add %s -l %s -t %s -s %s "%s"'
208GPART_BOOTCODE='gpart bootcode -b "%s" "%s"'
209GPART_BOOTCODE_PART='gpart bootcode -b "%s" -p "%s" -i %s "%s"'
210GPART_BOOTCODE_PARTONLY='gpart bootcode -p "%s" -i %s "%s"'
211GPART_CREATE='gpart create -s %s "%s"'
212GPART_DESTROY_F='gpart destroy -F "%s"'
213GPART_SET_ACTIVE='gpart set -a active -i %s "%s"'
214GPART_SET_LENOVOFIX='gpart set -a lenovofix "%s"'
215GPART_SET_PMBR_ACTIVE='gpart set -a active "%s"'
216GRAID_DELETE='graid delete "%s"'
217KLDLOAD='kldload %s'
218LN_SF='ln -sf "%s" "%s"'
219MKDIR_P='mkdir -p "%s"'
220MOUNT_TYPE='mount -t %s "%s" "%s"'
221NEWFS_ESP='newfs_msdos "%s"'
222PRINTF_CONF="printf '%s=\"%%s\"\\\n' %s >> \"%s\""
223PRINTF_FSTAB='printf "$FSTAB_FMT" "%s" "%s" "%s" "%s" "%s" "%s" >> "%s"'
224SHELL_TRUNCATE=':> "%s"'
225SWAP_GMIRROR_LABEL='gmirror label swap %s'
226SYSCTL_ZFS_MIN_ASHIFT_12='sysctl vfs.zfs.min_auto_ashift=12'
227UMOUNT='umount "%s"'
228ZFS_CREATE_WITH_OPTIONS='zfs create %s "%s"'
229ZFS_MOUNT='zfs mount "%s"'
230ZFS_SET='zfs set "%s" "%s"'
231ZFS_UNMOUNT='zfs unmount "%s"'
232ZPOOL_CREATE_WITH_OPTIONS='zpool create %s "%s" %s %s'
233ZPOOL_DESTROY='zpool destroy "%s"'
234ZPOOL_EXPORT='zpool export "%s"'
235ZPOOL_EXPORT_F='zpool export -f "%s"'
236ZPOOL_IMPORT_WITH_OPTIONS='zpool import %s "%s"'
237ZPOOL_LABELCLEAR_F='zpool labelclear -f "%s"'
238ZPOOL_SET='zpool set %s "%s"'
239
240#
241# Strings that should be moved to an i18n file and loaded with f_include_lang()
242#
243hline_alnum_arrows_punc_tab_enter="Use alnum, arrows, punctuation, TAB or ENTER"
244hline_arrows_space_tab_enter="Use arrows, SPACE, TAB or ENTER"
245hline_arrows_tab_enter="Press arrows, TAB or ENTER"
246msg_an_unknown_error_occurred="An unknown error occurred"
247msg_back="Back"
248msg_cancel="Cancel"
249msg_change_selection="Change Selection"
250msg_configure_options="Configure Options:"
251msg_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"
252msg_disk_info="Disk Info"
253msg_disk_info_help="Get detailed information on disk device(s)"
254msg_disk_plural="disks"
255msg_disk_singular="disk"
256msg_encrypt_disks="Encrypt Disks?"
257msg_encrypt_disks_help="Use geli(8) to encrypt all data partitions"
258msg_error="Error"
259msg_force_4k_sectors="Force 4K Sectors?"
260msg_force_4k_sectors_help="Align partitions to 4K sector boundries and set vfs.zfs.min_auto_ashift=12"
261msg_freebsd_installer="$OSNAME Installer"
262msg_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"
263msg_geli_setup="Initializing encryption on selected disks,\n this will take several seconds per disk"
264msg_install="Install"
265msg_install_desc="Proceed with Installation"
266msg_install_help="Create ZFS boot pool with displayed options"
267msg_invalid_boot_pool_size="Invalid boot pool size \`%s'"
268msg_invalid_disk_argument="Invalid disk argument \`%s'"
269msg_invalid_index_argument="Invalid index argument \`%s'"
270msg_invalid_pool_size="Invalid pool size \`%s'"
271msg_invalid_swap_size="Invalid swap size \`%s'"
272msg_invalid_virtual_device_type="Invalid Virtual Device type \`%s'"
273msg_last_chance_are_you_sure="Last Chance! Are you sure you want to destroy\nthe current contents of the following disks:\n\n   %s"
274msg_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'
275msg_mirror_desc="Mirror - n-Way Mirroring"
276msg_mirror_help="[2+ Disks] Mirroring provides the best performance, but the least storage"
277msg_missing_disk_arguments="missing disk arguments"
278msg_missing_one_or_more_scripted_disks="Missing one or more scripted disks!"
279msg_no="NO"
280msg_no_disks_present_to_configure="No disk(s) present to configure"
281msg_no_disks_selected="No disks selected."
282msg_not_enough_disks_selected="Not enough disks selected. (%u < %u minimum)"
283msg_null_disk_argument="NULL disk argument"
284msg_null_index_argument="NULL index argument"
285msg_null_poolname="NULL poolname"
286msg_odd_disk_selected="An even number of disks must be selected to create a RAID 1+0. (%u selected)"
287msg_ok="OK"
288msg_partition_scheme="Partition Scheme"
289msg_partition_scheme_help="Select partitioning scheme. GPT is recommended."
290msg_please_enter_a_name_for_your_zpool="Please enter a name for your zpool:"
291msg_please_enter_amount_of_swap_space="Please enter amount of swap space (SI-Unit suffixes\nrecommended; e.g., \`2g' for 2 Gigabytes):"
292msg_please_select_one_or_more_disks="Please select one or more disks to create a zpool:"
293msg_pool_name="Pool Name"
294msg_pool_name_cannot_be_empty="Pool name cannot be empty."
295msg_pool_name_help="Customize the name of the zpool to be created (Required)"
296msg_pool_type_disks="Pool Type/Disks:"
297msg_pool_type_disks_help="Choose type of ZFS Virtual Device and disks to use (Required)"
298msg_processing_selection="Processing selection..."
299msg_raid10_desc="RAID 1+0 - n x 2-Way Mirrors"
300msg_raid10_help="[4+ Disks] Striped Mirrors provides the best performance, but the least storage"
301msg_raidz1_desc="RAID-Z1 - Single Redundant RAID"
302msg_raidz1_help="[3+ Disks] Withstand failure of 1 disk. Recommended for: 3, 5 or 9 disks"
303msg_raidz2_desc="RAID-Z2 - Double Redundant RAID"
304msg_raidz2_help="[4+ Disks] Withstand failure of 2 disks. Recommended for: 4, 6 or 10 disks"
305msg_raidz3_desc="RAID-Z3 - Triple Redundant RAID"
306msg_raidz3_help="[5+ Disks] Withstand failure of 3 disks. Recommended for: 5, 7 or 11 disks"
307msg_rescan_devices="Rescan Devices"
308msg_rescan_devices_help="Scan for device changes"
309msg_select="Select"
310msg_select_a_disk_device="Select a disk device"
311msg_select_virtual_device_type="Select Virtual Device type:"
312msg_stripe_desc="Stripe - No Redundancy"
313msg_stripe_help="[1+ Disks] Striping provides maximum storage but no redundancy"
314msg_swap_encrypt="Encrypt Swap?"
315msg_swap_encrypt_help="Encrypt swap partitions with temporary keys, discarded on reboot"
316msg_swap_invalid="The selected swap size (%s) is invalid. Enter a number optionally followed by units. Example: 2G"
317msg_swap_mirror="Mirror Swap?"
318msg_swap_mirror_help="Mirror swap partitions for redundancy, breaks crash dumps"
319msg_swap_size="Swap Size"
320msg_swap_size_help="Customize how much swap space is allocated to each selected disk"
321msg_swap_toosmall="The selected swap size (%s) is to small. Please enter a value greater than 100MB or enter 0 for no swap"
322msg_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."
323msg_unable_to_get_disk_capacity="Unable to get disk capacity of \`%s'"
324msg_unsupported_partition_scheme="%s is an unsupported partition scheme"
325msg_user_cancelled="User Cancelled."
326msg_yes="YES"
327msg_zfs_configuration="ZFS Configuration"
328
329############################################################ FUNCTIONS
330
331# dialog_menu_main
332#
333# Display the dialog(1)-based application main menu.
334#
335dialog_menu_main()
336{
337	local title="$DIALOG_TITLE"
338	local btitle="$DIALOG_BACKTITLE"
339	local prompt="$msg_configure_options"
340	local force4k="$msg_no"
341	local usegeli="$msg_no"
342	local swapgeli="$msg_no"
343	local swapmirror="$msg_no"
344	[ "$ZFSBOOT_FORCE_4K_SECTORS" ] && force4k="$msg_yes"
345	[ "$ZFSBOOT_GELI_ENCRYPTION" ] && usegeli="$msg_yes"
346	[ "$ZFSBOOT_SWAP_ENCRYPTION" ] && swapgeli="$msg_yes"
347	[ "$ZFSBOOT_SWAP_MIRROR" ] && swapmirror="$msg_yes"
348	local disks n disks_grammar
349	f_count n $ZFSBOOT_DISKS
350	{ [ $n -eq 1 ] && disks_grammar=$msg_disk_singular; } ||
351		disks_grammar=$msg_disk_plural # grammar
352	local menu_list="
353		'>>> $msg_install'      '$msg_install_desc'
354		                        '$msg_install_help'
355		'T $msg_pool_type_disks'
356		               '$ZFSBOOT_VDEV_TYPE: $n $disks_grammar'
357		               '$msg_pool_type_disks_help'
358		'- $msg_rescan_devices' '*'
359		                        '$msg_rescan_devices_help'
360		'- $msg_disk_info'      '*'
361		                        '$msg_disk_info_help'
362		'N $msg_pool_name'      '$ZFSBOOT_POOL_NAME'
363		                        '$msg_pool_name_help'
364		'4 $msg_force_4k_sectors'
365		                        '$force4k'
366		                        '$msg_force_4k_sectors_help'
367		'E $msg_encrypt_disks'  '$usegeli'
368		                        '$msg_encrypt_disks_help'
369		'P $msg_partition_scheme'
370		               '$ZFSBOOT_PARTITION_SCHEME ($ZFSBOOT_BOOT_TYPE)'
371		               '$msg_partition_scheme_help'
372		'S $msg_swap_size'      '$ZFSBOOT_SWAP_SIZE'
373		                        '$msg_swap_size_help'
374		'M $msg_swap_mirror'    '$swapmirror'
375		                        '$msg_swap_mirror_help'
376		'W $msg_swap_encrypt'   '$swapgeli'
377		                        '$msg_swap_encrypt_help'
378	" # END-QUOTE
379	local defaultitem= # Calculated below
380	local hline="$hline_alnum_arrows_punc_tab_enter"
381
382	local height width rows
383	eval f_dialog_menu_with_help_size height width rows \
384		\"\$title\" \"\$btitle\" \"\$prompt\" \"\$hline\" $menu_list
385
386	# Obtain default-item from previously stored selection
387	f_dialog_default_fetch defaultitem
388
389	local menu_choice
390	menu_choice=$( eval $DIALOG \
391		--title \"\$title\"              \
392		--backtitle \"\$btitle\"         \
393		--hline \"\$hline\"              \
394		--item-help                      \
395		--ok-label \"\$msg_select\"      \
396		--cancel-label \"\$msg_cancel\"  \
397		--default-item \"\$defaultitem\" \
398		--menu \"\$prompt\"              \
399		$height $width $rows             \
400		$menu_list                       \
401		2>&1 >&$DIALOG_TERMINAL_PASSTHRU_FD
402	)
403	local retval=$?
404	f_dialog_data_sanitize menu_choice
405	f_dialog_menutag_store "$menu_choice"
406
407	# Only update default-item on success
408	[ $retval -eq $DIALOG_OK ] && f_dialog_default_store "$menu_choice"
409
410	return $retval
411}
412
413# dialog_last_chance $disks ...
414#
415# Display a list of the disks that the user is about to destroy. The default
416# action is to return error status unless the user explicitly (non-default)
417# selects "Yes" from the noyes dialog.
418#
419dialog_last_chance()
420{
421	local title="$DIALOG_TITLE"
422	local btitle="$DIALOG_BACKTITLE"
423	local prompt # Calculated below
424	local hline="$hline_arrows_tab_enter"
425
426	local height=8 width=50 prefix="   "
427	local plen=${#prefix} list= line=
428	local max_width=$(( $width - 3 - $plen ))
429
430	local yes no defaultno extra_args format
431	if [ "$USE_XDIALOG" ]; then
432		yes=ok no=cancel defaultno=default-no
433		extra_args="--wrap --left"
434		format="$msg_last_chance_are_you_sure"
435	else
436		yes=yes no=no defaultno=defaultno
437		extra_args="--colors --cr-wrap"
438		format="$msg_last_chance_are_you_sure_color"
439	fi
440
441	local disk line_width
442	for disk in $*; do
443		if [ "$line" ]; then
444			line_width=${#line}
445		else
446			line_width=$plen
447		fi
448		line_width=$(( $line_width + 1 + ${#disk} ))
449		# Add newline before disk if it would exceed max_width
450		if [ $line_width -gt $max_width ]; then
451			list="$list$line\n"
452			line="$prefix"
453			height=$(( $height + 1 ))
454		fi
455		# Add the disk to the list
456		line="$line $disk"
457	done
458	# Append the left-overs
459	if [ "${line#$prefix}" ]; then
460		list="$list$line"
461		height=$(( $height + 1 ))
462	fi
463
464	# Add height for Xdialog(1)
465	[ "$USE_XDIALOG" ] && height=$(( $height + $height / 5 + 3 ))
466
467	prompt=$( printf "$format" "$list" )
468	f_dprintf "%s: Last Chance!" "$0"
469	$DIALOG \
470		--title "$title"        \
471		--backtitle "$btitle"   \
472		--hline "$hline"        \
473		--$defaultno            \
474		--$yes-label "$msg_yes" \
475		--$no-label "$msg_no"   \
476		$extra_args             \
477		--yesno "$prompt" $height $width
478}
479
480# dialog_menu_layout
481#
482# Configure Virtual Device type and disks to use for the ZFS boot pool. User
483# must select enough disks to satisfy the chosen vdev type.
484#
485dialog_menu_layout()
486{
487	local funcname=dialog_menu_layout
488	local title="$DIALOG_TITLE"
489	local btitle="$DIALOG_BACKTITLE"
490	local vdev_prompt="$msg_select_virtual_device_type"
491	local disk_prompt="$msg_please_select_one_or_more_disks"
492	local vdev_menu_list="
493		'stripe' '$msg_stripe_desc' '$msg_stripe_help'
494		'mirror' '$msg_mirror_desc' '$msg_mirror_help'
495		'raid10' '$msg_raid10_desc' '$msg_raid10_help'
496		'raidz1' '$msg_raidz1_desc' '$msg_raidz1_help'
497		'raidz2' '$msg_raidz2_desc' '$msg_raidz2_help'
498		'raidz3' '$msg_raidz3_desc' '$msg_raidz3_help'
499	" # END-QUOTE
500	local disk_check_list= # Calculated below
501	local vdev_hline="$hline_arrows_tab_enter"
502	local disk_hline="$hline_arrows_space_tab_enter"
503
504	# Warn the user if vdev type is not valid
505	case "$ZFSBOOT_VDEV_TYPE" in
506	stripe|mirror|raid10|raidz1|raidz2|raidz3) : known good ;;
507	*)
508		f_dprintf "%s: Invalid virtual device type \`%s'" \
509			  $funcname "$ZFSBOOT_VDEV_TYPE"
510		f_show_err "$msg_invalid_virtual_device_type" \
511			   "$ZFSBOOT_VDEV_TYPE"
512		f_interactive || return $FAILURE
513	esac
514
515	# Calculate size of vdev menu once only
516	local vheight vwidth vrows
517	eval f_dialog_menu_with_help_size vheight vwidth vrows \
518		\"\$title\" \"\$btitle\" \"\$vdev_prompt\" \"\$vdev_hline\" \
519		$vdev_menu_list
520
521	# Get a list of probed disk devices
522	local disks=
523	debug= f_device_find "" $DEVICE_TYPE_DISK disks
524
525	# Prune out mounted md(4) devices that may be part of the boot process
526	local disk name new_list=
527	for disk in $disks; do
528		debug= $disk get name name
529		case "$name" in
530		md[0-9]*) f_mounted -b "/dev/$name" && continue ;;
531		esac
532		new_list="$new_list $disk"
533	done
534	disks="${new_list# }"
535
536	# Prune out disks that are not available to install to
537	local avail_disks=
538	for disk in $disks; do
539		debug= $disk get name name
540		geom disk list $name | awk '$1 == "Mode:" && $2 != "r0w0e0" { exit 1 }'
541		[ $? -eq 0 ] && avail_disks="$avail_disks $disk"
542	done
543	disks="${avail_disks# }"
544
545	# Debugging
546	if [ "$debug" ]; then
547		local disk_names=
548		for disk in $disks; do
549			debug= $disk get name name
550			disk_names="$disk_names $name"
551		done
552		f_dprintf "$funcname: disks=[%s]" "${disk_names# }"
553	fi
554
555	if [ ! "$disks" ]; then
556		f_dprintf "No disk(s) present to configure"
557		f_show_err "$msg_no_disks_present_to_configure"
558		return $FAILURE
559	fi
560
561	# Lets sort the disks array to be more user friendly
562	f_device_sort_by name disks disks
563
564	#
565	# Operate in a loop so we can (if interactive) repeat if not enough
566	# disks are selected to satisfy the chosen vdev type or user wants to
567	# back-up to the previous menu.
568	#
569	local vardisk ndisks onoff selections vdev_choice breakout device
570	local valid_disks all_valid want_disks desc height width rows
571	while :; do
572		#
573		# Confirm the vdev type that was selected
574		#
575		if f_interactive && [ "$ZFSBOOT_CONFIRM_LAYOUT" ]; then
576			vdev_choice=$( eval $DIALOG \
577				--title \"\$title\"              \
578				--backtitle \"\$btitle\"         \
579				--hline \"\$vdev_hline\"         \
580				--ok-label \"\$msg_ok\"          \
581				--cancel-label \"\$msg_cancel\"  \
582				--item-help                      \
583				--default-item \"\$ZFSBOOT_VDEV_TYPE\" \
584				--menu \"\$vdev_prompt\"         \
585				$vheight $vwidth $vrows          \
586				$vdev_menu_list                  \
587				2>&1 >&$DIALOG_TERMINAL_PASSTHRU_FD
588			) || return $?
589				# Exit if user pressed ESC or chose Cancel/No
590			f_dialog_data_sanitize vdev_choice
591
592			ZFSBOOT_VDEV_TYPE="$vdev_choice"
593			f_dprintf "$funcname: ZFSBOOT_VDEV_TYPE=[%s]" \
594			          "$ZFSBOOT_VDEV_TYPE"
595		fi
596
597		# Determine the number of disks needed for this vdev type
598		want_disks=0
599		case "$ZFSBOOT_VDEV_TYPE" in
600		stripe) want_disks=1 ;;
601		mirror) want_disks=2 ;;
602		raid10) want_disks=4 ;;
603		raidz1) want_disks=3 ;;
604		raidz2) want_disks=4 ;;
605		raidz3) want_disks=5 ;;
606		esac
607
608		#
609		# Warn the user if any scripted disks are invalid
610		#
611		valid_disks= all_valid=${ZFSBOOT_DISKS:+1} # optimism
612		for disk in $ZFSBOOT_DISKS; do
613			if debug= f_device_find -1 \
614				$disk $DEVICE_TYPE_DISK device
615			then
616				valid_disks="$valid_disks $disk"
617				continue
618			fi
619			f_dprintf "$funcname: \`%s' is not a real disk" "$disk"
620			all_valid=
621		done
622		if [ ! "$all_valid" ]; then
623			if [ "$ZFSBOOT_DISKS" ]; then
624				f_show_err \
625				    "$msg_missing_one_or_more_scripted_disks"
626			else
627				f_dprintf "No disks selected."
628				f_interactive ||
629					f_show_err "$msg_no_disks_selected"
630			fi
631			f_interactive || return $FAILURE
632		fi
633		ZFSBOOT_DISKS="${valid_disks# }"
634
635		#
636		# Short-circuit if we're running non-interactively
637		#
638		if ! f_interactive || [ ! "$ZFSBOOT_CONFIRM_LAYOUT" ]; then
639			f_count ndisks $ZFSBOOT_DISKS
640			[ $ndisks -ge $want_disks ] && break # to success
641
642			# Not enough disks selected
643			f_dprintf "$funcname: %s: %s (%u < %u minimum)" \
644				  "$ZFSBOOT_VDEV_TYPE" \
645				  "Not enough disks selected." \
646				  $ndisks $want_disks
647			f_interactive || return $FAILURE
648			msg_yes="$msg_change_selection" msg_no="$msg_cancel" \
649				f_yesno "%s: $msg_not_enough_disks_selected" \
650				"$ZFSBOOT_VDEV_TYPE" $ndisks $want_disks ||
651				return $FAILURE
652		fi
653
654		#
655		# Confirm the disks that were selected
656		# Loop until the user cancels or selects enough disks
657		#
658		breakout=
659		while :; do
660			# Loop over list of available disks, resetting state
661			for disk in $disks; do
662				f_isset _${disk}_status && setvar _${disk}_status
663			done
664
665			# Loop over list of selected disks and create temporary
666			# locals to map statuses onto up-to-date list of disks
667			for disk in $ZFSBOOT_DISKS; do
668				debug= f_device_find -1 \
669					$disk $DEVICE_TYPE_DISK disk
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 the root of the pool..."
1476	f_eval_catch $funcname zfs "$ZFS_SET" "canmount=noauto" \
1477		"$zroot_name/$ZFSBOOT_BEROOT_NAME/$ZFSBOOT_BOOTFS_NAME"
1478
1479	# Last, but not least... required lines for rc.conf(5)/loader.conf(5)
1480	# NOTE: We later concatenate these into their destination
1481	f_dprintf "%s: Configuring rc.conf(5)/loader.conf(5) additions..." \
1482	          "$funcname"
1483	f_eval_catch $funcname echo "$ECHO_APPEND" 'zfs_enable=\"YES\"' \
1484	             $BSDINSTALL_TMPETC/rc.conf.zfs || return $FAILURE
1485	f_eval_catch $funcname echo "$ECHO_APPEND" \
1486	             'kern.geom.label.disk_ident.enable=\"0\"' \
1487	             $BSDINSTALL_TMPBOOT/loader.conf.zfs || return $FAILURE
1488	f_eval_catch $funcname echo "$ECHO_APPEND" \
1489	             'kern.geom.label.gptid.enable=\"0\"' \
1490	             $BSDINSTALL_TMPBOOT/loader.conf.zfs || return $FAILURE
1491
1492	if [ "$ZFSBOOT_FORCE_4K_SECTORS" ]; then
1493		f_eval_catch $funcname echo "$ECHO_APPEND" \
1494	             'vfs.zfs.min_auto_ashift=12' \
1495	             $BSDINSTALL_TMPETC/sysctl.conf.zfs || return $FAILURE
1496	fi
1497
1498	if [ "$ZFSBOOT_SWAP_MIRROR" ]; then
1499		f_eval_catch $funcname echo "$ECHO_APPEND" \
1500		             'geom_mirror_load=\"YES\"' \
1501		             $BSDINSTALL_TMPBOOT/loader.conf.gmirror ||
1502		             return $FAILURE
1503	fi
1504
1505	# We're all done unless we should go on to do encryption
1506	[ "$ZFSBOOT_GELI_ENCRYPTION" ] || return $SUCCESS
1507
1508	#
1509	# Configure geli(8)-based encryption
1510	#
1511	f_dprintf "$funcname: Configuring disk encryption..."
1512	f_eval_catch $funcname echo "$ECHO_APPEND" 'aesni_load=\"YES\"' \
1513		$BSDINSTALL_TMPBOOT/loader.conf.aesni || return $FAILURE
1514	f_eval_catch $funcname echo "$ECHO_APPEND" 'geom_eli_load=\"YES\"' \
1515		$BSDINSTALL_TMPBOOT/loader.conf.geli || return $FAILURE
1516
1517	# We're all done unless we should go on for boot pool
1518	[ "$ZFSBOOT_BOOT_POOL" ] || return $SUCCESS
1519
1520	for disk in $disks; do
1521		f_eval_catch $funcname printf "$PRINTF_CONF" \
1522			geli_%s_keyfile0_load "$disk$targetpart YES" \
1523			$BSDINSTALL_TMPBOOT/loader.conf.$disk$targetpart ||
1524			return $FAILURE
1525		f_eval_catch $funcname printf "$PRINTF_CONF" \
1526			geli_%s_keyfile0_type \
1527			"$disk$targetpart $disk$targetpart:geli_keyfile0" \
1528			$BSDINSTALL_TMPBOOT/loader.conf.$disk$targetpart ||
1529			return $FAILURE
1530		f_eval_catch $funcname printf "$PRINTF_CONF" \
1531			geli_%s_keyfile0_name \
1532			"$disk$targetpart \"$ZFSBOOT_GELI_KEY_FILE\"" \
1533			$BSDINSTALL_TMPBOOT/loader.conf.$disk$targetpart ||
1534			return $FAILURE
1535	done
1536
1537	# Set cachefile for boot pool so it auto-imports at system start
1538	f_dprintf "$funcname: Configuring zpool.cache for boot pool..."
1539	f_eval_catch $funcname zpool "$ZPOOL_SET" \
1540	             "cachefile=\"$BSDINSTALL_CHROOT/boot/zfs/zpool.cache\"" \
1541	             "$bootpool_name" || return $FAILURE
1542
1543	# Some additional geli(8) requirements for loader.conf(5)
1544	for option in \
1545		'zpool_cache_load=\"YES\"' \
1546		'zpool_cache_type=\"/boot/zfs/zpool.cache\"' \
1547		'zpool_cache_name=\"/boot/zfs/zpool.cache\"' \
1548		'geom_eli_passphrase_prompt=\"YES\"' \
1549	; do
1550		f_eval_catch $funcname echo "$ECHO_APPEND" "$option" \
1551		             $BSDINSTALL_TMPBOOT/loader.conf.zfs ||
1552		             return $FAILURE
1553	done
1554	return $SUCCESS
1555}
1556
1557# dialog_menu_diskinfo
1558#
1559# Prompt the user to select a disk and then provide detailed info on it.
1560#
1561dialog_menu_diskinfo()
1562{
1563	local device disk
1564
1565	#
1566	# Break from loop when user cancels disk selection
1567	#
1568	while :; do
1569		device=$( msg_cancel="$msg_back" f_device_menu \
1570			"$DIALOG_TITLE" "$msg_select_a_disk_device" "" \
1571			$DEVICE_TYPE_DISK 2>&1 ) || break
1572		$device get name disk
1573
1574		# Show gpart(8) `show' and camcontrol(8) `inquiry' data
1575		f_show_msg "$msg_detailed_disk_info" \
1576			"$disk" "$( gpart show $disk 2> /dev/null )" \
1577			"$disk" "$( camcontrol inquiry $disk 2> /dev/null )" \
1578			"$disk" "$( camcontrol identify $disk 2> /dev/null )"
1579	done
1580
1581	return $SUCCESS
1582}
1583
1584dialog_zpool_name()
1585{
1586	local prompt="$* is already taken, please enter a name for the ZFS pool \
1587	(Or confirm using the same name by just pressing enter)"
1588	local hline=
1589	local value="$*"
1590	local height width
1591
1592	f_dialog_inputbox_size height width \
1593		"$DIALOG_TITLE" "$DIALOG_BACKTITLE" "$prompt" "$value" "$hline"
1594
1595	$DIALOG \
1596		--title "$DIALOG_TITLE"         \
1597		--backtitle "$DIALOG_BACKTITLE" \
1598		--hline "$hline"                \
1599		--ok-label "Ok"                 \
1600		--no-cancel                     \
1601		--inputbox "$prompt"            \
1602		$height $width "$value"         \
1603		2>&1 >&$DIALOG_TERMINAL_PASSTHRU_FD
1604}
1605
1606############################################################ MAIN
1607
1608#
1609# Initialize
1610#
1611f_dialog_title "$msg_zfs_configuration"
1612f_dialog_backtitle "$msg_freebsd_installer"
1613
1614# User may have specifically requested ZFS-related operations be interactive
1615! f_interactive && f_zfsinteractive && unset $VAR_NONINTERACTIVE
1616
1617#
1618# Debugging
1619#
1620f_dprintf "BSDINSTALL_CHROOT=[%s]" "$BSDINSTALL_CHROOT"
1621f_dprintf "BSDINSTALL_TMPETC=[%s]" "$BSDINSTALL_TMPETC"
1622f_dprintf "FSTAB_FMT=[%s]" "$FSTAB_FMT"
1623
1624pools=$(zpool import | awk '$1 == "pool:" { print $2}')
1625for pool in ${pools}; do
1626	f_dprintf "Checking ${pool} against ${ZFSBOOT_POOL_NAME}"
1627	if [ "${pool}" = "${ZFSBOOT_POOL_NAME}" ]; then
1628		f_dprintf "Pool ${pool} already taken"
1629		ZFSBOOT_POOL_NAME=$(dialog_zpool_name "${ZFSBOOT_POOL_NAME}")
1630		break
1631	fi
1632done
1633
1634#
1635# Determine default boot type
1636#
1637case $(uname -m) in
1638arm64|riscv)
1639	# We support only UEFI boot for arm64 and riscv.
1640	: ${ZFSBOOT_BOOT_TYPE:=UEFI}
1641	: ${ZFSBOOT_PARTITION_SCHEME:=GPT}
1642	;;
1643*)
1644	# If the system was booted with UEFI, set the default boot type to UEFI
1645	bootmethod=$( sysctl -n machdep.bootmethod )
1646	f_dprintf "machdep.bootmethod=[%s]" "$bootmethod"
1647	if [ "$bootmethod" = "UEFI" ]; then
1648		: ${ZFSBOOT_BOOT_TYPE:=BIOS+UEFI}
1649		: ${ZFSBOOT_PARTITION_SCHEME:=GPT}
1650	else
1651		: ${ZFSBOOT_BOOT_TYPE:=BIOS}
1652		: ${ZFSBOOT_PARTITION_SCHEME:=GPT}
1653	fi
1654	;;
1655esac
1656
1657#
1658# Loop over the main menu until we've accomplished what we came here to do
1659#
1660while :; do
1661	if ! f_interactive; then
1662		retval=$DIALOG_OK
1663		mtag=">>> $msg_install"
1664	else
1665		dialog_menu_main
1666		retval=$?
1667		f_dialog_menutag_fetch mtag
1668	fi
1669
1670	f_dprintf "retval=%u mtag=[%s]" $retval "$mtag"
1671	[ $retval -eq $DIALOG_OK ] || f_die
1672
1673	case "$mtag" in
1674	">>> $msg_install")
1675		#
1676		# First, validate the user's selections
1677		#
1678
1679		# Make sure they gave us a name for the pool
1680		if [ ! "$ZFSBOOT_POOL_NAME" ]; then
1681			f_dprintf "Pool name cannot be empty."
1682			f_show_err "$msg_pool_name_cannot_be_empty"
1683			continue
1684		fi
1685
1686		# Validate vdev type against number of disks selected/scripted
1687		# (also validates that ZFSBOOT_DISKS are real [probed] disks)
1688		# NB: dialog_menu_layout supports running non-interactively
1689		dialog_menu_layout || continue
1690
1691		# Make sure each disk will have room for ZFS
1692		if f_expand_number "$ZFSBOOT_SWAP_SIZE" swapsize &&
1693		   f_expand_number "$ZFSBOOT_BOOT_POOL_SIZE" bootsize &&
1694		   f_expand_number "1g" zpoolmin
1695		then
1696			minsize=$swapsize teeny_disks=
1697			if [ "$ZFSBOOT_POOL_SIZE" ]; then
1698				f_expand_number "$ZFSBOOT_POOL_SIZE" poolsize
1699				minsize=$(( $minsize + $poolsize ))
1700			fi
1701			[ "$ZFSBOOT_BOOT_POOL" ] &&
1702				minsize=$(( $minsize + $bootsize ))
1703			for disk in $ZFSBOOT_DISKS; do
1704				debug= f_device_find -1 \
1705					$disk $DEVICE_TYPE_DISK device
1706				$device get capacity disksize || continue
1707				[ ${disksize:-0} -ge 0 ] || disksize=0
1708				[ $disksize -lt $minsize ] &&
1709					teeny_disks="$teeny_disks $disk"
1710			done
1711			if [ "$teeny_disks" ]; then
1712				f_dprintf "swapsize=[%s] bootsize[%s] %s" \
1713				          "$ZFSBOOT_SWAP_SIZE" \
1714				          "$ZFSBOOT_BOOT_POOL_SIZE" \
1715				          "minsize=[$minsize]"
1716				f_dprintf "These disks are too small: %s" \
1717				          "$teeny_disks"
1718				f_show_err "$msg_these_disks_are_too_small" \
1719				           "$ZFSBOOT_SWAP_SIZE" \
1720				           "$ZFSBOOT_BOOT_POOL_SIZE" \
1721				           "$teeny_disks"
1722				continue
1723			fi
1724		fi
1725
1726		#
1727		# Last Chance!
1728		#
1729		if f_interactive; then
1730			dialog_last_chance $ZFSBOOT_DISKS || continue
1731		fi
1732
1733		#
1734		# Let's do this
1735		#
1736
1737		vdev_type="$ZFSBOOT_VDEV_TYPE"
1738
1739		# Blank the vdev type for the default layout
1740		[ "$vdev_type" = "stripe" ] && vdev_type=
1741
1742		zfs_create_boot "$ZFSBOOT_POOL_NAME" \
1743		                "$vdev_type" $ZFSBOOT_DISKS || continue
1744
1745		# To be reused by bootconfig
1746		echo "$ZFSBOOT_DISKS" > ${TMPDIR:-"/tmp"}/bsdinstall-zfsboot
1747
1748		break # to success
1749		;;
1750	?" $msg_pool_type_disks")
1751		ZFSBOOT_CONFIRM_LAYOUT=1
1752		dialog_menu_layout
1753		# User has poked settings, disable later confirmation
1754		ZFSBOOT_CONFIRM_LAYOUT=
1755		;;
1756	"- $msg_rescan_devices") f_device_rescan ;;
1757	"- $msg_disk_info") dialog_menu_diskinfo ;;
1758	?" $msg_pool_name")
1759		# Prompt the user to input/change the name for the new pool
1760		f_dialog_input input \
1761			"$msg_please_enter_a_name_for_your_zpool" \
1762			"$ZFSBOOT_POOL_NAME" &&
1763			ZFSBOOT_POOL_NAME="$input"
1764		;;
1765	?" $msg_force_4k_sectors")
1766		# Toggle the variable referenced both by the menu and later
1767		if [ "$ZFSBOOT_FORCE_4K_SECTORS" ]; then
1768			ZFSBOOT_FORCE_4K_SECTORS=
1769		else
1770			ZFSBOOT_FORCE_4K_SECTORS=1
1771		fi
1772		;;
1773	?" $msg_encrypt_disks")
1774		# Toggle the variable referenced both by the menu and later
1775		if [ "$ZFSBOOT_GELI_ENCRYPTION" ]; then
1776			ZFSBOOT_GELI_ENCRYPTION=
1777		else
1778			ZFSBOOT_FORCE_4K_SECTORS=1
1779			ZFSBOOT_GELI_ENCRYPTION=1
1780		fi
1781		;;
1782	?" $msg_partition_scheme")
1783		# Toggle between GPT (BIOS), GPT (UEFI) and MBR
1784		if [ "$ZFSBOOT_PARTITION_SCHEME" = "GPT" -a \
1785		     "$ZFSBOOT_BOOT_TYPE" = "BIOS" ]
1786		then
1787			ZFSBOOT_PARTITION_SCHEME="GPT"
1788			ZFSBOOT_BOOT_TYPE="UEFI"
1789		elif [ "$ZFSBOOT_PARTITION_SCHEME" = "GPT" -a \
1790		       "$ZFSBOOT_BOOT_TYPE" = "UEFI" ]
1791		then
1792			ZFSBOOT_PARTITION_SCHEME="GPT"
1793			ZFSBOOT_BOOT_TYPE="BIOS+UEFI"
1794		elif [ "$ZFSBOOT_PARTITION_SCHEME" = "GPT" ]; then
1795			ZFSBOOT_PARTITION_SCHEME="MBR"
1796			ZFSBOOT_BOOT_TYPE="BIOS"
1797		elif [ "$ZFSBOOT_PARTITION_SCHEME" = "MBR" ]; then
1798			ZFSBOOT_PARTITION_SCHEME="GPT + Active"
1799			ZFSBOOT_BOOT_TYPE="BIOS"
1800		elif [ "$ZFSBOOT_PARTITION_SCHEME" = "GPT + Active" ]; then
1801			ZFSBOOT_PARTITION_SCHEME="GPT + Lenovo Fix"
1802			ZFSBOOT_BOOT_TYPE="BIOS"
1803		else
1804			ZFSBOOT_PARTITION_SCHEME="GPT"
1805			ZFSBOOT_BOOT_TYPE="BIOS"
1806		fi
1807		;;
1808	?" $msg_swap_size")
1809		# Prompt the user to input/change the swap size for each disk
1810		while :; do
1811		    f_dialog_input input \
1812			    "$msg_please_enter_amount_of_swap_space" \
1813			    "$ZFSBOOT_SWAP_SIZE" &&
1814			    ZFSBOOT_SWAP_SIZE="${input:-0}"
1815		    if f_expand_number "$ZFSBOOT_SWAP_SIZE" swapsize
1816		    then
1817			if [ $swapsize -ne 0 -a $swapsize -lt 104857600 ]; then
1818			    f_show_err "$msg_swap_toosmall" \
1819				       "$ZFSBOOT_SWAP_SIZE"
1820			    continue
1821			else
1822			    break
1823			fi
1824		    else
1825			f_show_err "$msg_swap_invalid" \
1826				   "$ZFSBOOT_SWAP_SIZE"
1827			continue
1828		    fi
1829		done
1830		;;
1831	?" $msg_swap_mirror")
1832		# Toggle the variable referenced both by the menu and later
1833		if [ "$ZFSBOOT_SWAP_MIRROR" ]; then
1834			ZFSBOOT_SWAP_MIRROR=
1835		else
1836			ZFSBOOT_SWAP_MIRROR=1
1837		fi
1838		;;
1839	?" $msg_swap_encrypt")
1840		# Toggle the variable referenced both by the menu and later
1841		if [ "$ZFSBOOT_SWAP_ENCRYPTION" ]; then
1842			ZFSBOOT_SWAP_ENCRYPTION=
1843		else
1844			ZFSBOOT_SWAP_ENCRYPTION=1
1845		fi
1846		;;
1847	esac
1848done
1849
1850exit $SUCCESS
1851
1852################################################################################
1853# END
1854################################################################################
1855