simd_stat: fix undefined CONFIG_KERNEL_MODE_NEON error on armel
[zfs.git] / contrib / initramfs / scripts / zfs
blobc569b2528368568f2b5225ee02f9a7f796f0554c
1 # ZFS boot stub for initramfs-tools.
3 # In the initramfs environment, the /init script sources this stub to
4 # override the default functions in the /scripts/local script.
6 # Enable this by passing boot=zfs on the kernel command line.
8 # $quiet, $root, $rpool, $bootfs come from the cmdline:
9 # shellcheck disable=SC2154
11 # Source the common functions
12 . /etc/zfs/zfs-functions
14 # Start interactive shell.
15 # Use debian's panic() if defined, because it allows to prevent shell access
16 # by setting panic in cmdline (e.g. panic=0 or panic=15).
17 # See "4.5 Disable root prompt on the initramfs" of Securing Debian Manual:
18 # https://www.debian.org/doc/manuals/securing-debian-howto/ch4.en.html
19 shell() {
20         if command -v panic > /dev/null 2>&1; then
21                 panic
22         else
23                 /bin/sh
24         fi
27 # This runs any scripts that should run before we start importing
28 # pools and mounting any filesystems.
29 pre_mountroot()
31         if command -v run_scripts > /dev/null 2>&1
32         then
33                 if [ -f "/scripts/local-top" ] || [ -d "/scripts/local-top" ]
34                 then
35                         [ "$quiet" != "y" ] && \
36                             zfs_log_begin_msg "Running /scripts/local-top"
37                         run_scripts /scripts/local-top
38                         [ "$quiet" != "y" ] && zfs_log_end_msg
39                 fi
41           if [ -f "/scripts/local-premount" ] || [ -d "/scripts/local-premount" ]
42           then
43                         [ "$quiet" != "y" ] && \
44                             zfs_log_begin_msg "Running /scripts/local-premount"
45                         run_scripts /scripts/local-premount
46                         [ "$quiet" != "y" ] && zfs_log_end_msg
47                 fi
48         fi
51 # If plymouth is available, hide the splash image.
52 disable_plymouth()
54         if [ -x /bin/plymouth ] && /bin/plymouth --ping
55         then
56                 /bin/plymouth hide-splash >/dev/null 2>&1
57         fi
60 # Get a ZFS filesystem property value.
61 get_fs_value()
63         fs="$1"
64         value=$2
66         "${ZFS}" get -H -ovalue "$value" "$fs" 2> /dev/null
69 # Find the 'bootfs' property on pool $1.
70 # If the property does not contain '/', then ignore this
71 # pool by exporting it again.
72 find_rootfs()
74         pool="$1"
76         # If 'POOL_IMPORTED' isn't set, no pool imported and therefore
77         # we won't be able to find a root fs.
78         [ -z "${POOL_IMPORTED}" ] && return 1
80         # If it's already specified, just keep it mounted and exit
81         # User (kernel command line) must be correct.
82         if [ -n "${ZFS_BOOTFS}" ] && [ "${ZFS_BOOTFS}" != "zfs:AUTO" ]; then
83                 return 0
84         fi
86         # Not set, try to find it in the 'bootfs' property of the pool.
87         # NOTE: zpool does not support 'get -H -ovalue bootfs'...
88         ZFS_BOOTFS=$("${ZPOOL}" list -H -obootfs "$pool")
90         # Make sure it's not '-' and that it starts with /.
91         if [ "${ZFS_BOOTFS}" != "-" ] && \
92                 get_fs_value "${ZFS_BOOTFS}" mountpoint | grep -q '^/$'
93         then
94                 # Keep it mounted
95                 POOL_IMPORTED=1
96                 return 0
97         fi
99         # Not boot fs here, export it and later try again..
100         "${ZPOOL}" export "$pool"
101         POOL_IMPORTED=
102         ZFS_BOOTFS=
103         return 1
106 # Support function to get a list of all pools, separated with ';'
107 find_pools()
109         pools=$("$@" 2> /dev/null | \
110                 sed -Ee '/pool:|^[a-zA-Z0-9]/!d' -e 's@.*: @@' | \
111                 tr '\n' ';')
113         echo "${pools%%;}" # Return without the last ';'.
116 # Get a list of all available pools
117 get_pools()
119         if [ -n "${ZFS_POOL_IMPORT}" ]; then
120                 echo "$ZFS_POOL_IMPORT"
121                 return 0
122         fi
124         # Get the base list of available pools.
125         available_pools=$(find_pools "$ZPOOL" import)
127         # Just in case - seen it happen (that a pool isn't visible/found
128         # with a simple "zpool import" but only when using the "-d"
129         # option or setting ZPOOL_IMPORT_PATH).
130         if [ -d "/dev/disk/by-id" ]
131         then
132                 npools=$(find_pools "$ZPOOL" import -d /dev/disk/by-id)
133                 if [ -n "$npools" ]
134                 then
135                         # Because we have found extra pool(s) here, which wasn't
136                         # found 'normally', we need to force USE_DISK_BY_ID to
137                         # make sure we're able to actually import it/them later.
138                         USE_DISK_BY_ID='yes'
140                         if [ -n "$available_pools" ]
141                         then
142                                 # Filter out duplicates (pools found with the simple
143                                 # "zpool import" but which is also found with the
144                                 # "zpool import -d ...").
145                                 npools=$(echo "$npools" | sed "s,$available_pools,,")
147                                 # Add the list to the existing list of
148                                 # available pools
149                                 available_pools="$available_pools;$npools"
150                         else
151                                 available_pools="$npools"
152                         fi
153                 fi
154         fi
156         # Filter out any exceptions...
157         if [ -n "$ZFS_POOL_EXCEPTIONS" ]
158         then
159                 found=""
160                 apools=""
161                 OLD_IFS="$IFS" ; IFS=";"
163                 for pool in $available_pools
164                 do
165                         for exception in $ZFS_POOL_EXCEPTIONS
166                         do
167                                 [ "$pool" = "$exception" ] && continue 2
168                                 found="$pool"
169                         done
171                         if [ -n "$found" ]
172                         then
173                                 if [ -n "$apools" ]
174                                 then
175                                         apools="$apools;$pool"
176                                 else
177                                         apools="$pool"
178                                 fi
179                         fi
180                 done
182                 IFS="$OLD_IFS"
183                 available_pools="$apools"
184         fi
186         # Return list of available pools.
187         echo "$available_pools"
190 # Import given pool $1
191 import_pool()
193         pool="$1"
195         # Verify that the pool isn't already imported
196         # Make as sure as we can to not require '-f' to import.
197         "${ZPOOL}" get -H -o value name,guid 2>/dev/null | grep -Fxq "$pool" && return 0
199         # For backwards compatibility, make sure that ZPOOL_IMPORT_PATH is set
200         # to something we can use later with the real import(s). We want to
201         # make sure we find all by* dirs, BUT by-vdev should be first (if it
202         # exists).
203         if [ -n "$USE_DISK_BY_ID" ] && [ -z "$ZPOOL_IMPORT_PATH" ]
204         then
205                 dirs="$(for dir in /dev/disk/by-*
206                 do
207                         # Ignore by-vdev here - we want it first!
208                         echo "$dir" | grep -q /by-vdev && continue
209                         [ ! -d "$dir" ] && continue
211                         printf "%s" "$dir:"
212                 done | sed 's,:$,,g')"
214                 if [ -d "/dev/disk/by-vdev" ]
215                 then
216                         # Add by-vdev at the beginning.
217                         ZPOOL_IMPORT_PATH="/dev/disk/by-vdev:"
218                 fi
220                 # ... and /dev at the very end, just for good measure.
221                 ZPOOL_IMPORT_PATH="$ZPOOL_IMPORT_PATH$dirs:/dev"
222         fi
224         # Needs to be exported for "zpool" to catch it.
225         [ -n "$ZPOOL_IMPORT_PATH" ] && export ZPOOL_IMPORT_PATH
228         [ "$quiet" != "y" ] && zfs_log_begin_msg \
229                 "Importing pool '${pool}' using defaults"
231         ZFS_CMD="${ZPOOL} import -N ${ZPOOL_FORCE} ${ZPOOL_IMPORT_OPTS}"
232         ZFS_STDERR="$($ZFS_CMD "$pool" 2>&1)"
233         ZFS_ERROR="$?"
234         if [ "${ZFS_ERROR}" != 0 ]
235         then
236                 [ "$quiet" != "y" ] && zfs_log_failure_msg "${ZFS_ERROR}"
238                 if [ -f "${ZPOOL_CACHE}" ]
239                 then
240                         [ "$quiet" != "y" ] && zfs_log_begin_msg \
241                                 "Importing pool '${pool}' using cachefile."
243                         ZFS_CMD="${ZPOOL} import -c ${ZPOOL_CACHE} -N ${ZPOOL_FORCE} ${ZPOOL_IMPORT_OPTS}"
244                         ZFS_STDERR="$($ZFS_CMD "$pool" 2>&1)"
245                         ZFS_ERROR="$?"
246                 fi
248                 if [ "${ZFS_ERROR}" != 0 ]
249                 then
250                         [ "$quiet" != "y" ] && zfs_log_failure_msg "${ZFS_ERROR}"
252                         disable_plymouth
253                         echo ""
254                         echo "Command: ${ZFS_CMD} '$pool'"
255                         echo "Message: $ZFS_STDERR"
256                         echo "Error: $ZFS_ERROR"
257                         echo ""
258                         echo "Failed to import pool '$pool'."
259                         echo "Manually import the pool and exit."
260                         shell
261                 fi
262         fi
264         [ "$quiet" != "y" ] && zfs_log_end_msg
266         POOL_IMPORTED=1
267         return 0
270 # Load ZFS modules
271 # Loading a module in a initrd require a slightly different approach,
272 # with more logging etc.
273 load_module_initrd()
275         ZFS_INITRD_PRE_MOUNTROOT_SLEEP=${ROOTDELAY:-0}
277         if [ "$ZFS_INITRD_PRE_MOUNTROOT_SLEEP" -gt 0 ]; then
278                 [ "$quiet" != "y" ] && zfs_log_begin_msg "Delaying for up to '${ZFS_INITRD_PRE_MOUNTROOT_SLEEP}' seconds."
279         fi
281         START=$(/bin/date -u +%s)
282         END=$((START+ZFS_INITRD_PRE_MOUNTROOT_SLEEP))
283         while true; do
285                 # Wait for all of the /dev/{hd,sd}[a-z] device nodes to appear.
286                 if command -v wait_for_udev > /dev/null 2>&1 ; then
287                         wait_for_udev 10
288                 elif command -v wait_for_dev > /dev/null 2>&1 ; then
289                         wait_for_dev
290                 fi
292                 #
293                 # zpool import refuse to import without a valid
294                 # /proc/self/mounts
295                 #
296                 [ ! -f /proc/self/mounts ] && mount proc /proc
298                 # Load the module
299                 if load_module "zfs"; then
300                         ret=0
301                         break
302                 else
303                         ret=1
304                 fi
306                 [ "$(/bin/date -u +%s)" -gt "$END" ] && break
307                 sleep 1
309         done
310         if [ "$ZFS_INITRD_PRE_MOUNTROOT_SLEEP" -gt 0 ]; then
311                 [ "$quiet" != "y" ] && zfs_log_end_msg
312         fi
314         [ "$ret" -ne 0 ] && return 1
316         if [ "$ZFS_INITRD_POST_MODPROBE_SLEEP" -gt 0 ] 2>/dev/null
317         then
318                 if [ "$quiet" != "y" ]; then
319                         zfs_log_begin_msg "Sleeping for" \
320                                 "$ZFS_INITRD_POST_MODPROBE_SLEEP seconds..."
321                 fi
322                 sleep "$ZFS_INITRD_POST_MODPROBE_SLEEP"
323                 [ "$quiet" != "y" ] && zfs_log_end_msg
324         fi
326         return 0
329 # Mount a given filesystem
330 mount_fs()
332         fs="$1"
334         # Check that the filesystem exists
335         "${ZFS}" list -oname -tfilesystem -H "${fs}" > /dev/null 2>&1 ||  return 1
337         # Skip filesystems with canmount=off.  The root fs should not have
338         # canmount=off, but ignore it for backwards compatibility just in case.
339         if [ "$fs" != "${ZFS_BOOTFS}" ]
340         then
341                 canmount=$(get_fs_value "$fs" canmount)
342                 [ "$canmount" = "off" ] && return 0
343         fi
345         # Need the _original_ datasets mountpoint!
346         mountpoint=$(get_fs_value "$fs" mountpoint)
347         ZFS_CMD="mount.zfs -o zfsutil"
348         if [ "$mountpoint" = "legacy" ] || [ "$mountpoint" = "none" ]; then
349                 # Can't use the mountpoint property. Might be one of our
350                 # clones. Check the 'org.zol:mountpoint' property set in
351                 # clone_snap() if that's usable.
352                 mountpoint1=$(get_fs_value "$fs" org.zol:mountpoint)
353                 if [ "$mountpoint1" = "legacy" ] ||
354                    [ "$mountpoint1" = "none" ] ||
355                    [ "$mountpoint1" = "-" ]
356                 then
357                         if [ "$fs" != "${ZFS_BOOTFS}" ]; then
358                                 # We don't have a proper mountpoint and this
359                                 # isn't the root fs.
360                                 return 0
361                         fi
362                         if [ "$mountpoint" = "legacy" ]; then
363                                 ZFS_CMD="mount.zfs"
364                         fi
365                         # Last hail-mary: Hope 'rootmnt' is set!
366                         mountpoint=""
367                 else
368                         mountpoint="$mountpoint1"
369                 fi
370         fi
372         # Possibly decrypt a filesystem using native encryption.
373         decrypt_fs "$fs"
375         [ "$quiet" != "y" ] && \
376             zfs_log_begin_msg "Mounting '${fs}' on '${rootmnt}/${mountpoint}'"
377         [ -n "${ZFS_DEBUG}" ] && \
378             zfs_log_begin_msg "CMD: '$ZFS_CMD ${fs} ${rootmnt}/${mountpoint}'"
380         ZFS_STDERR=$(${ZFS_CMD} "${fs}" "${rootmnt}/${mountpoint}" 2>&1)
381         ZFS_ERROR=$?
382         if [ "${ZFS_ERROR}" != 0 ]
383         then
384                 [ "$quiet" != "y" ] && zfs_log_failure_msg "${ZFS_ERROR}"
386                 disable_plymouth
387                 echo ""
388                 echo "Command: ${ZFS_CMD} ${fs} ${rootmnt}/${mountpoint}"
389                 echo "Message: $ZFS_STDERR"
390                 echo "Error: $ZFS_ERROR"
391                 echo ""
392                 echo "Failed to mount ${fs} on ${rootmnt}/${mountpoint}."
393                 echo "Manually mount the filesystem and exit."
394                 shell
395         else
396                 [ "$quiet" != "y" ] && zfs_log_end_msg
397         fi
399         return 0
402 # Unlock a ZFS native encrypted filesystem.
403 decrypt_fs()
405         fs="$1"
407         # If pool encryption is active and the zfs command understands '-o encryption'
408         if [ "$(zpool list -H -o feature@encryption "${fs%%/*}")" = 'active' ]; then
410                 # Determine dataset that holds key for root dataset
411                 ENCRYPTIONROOT="$(get_fs_value "${fs}" encryptionroot)"
412                 KEYLOCATION="$(get_fs_value "${ENCRYPTIONROOT}" keylocation)"
414                 echo "${ENCRYPTIONROOT}" > /run/zfs_fs_name
416                 # If root dataset is encrypted...
417                 if ! [ "${ENCRYPTIONROOT}" = "-" ]; then
418                         KEYSTATUS="$(get_fs_value "${ENCRYPTIONROOT}" keystatus)"
419                         # Continue only if the key needs to be loaded
420                         [ "$KEYSTATUS" = "unavailable" ] || return 0
422                         # Try extensions first
423                         for f in "/etc/zfs/initramfs-tools-load-key" "/etc/zfs/initramfs-tools-load-key.d/"*; do
424                                 [ -r "$f" ] || continue
425                                 (. "$f") && {
426                                         # Successful return and actually-loaded key: we're done
427                                         KEYSTATUS="$(get_fs_value "${ENCRYPTIONROOT}" keystatus)"
428                                         [ "$KEYSTATUS" = "unavailable" ] || return 0
429                                 }
430                         done
432                         # Do not prompt if key is stored noninteractively,
433                         if ! [ "${KEYLOCATION}" = "prompt" ]; then
434                                 $ZFS load-key "${ENCRYPTIONROOT}"
436                         # Prompt with plymouth, if active
437                         elif /bin/plymouth --ping 2>/dev/null; then
438                                 echo "plymouth" > /run/zfs_console_askpwd_cmd
439                                 for _ in 1 2 3; do
440                                         plymouth ask-for-password --prompt "Encrypted ZFS password for ${ENCRYPTIONROOT}" | \
441                                                 $ZFS load-key "${ENCRYPTIONROOT}" && break
442                                 done
444                         # Prompt with systemd, if active
445                         elif [ -e /run/systemd/system ]; then
446                                 echo "systemd-ask-password" > /run/zfs_console_askpwd_cmd
447                                 for _ in 1 2 3; do
448                                         systemd-ask-password --no-tty "Encrypted ZFS password for ${ENCRYPTIONROOT}" | \
449                                                 $ZFS load-key "${ENCRYPTIONROOT}" && break
450                                 done
452                         # Prompt with ZFS tty, otherwise
453                         else
454                                 # Temporarily setting "printk" to "7" allows the prompt to appear even when the "quiet" kernel option has been used
455                                 echo "load-key" > /run/zfs_console_askpwd_cmd
456                                 read -r storeprintk _ < /proc/sys/kernel/printk
457                                 echo 7 > /proc/sys/kernel/printk
458                                 $ZFS load-key "${ENCRYPTIONROOT}"
459                                 echo "$storeprintk" > /proc/sys/kernel/printk
460                         fi
461                 fi
462         fi
464         return 0
467 # Destroy a given filesystem.
468 destroy_fs()
470         fs="$1"
472         [ "$quiet" != "y" ] && \
473             zfs_log_begin_msg "Destroying '$fs'"
475         ZFS_CMD="${ZFS} destroy $fs"
476         ZFS_STDERR="$(${ZFS_CMD} 2>&1)"
477         ZFS_ERROR="$?"
478         if [ "${ZFS_ERROR}" != 0 ]
479         then
480                 [ "$quiet" != "y" ] && zfs_log_failure_msg "${ZFS_ERROR}"
482                 disable_plymouth
483                 echo ""
484                 echo "Command: $ZFS_CMD"
485                 echo "Message: $ZFS_STDERR"
486                 echo "Error: $ZFS_ERROR"
487                 echo ""
488                 echo "Failed to destroy '$fs'. Please make sure that '$fs' is not available."
489                 echo "Hint: Try:  zfs destroy -Rfn $fs"
490                 echo "If this dryrun looks good, then remove the 'n' from '-Rfn' and try again."
491                 shell
492         else
493                 [ "$quiet" != "y" ] && zfs_log_end_msg
494         fi
496         return 0
499 # Clone snapshot $1 to destination filesystem $2
500 # Set 'canmount=noauto' and 'mountpoint=none' so that we get to keep
501 # manual control over it's mounting (i.e., make sure it's not automatically
502 # mounted with a 'zfs mount -a' in the init/systemd scripts).
503 clone_snap()
505         snap="$1"
506         destfs="$2"
507         mountpoint="$3"
509         [ "$quiet" != "y" ] && zfs_log_begin_msg "Cloning '$snap' to '$destfs'"
511         # Clone the snapshot into a dataset we can boot from
512         # + We don't want this filesystem to be automatically mounted, we
513         #   want control over this here and nowhere else.
514         # + We don't need any mountpoint set for the same reason.
515         # We use the 'org.zol:mountpoint' property to remember the mountpoint.
516         ZFS_CMD="${ZFS} clone -o canmount=noauto -o mountpoint=none"
517         ZFS_CMD="${ZFS_CMD} -o org.zol:mountpoint=${mountpoint}"
518         ZFS_CMD="${ZFS_CMD} $snap $destfs"
519         ZFS_STDERR="$(${ZFS_CMD} 2>&1)"
520         ZFS_ERROR="$?"
521         if [ "${ZFS_ERROR}" != 0 ]
522         then
523                 [ "$quiet" != "y" ] && zfs_log_failure_msg "${ZFS_ERROR}"
525                 disable_plymouth
526                 echo ""
527                 echo "Command: $ZFS_CMD"
528                 echo "Message: $ZFS_STDERR"
529                 echo "Error: $ZFS_ERROR"
530                 echo ""
531                 echo "Failed to clone snapshot."
532                 echo "Make sure that any problems are corrected and then make sure"
533                 echo "that the dataset '$destfs' exists and is bootable."
534                 shell
535         else
536                 [ "$quiet" != "y" ] && zfs_log_end_msg
537         fi
539         return 0
542 # Rollback a given snapshot.
543 rollback_snap()
545         snap="$1"
547         [ "$quiet" != "y" ] && zfs_log_begin_msg "Rollback $snap"
549         ZFS_CMD="${ZFS} rollback -Rf $snap"
550         ZFS_STDERR="$(${ZFS_CMD} 2>&1)"
551         ZFS_ERROR="$?"
552         if [ "${ZFS_ERROR}" != 0 ]
553         then
554                 [ "$quiet" != "y" ] && zfs_log_failure_msg "${ZFS_ERROR}"
556                 disable_plymouth
557                 echo ""
558                 echo "Command: $ZFS_CMD"
559                 echo "Message: $ZFS_STDERR"
560                 echo "Error: $ZFS_ERROR"
561                 echo ""
562                 echo "Failed to rollback snapshot."
563                 shell
564         else
565                 [ "$quiet" != "y" ] && zfs_log_end_msg
566         fi
568         return 0
571 # Get a list of snapshots, give them as a numbered list
572 # to the user to choose from.
573 ask_user_snap()
575         fs="$1"
577         # We need to temporarily disable debugging. Set 'debug' so we
578         # remember to enabled it again.
579         if [ -n "${ZFS_DEBUG}" ]; then
580                 unset ZFS_DEBUG
581                 set +x
582                 debug=1
583         fi
585         # Because we need the resulting snapshot, which is sent on
586         # stdout to the caller, we use stderr for our questions.
587         echo "What snapshot do you want to boot from?" > /dev/stderr
588         # shellcheck disable=SC2046
589         IFS="
590 " set -- $("${ZFS}" list -H -oname -tsnapshot -r "${fs}")
592         i=1
593         for snap in "$@"; do
594                 echo "  $i: $snap"
595                 i=$((i + 1))
596         done > /dev/stderr
598         # expr instead of test here because [ a -lt 0 ] errors out,
599         # but expr falls back to lexicographical, which works out right
600         snapnr=0
601         while expr "$snapnr" "<" 1 > /dev/null ||
602             expr "$snapnr" ">" "$#" > /dev/null
603         do
604                 printf "%s" "Snap nr [1-$#]? " > /dev/stderr
605                 read -r snapnr
606         done
608         # Re-enable debugging.
609         if [ -n "${debug}" ]; then
610                 ZFS_DEBUG=1
611                 set -x
612         fi
614         eval echo '$'"$snapnr"
617 setup_snapshot_booting()
619         snap="$1"
620         retval=0
622         # Make sure that the snapshot specified actually exists.
623         if [ -z "$(get_fs_value "${snap}" type)" ]
624         then
625                 # Snapshot does not exist (...@<null> ?)
626                 # ask the user for a snapshot to use.
627                 snap="$(ask_user_snap "${snap%%@*}")"
628         fi
630         # Separate the full snapshot ('$snap') into it's filesystem and
631         # snapshot names. Would have been nice with a split() function..
632         rootfs="${snap%%@*}"
633         snapname="${snap##*@}"
634         ZFS_BOOTFS="${rootfs}_${snapname}"
636         if ! grep -qiE '(^|[^\\](\\\\)* )(rollback)=(on|yes|1)( |$)' /proc/cmdline
637         then
638                 # If the destination dataset for the clone
639                 # already exists, destroy it. Recursively
640                 if [ -n "$(get_fs_value "${rootfs}_${snapname}" type)" ]
641                 then
642                         filesystems=$("${ZFS}" list -oname -tfilesystem -H \
643                             -r -Sname "${ZFS_BOOTFS}")
644                         for fs in $filesystems; do
645                                 destroy_fs "${fs}"
646                         done
647                 fi
648         fi
650         # Get all snapshots, recursively (might need to clone /usr, /var etc
651         # as well).
652         for s in $("${ZFS}" list -H -oname -tsnapshot -r "${rootfs}" | \
653             grep "${snapname}")
654         do
655                 if grep -qiE '(^|[^\\](\\\\)* )(rollback)=(on|yes|1)( |$)' /proc/cmdline
656                 then
657                         # Rollback snapshot
658                         rollback_snap "$s" || retval=$((retval + 1))
659                         ZFS_BOOTFS="${rootfs}"
660                 else
661                         # Setup a destination filesystem name.
662                         # Ex: Called with 'rpool/ROOT/debian@snap2'
663                         #       rpool/ROOT/debian@snap2         => rpool/ROOT/debian_snap2
664                         #       rpool/ROOT/debian/boot@snap2    => rpool/ROOT/debian_snap2/boot
665                         #       rpool/ROOT/debian/usr@snap2     => rpool/ROOT/debian_snap2/usr
666                         #       rpool/ROOT/debian/var@snap2     => rpool/ROOT/debian_snap2/var
667                         subfs="${s##"$rootfs"}"
668                         subfs="${subfs%%@"$snapname"}"
670                         destfs="${rootfs}_${snapname}" # base fs.
671                         [ -n "$subfs" ] && destfs="${destfs}$subfs" # + sub fs.
673                         # Get the mountpoint of the filesystem, to be used
674                         # with clone_snap(). If legacy or none, then use
675                         # the sub fs value.
676                         mountpoint=$(get_fs_value "${s%%@*}" mountpoint)
677                         if [ "$mountpoint" = "legacy" ] || \
678                            [ "$mountpoint" = "none" ]
679                         then
680                                 if [ -n "${subfs}" ]; then
681                                         mountpoint="${subfs}"
682                                 else
683                                         mountpoint="/"
684                                 fi
685                         fi
687                         # Clone the snapshot into its own
688                         # filesystem
689                         clone_snap "$s" "${destfs}" "${mountpoint}" || \
690                             retval=$((retval + 1))
691                 fi
692         done
694         # If we haven't return yet, we have a problem...
695         return "${retval}"
698 # ================================================================
700 # This is the main function.
701 mountroot()
703         # ----------------------------------------------------------------
704         # I N I T I A L   S E T U P
706         # ------------
707         # Run the pre-mount scripts from /scripts/local-top.
708         pre_mountroot
710         # ------------
711         # Source the default setup variables.
712         [ -r '/etc/default/zfs' ] && . /etc/default/zfs
714         # ------------
715         # Support debug option
716         if grep -qiE '(^|[^\\](\\\\)* )(zfs_debug|zfs\.debug|zfsdebug)=(on|yes|1)( |$)' /proc/cmdline
717         then
718                 ZFS_DEBUG=1
719                 mkdir /var/log
720                 #exec 2> /var/log/boot.debug
721                 set -x
722         fi
724         # ------------
725         # Load ZFS module etc.
726         if ! load_module_initrd; then
727                 disable_plymouth
728                 echo ""
729                 echo "Failed to load ZFS modules."
730                 echo "Manually load the modules and exit."
731                 shell
732         fi
734         # ------------
735         # Look for the cache file (if any).
736         [ -f "${ZPOOL_CACHE}" ] || unset ZPOOL_CACHE
737         [ -s "${ZPOOL_CACHE}" ] || unset ZPOOL_CACHE
739         # ------------
740         # Compatibility: 'ROOT' is for Debian GNU/Linux (etc),
741         #                'root' is for Redhat/Fedora (etc),
742         #                'REAL_ROOT' is for Gentoo
743         if [ -z "$ROOT" ]
744         then
745                 [ -n "$root" ] && ROOT=${root}
747                 [ -n "$REAL_ROOT" ] && ROOT=${REAL_ROOT}
748         fi
750         # ------------
751         # Where to mount the root fs in the initrd - set outside this script
752         # Compatibility: 'rootmnt' is for Debian GNU/Linux (etc),
753         #                'NEWROOT' is for RedHat/Fedora (etc),
754         #                'NEW_ROOT' is for Gentoo
755         if [ -z "$rootmnt" ]
756         then
757                 [ -n "$NEWROOT" ] && rootmnt=${NEWROOT}
759                 [ -n "$NEW_ROOT" ] && rootmnt=${NEW_ROOT}
760         fi
762         # ------------
763         # No longer set in the defaults file, but it could have been set in
764         # get_pools() in some circumstances. If it's something, but not 'yes',
765         # it's no good to us.
766         [ -n "$USE_DISK_BY_ID" ] && [ "$USE_DISK_BY_ID" != 'yes' ] && \
767             unset USE_DISK_BY_ID
769         # ----------------------------------------------------------------
770         # P A R S E   C O M M A N D   L I N E   O P T I O N S
772         # This part is the really ugly part - there's so many options and permutations
773         # 'out there', and if we should make this the 'primary' source for ZFS initrd
774         # scripting, we need/should support them all.
775         #
776         # Supports the following kernel command line argument combinations
777         # (in this order - first match win):
778         #
779         #       rpool=<pool>                    (tries to finds bootfs automatically)
780         #       bootfs=<pool>/<dataset>         (uses this for rpool - first part)
781         #       rpool=<pool> bootfs=<pool>/<dataset>
782         #       -B zfs-bootfs=<pool>/<fs>       (uses this for rpool - first part)
783         #       rpool=rpool                     (default if none of the above is used)
784         #       root=<pool>/<dataset>           (uses this for rpool - first part)
785         #       root=ZFS=<pool>/<dataset>       (uses this for rpool - first part, without 'ZFS=')
786         #       root=zfs:AUTO                   (tries to detect both pool and rootfs)
787         #       root=zfs:<pool>/<dataset>       (uses this for rpool - first part, without 'zfs:')
788         #
789         # Option <dataset> could also be <snapshot>
790         # Option <pool> could also be <guid>
792         # ------------
793         # Support force option
794         # In addition, setting one of zfs_force, zfs.force or zfsforce to
795         # 'yes', 'on' or '1' will make sure we force import the pool.
796         # This should (almost) never be needed, but it's here for
797         # completeness.
798         ZPOOL_FORCE=""
799         if grep -qiE '(^|[^\\](\\\\)* )(zfs_force|zfs\.force|zfsforce)=(on|yes|1)( |$)' /proc/cmdline
800         then
801                 ZPOOL_FORCE="-f"
802         fi
804         # ------------
805         # Look for 'rpool' and 'bootfs' parameter
806         [ -n "$rpool" ] && ZFS_RPOOL="${rpool#rpool=}"
807         [ -n "$bootfs" ] && ZFS_BOOTFS="${bootfs#bootfs=}"
809         # ------------
810         # If we have 'ROOT' (see above), but not 'ZFS_BOOTFS', then use
811         # 'ROOT'
812         [ -n "$ROOT" ] && [ -z "${ZFS_BOOTFS}" ] && ZFS_BOOTFS="$ROOT"
814         # ------------
815         # Check for the `-B zfs-bootfs=%s/%u,...` kind of parameter.
816         # NOTE: Only use the pool name and dataset. The rest is not
817         #       supported by OpenZFS (whatever it's for).
818         if [ -z "$ZFS_RPOOL" ]
819         then
820                 # The ${zfs-bootfs} variable is set at the kernel command
821                 # line, usually by GRUB, but it cannot be referenced here
822                 # directly because bourne variable names cannot contain a
823                 # hyphen.
824                 #
825                 # Reassign the variable by dumping the environment and
826                 # stripping the zfs-bootfs= prefix.  Let the shell handle
827                 # quoting through the eval command:
828                 # shellcheck disable=SC2046
829                 eval ZFS_RPOOL=$(set | sed -n -e 's,^zfs-bootfs=,,p')
830         fi
832         # ------------
833         # No root fs or pool specified - do auto detect.
834         if [ -z "$ZFS_RPOOL" ] && [ -z "${ZFS_BOOTFS}" ]
835         then
836                 # Do auto detect. Do this by 'cheating' - set 'root=zfs:AUTO'
837                 # which will be caught later
838                 ROOT='zfs:AUTO'
839         fi
841         # ----------------------------------------------------------------
842         # F I N D   A N D   I M P O R T   C O R R E C T   P O O L
844         # ------------
845         if [ "$ROOT" = "zfs:AUTO" ]
846         then
847                 # Try to detect both pool and root fs.
849                 # If we got here, that means we don't have a hint so as to
850                 # the root dataset, but with root=zfs:AUTO on cmdline,
851                 # this says "zfs:AUTO" here and interferes with checks later
852                 ZFS_BOOTFS=
854                 [ "$quiet" != "y" ] && \
855                     zfs_log_begin_msg "Attempting to import additional pools."
857                 # Get a list of pools available for import
858                 if [ -n "$ZFS_RPOOL" ]
859                 then
860                         # We've specified a pool - check only that
861                         POOLS=$ZFS_RPOOL
862                 else
863                         POOLS=$(get_pools)
864                 fi
866                 OLD_IFS="$IFS" ; IFS=";"
867                 for pool in $POOLS
868                 do
869                         [ -z "$pool" ] && continue
871                         IFS="$OLD_IFS" import_pool "$pool"
872                         IFS="$OLD_IFS" find_rootfs "$pool" && break
873                 done
874                 IFS="$OLD_IFS"
876                 [ "$quiet" != "y" ] && zfs_log_end_msg "$ZFS_ERROR"
877         else
878                 # No auto - use value from the command line option.
880                 # Strip 'zfs:' and 'ZFS='.
881                 ZFS_BOOTFS="${ROOT#*[:=]}"
883                 # Strip everything after the first slash.
884                 ZFS_RPOOL="${ZFS_BOOTFS%%/*}"
885         fi
887         # Import the pool (if not already done so in the AUTO check above).
888         if [ -n "$ZFS_RPOOL" ] && [ -z "${POOL_IMPORTED}" ]
889         then
890                 [ "$quiet" != "y" ] && \
891                     zfs_log_begin_msg "Importing ZFS root pool '$ZFS_RPOOL'"
893                 import_pool "${ZFS_RPOOL}"
894                 find_rootfs "${ZFS_RPOOL}"
896                 [ "$quiet" != "y" ] && zfs_log_end_msg
897         fi
899         if [ -z "${POOL_IMPORTED}" ]
900         then
901                 # No pool imported, this is serious!
902                 disable_plymouth
903                 echo ""
904                 echo "Command: $ZFS_CMD"
905                 echo "Message: $ZFS_STDERR"
906                 echo "Error: $ZFS_ERROR"
907                 echo ""
908                 echo "No pool imported. Manually import the root pool"
909                 echo "at the command prompt and then exit."
910                 echo "Hint: Try:  zpool import -N ${ZFS_RPOOL}"
911                 shell
912         fi
914         # In case the pool was specified as guid, resolve guid to name
915         pool="$("${ZPOOL}" get -H -o name,value name,guid | \
916             awk -v pool="${ZFS_RPOOL}" '$2 == pool { print $1 }')"
917         if [ -n "$pool" ]; then
918                 # If $ZFS_BOOTFS contains guid, replace the guid portion with $pool
919                 ZFS_BOOTFS=$(echo "$ZFS_BOOTFS" | \
920                         sed -e "s/$("${ZPOOL}" get -H -o value guid "$pool")/$pool/g")
921                 ZFS_RPOOL="${pool}"
922         fi
925         # ----------------------------------------------------------------
926         # P R E P A R E   R O O T   F I L E S Y S T E M
928         if [ -n "${ZFS_BOOTFS}" ]
929         then
930                 # Booting from a snapshot?
931                 # Will overwrite the ZFS_BOOTFS variable like so:
932                 #   rpool/ROOT/debian@snap2 => rpool/ROOT/debian_snap2
933                 echo "${ZFS_BOOTFS}" | grep -q '@' && \
934                     setup_snapshot_booting "${ZFS_BOOTFS}"
935         fi
937         if [ -z "${ZFS_BOOTFS}" ]
938         then
939                 # Still nothing! Let the user sort this out.
940                 disable_plymouth
941                 echo ""
942                 echo "Error: Unknown root filesystem - no 'bootfs' pool property and"
943                 echo "       not specified on the kernel command line."
944                 echo ""
945                 echo "Manually mount the root filesystem on $rootmnt and then exit."
946                 echo "Hint: Try:  mount -o zfsutil -t zfs ${ZFS_RPOOL-rpool}/ROOT/system $rootmnt"
947                 shell
948         fi
950         # ----------------------------------------------------------------
951         # M O U N T   F I L E S Y S T E M S
953         # * Ideally, the root filesystem would be mounted like this:
954         #
955         #     zpool import -R "$rootmnt" -N "$ZFS_RPOOL"
956         #     zfs mount -o mountpoint=/ "${ZFS_BOOTFS}"
957         #
958         #   but the MOUNTPOINT prefix is preserved on descendent filesystem
959         #   after the pivot into the regular root, which later breaks things
960         #   like `zfs mount -a` and the /proc/self/mounts refresh.
961         #
962         # * Mount additional filesystems required
963         #   Such as /usr, /var, /usr/local etc.
964         #   NOTE: Mounted in the order specified in the
965         #         ZFS_INITRD_ADDITIONAL_DATASETS variable so take care!
967         # Go through the complete list (recursively) of all filesystems below
968         # the real root dataset
969         filesystems="$("${ZFS}" list -oname -tfilesystem -H -r "${ZFS_BOOTFS}")"
970         OLD_IFS="$IFS" ; IFS="
972         for fs in $filesystems; do
973                 IFS="$OLD_IFS" mount_fs "$fs"
974         done
975         IFS="$OLD_IFS"
976         for fs in $ZFS_INITRD_ADDITIONAL_DATASETS; do
977                 mount_fs "$fs"
978         done
980         touch /run/zfs_unlock_complete
981         if [ -e /run/zfs_unlock_complete_notify ]; then
982                 read -r < /run/zfs_unlock_complete_notify
983         fi
985         # ------------
986         # Debugging information
987         if [ -n "${ZFS_DEBUG}" ]
988         then
989                 #exec 2>&1-
991                 echo "DEBUG: imported pools:"
992                 "${ZPOOL}" list -H
993                 echo
995                 echo "DEBUG: mounted ZFS filesystems:"
996                 mount | grep zfs
997                 echo
999                 echo "=> waiting for ENTER before continuing because of 'zfsdebug=1'. "
1000                 printf "%s" "   'c' for shell, 'r' for reboot, 'ENTER' to continue. "
1001                 read -r b
1003                 [ "$b" = "c" ] && /bin/sh
1004                 [ "$b" = "r" ] && reboot -f
1006                 set +x
1007         fi
1009         # ------------
1010         # Run local bottom script
1011         if command -v run_scripts > /dev/null 2>&1
1012         then
1013                 if [ -f "/scripts/local-bottom" ] || [ -d "/scripts/local-bottom" ]
1014                 then
1015                         [ "$quiet" != "y" ] && \
1016                             zfs_log_begin_msg "Running /scripts/local-bottom"
1017                         run_scripts /scripts/local-bottom
1018                         [ "$quiet" != "y" ] && zfs_log_end_msg
1019                 fi
1020         fi