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