dracut-functions: use /proc/self/mountinfo, instead of /proc/mounts
[dracut.git] / dracut-functions
blobf53d5e343ce28e0a7d0b5b3df30677a467dd3c07
1 #!/bin/bash
3 # functions used by dracut and other tools.
5 # Copyright 2005-2009 Red Hat, Inc. All rights reserved.
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 2 of the License, or
10 # (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
21 IF_RTLD=""
22 IF_dynamic=""
24 # Generic substring function. If $2 is in $1, return 0.
25 strstr() { [[ $1 =~ $2 ]]; }
27 # Create all subdirectories for given path without creating the last element.
28 # $1 = path
29 mksubdirs() { mkdir -p ${1%/*}; }
31 # Version comparision function. Assumes Linux style version scheme.
32 # $1 = version a
33 # $2 = comparision op (gt, ge, eq, le, lt, ne)
34 # $3 = version b
35 vercmp() {
36 local n1=(${1//./ }) op=$2 n2=(${3//./ }) i res
38 for ((i=0; ; i++))
40 if [[ ! ${n1[i]}${n2[i]} ]]; then res=0
41 elif ((${n1[i]:-0} > ${n2[i]:-0})); then res=1
42 elif ((${n1[i]:-0} < ${n2[i]:-0})); then res=2
43 else continue
45 break
46 done
48 case $op in
49 gt) ((res == 1));;
50 ge) ((res != 2));;
51 eq) ((res == 0));;
52 le) ((res != 1));;
53 lt) ((res == 2));;
54 ne) ((res != 0));;
55 esac
58 # Log initrd creation.
59 if ! [[ $dracutlogfile ]]; then
60 [[ $dracutbasedir = /usr/share/dracut ]] && \
61 dracutlogfile=/var/log/dracut.log || \
62 dracutlogfile=/tmp/dracut.log
63 # [[ -w $dracutlogfile ]] || dracutlogfile=/tmp/dracut.log
64 if [[ -w $dracutlogfile ]]; then
65 >"$dracutlogfile"
69 dwarning() {
70 echo "W: $@" >&2
71 [[ -w $dracutlogfile ]] && echo "W: $@" >>"$dracutlogfile"
74 dinfo() {
75 [[ $beverbose ]] && echo "I: $@" >&2
76 [[ -w $dracutlogfile ]] && echo "I: $@" >>"$dracutlogfile"
79 derror() {
80 echo "E: $@" >&2
81 [[ -w $dracutlogfile ]] && echo "E: $@" >>"$dracutlogfile"
84 # Function prints global variables in format name=value line by line.
85 # $@ = list of global variables' name
86 print_vars() {
87 local var value
89 for var in $@
91 value=$(eval echo \$$var)
92 [[ ${value} ]] && echo "${var}=\"${value}\""
93 done
96 get_fs_env() {
97 eval $(udevadm info --query=env --name=$1|egrep 'ID_FS_(TYPE|UUID)=')
98 [[ $ID_FS_TYPE ]] && return
100 if [[ -x /lib/udev/vol_id ]]; then
101 eval $(/lib/udev/vol_id --export $1)
102 elif find_binary blkid >/dev/null; then
103 eval $(blkid -o udev $1)
104 else
105 return 1
109 get_fs_type() (
110 get_fs_env $1 || return
111 echo $ID_FS_TYPE
114 get_fs_uuid() (
115 get_fs_env $1 || return
116 echo $ID_FS_UUID
119 # finds the major:minor of the block device backing the root filesystem.
120 find_block_device() {
121 local majmin rootdev blkdev fs type opts misc
122 while read a b majmin c mpt opts d fs type opts misc; do
123 [[ $mpt = $1 ]] && { echo $majmin; break; } # we have a winner!
124 done < /proc/self/mountinfo
127 find_root_block_device() { find_block_device /; }
129 # Walk all the slave relationships for a given block device.
130 # Stop when our helper function returns success
131 # $1 = function to call on every found block device
132 # $2 = block device in major:minor format
133 check_block_and_slaves() {
134 local x
135 [[ -b /dev/block/$2 ]] || return 1 # Not a block device? So sorry.
136 "$1" $2 && return
137 check_vol_slaves "$@" && return 0
138 if [[ -f "/sys/dev/block/$2/../dev" ]]; then
139 check_block_and_slaves $1 $(cat "/sys/dev/block/$2/../dev") && return 0
141 [[ -d /sys/dev/block/$2/slaves ]] || return 1
142 for x in /sys/dev/block/$2/slaves/*/dev; do
143 [[ -f $x ]] || continue
144 check_block_and_slaves $1 $(cat "$x") && return 0
145 done
146 return 1
149 get_numeric_dev() {
150 ls -lH "$1" | { read a b c d maj min rest; printf "%d:%d" ${maj%%,} $min;}
153 # ugly workaround for the lvm design
154 # There is no volume group device,
155 # so, there are no slave devices for volume groups.
156 # Logical volumes only have the slave devices they really live on,
157 # but you cannot create the logical volume without the volume group.
158 # And the volume group might be bigger than the devices the LV needs.
159 check_vol_slaves() {
160 for i in /dev/mapper/*; do
161 lv=$(get_numeric_dev $i)
162 if [[ $lv = $2 ]]; then
163 vg=$(lvm lvs --noheadings -o vg_name $i 2>/dev/null)
164 # strip space
165 vg=$(echo $vg)
166 if [[ $vg ]]; then
167 for pv in $(lvm vgs --noheadings -o pv_name "$vg" 2>/dev/null); \
169 check_block_and_slaves $1 $(get_numeric_dev $pv) \
170 && return 0
171 done
174 done
175 return 1
178 # Install a directory, keeping symlinks as on the original system.
179 # Example: if /lib64 points to /lib on the host, "inst_dir /lib/file"
180 # will create ${initdir}/lib64, ${initdir}/lib64/file,
181 # and a symlink ${initdir}/lib -> lib64.
182 inst_dir() {
183 local dir="$1"
184 [[ -e "${initdir}$dir" ]] && return 0
186 # iterate over parent directories
187 local file=""
188 local IFS="/"
189 for part in $dir; do
190 [ -z "$part" ] && continue
191 file="$file/$part"
192 [[ -e "${initdir}$file" ]] && continue
194 if [ -L "$file" ]; then
195 # create link as the original
196 local target=$(readlink "$file")
197 ln -sfn "$target" "${initdir}$file" || return 1
198 # resolve relative path and recursively install destionation
199 [[ "$target" = "${target##*/}" ]] && target="${file%/*}/$target"
200 inst_dir "$target"
201 else
202 # create directory
203 mkdir -p "${initdir}$file" || return 1
205 done
208 # $1 = file to copy to ramdisk
209 # $2 (optional) Name for the file on the ramdisk
210 # Location of the image dir is assumed to be $initdir
211 # We never overwrite the target if it exists.
212 inst_simple() {
213 local src target
214 [[ -f $1 ]] || return 1
215 src=$1 target="${2:-$1}"
216 if ! [[ -d ${initdir}$target ]]; then
217 [[ -e ${initdir}$target ]] && return 0
218 inst_dir "${target%/*}"
220 dinfo "Installing $src"
221 cp -pfL "$src" "${initdir}$target"
224 # find symlinks linked to given library file
225 # $1 = library file
226 # Function searches for symlinks by stripping version numbers appended to
227 # library filename, checks if it points to the same target and finally
228 # prints the list of symlinks to stdout.
230 # Example:
231 # rev_lib_symlinks libfoo.so.8.1
232 # output: libfoo.so.8 libfoo.so
233 # (Only if libfoo.so.8 and libfoo.so exists on host system.)
234 rev_lib_symlinks() {
235 [[ ! $1 ]] && return 0
237 local fn="$1" orig="$(readlink -f "$1")" links=''
239 [[ ${fn} =~ .*\.so\..* ]] || return 1
241 until [[ ${fn##*.} == so ]]; do
242 fn="${fn%.*}"
243 [[ -L ${fn} && $(readlink -f "${fn}") == ${orig} ]] && links+=" ${fn}"
244 done
246 echo ${links}
249 # Same as above, but specialized to handle dynamic libraries.
250 # It handles making symlinks according to how the original library
251 # is referenced.
252 inst_library() {
253 local src=$1 dest=${2:-$1} lib reallib symlink
254 [[ -e $initdir$dest ]] && return 0
255 if [[ -L $src ]]; then
256 reallib=$(readlink -f "$src")
257 lib=${src##*/}
258 inst_simple "$reallib" "$reallib"
259 inst_dir "${dest%/*}"
260 (cd "${initdir}${dest%/*}" && ln -s "$reallib" "$lib")
261 else
262 inst_simple "$src" "$dest"
265 # Create additional symlinks. See rev_symlinks description.
266 for symlink in $(rev_lib_symlinks $src) $(rev_lib_symlinks $reallib); do
267 [[ ! -e $initdir$symlink ]] && {
268 dinfo "Creating extra symlink: $symlink"
269 inst_symlink $symlink
271 done
274 # find a binary. If we were not passed the full path directly,
275 # search in the usual places to find the binary.
276 find_binary() {
277 local binpath="/bin /sbin /usr/bin /usr/sbin" p
278 [[ -z ${1##/*} && -x $1 ]] && { echo $1; return 0; }
279 for p in $binpath; do
280 [[ -x $p/$1 ]] && { echo "$p/$1"; return 0; }
281 done
282 return 1
285 # Same as above, but specialized to install binary executables.
286 # Install binary executable, and all shared library dependencies, if any.
287 inst_binary() {
288 local bin target
289 bin=$(find_binary "$1") || return 1
290 target=${2:-$bin}
291 inst_symlink $bin $target && return 0
292 local LDSO NAME IO FILE ADDR I1 n f TLIBDIR
293 [[ -e $initdir$target ]] && return 0
294 # I love bash!
295 LC_ALL=C ldd $bin 2>/dev/null | while read line; do
296 [[ $line = 'not a dynamic executable' ]] && return 1
297 if [[ $line =~ not\ found ]]; then
298 derror "Missing a shared library required by $bin."
299 derror "Run \"ldd $bin\" to find out what it is."
300 derror "dracut cannot create an initrd."
301 exit 1
303 so_regex='([^ ]*/lib[^/]*/[^ ]*\.so[^ ]*)'
304 [[ $line =~ $so_regex ]] || continue
305 FILE=${BASH_REMATCH[1]}
306 [[ -e ${initdir}$FILE ]] && continue
307 # see if we are loading an optimized version of a shared lib.
308 lib_regex='^(/lib[^/]*).*'
309 if [[ $FILE =~ $lib_regex ]]; then
310 TLIBDIR=${BASH_REMATCH[1]}
311 BASE=${FILE##*/}
312 # prefer nosegneg libs, then unoptimized ones.
313 for f in "$TLIBDIR/i686/nosegneg" "$TLIBDIR"; do
314 [[ -e $f/$BASE ]] || continue
315 FILE=$f/$BASE
316 break
317 done
318 inst_library "$FILE" "$TLIBDIR/$BASE"
319 IF_dynamic=yes
320 continue
322 inst_library "$FILE"
323 done
324 inst_simple "$bin" "$target"
327 # same as above, except for shell scripts.
328 # If your shell script does not start with shebang, it is not a shell script.
329 inst_script() {
330 [[ -f $1 ]] || return 1
331 local line
332 read -r -n 80 line <"$1"
333 # If debug is set, clean unprintable chars to prevent messing up the term
334 [[ $debug ]] && line=$(echo -n "$line" | tr -c -d '[:print:][:space:]')
335 shebang_regex='(#! *)(/[^ ]+).*'
336 [[ $line =~ $shebang_regex ]] || return 1
337 inst "${BASH_REMATCH[2]}" && inst_simple "$@"
340 # same as above, but specialized for symlinks
341 inst_symlink() {
342 local src=$1 target=$initdir${2:-$1} realsrc
343 [[ -L $1 ]] || return 1
344 [[ -L $target ]] && return 0
345 realsrc=$(readlink -f "$src")
346 [[ $realsrc = ${realsrc##*/} ]] && realsrc=${src%/*}/$realsrc
347 inst "$realsrc" && ln -s "$realsrc" "$target"
350 # find a udev rule in the usual places.
351 find_rule() {
352 [[ -f $1 ]] && { echo "$1"; return 0; }
353 for r in . /lib/udev/rules.d /etc/udev/rules.d $dracutbasedir/rules.d; do
354 [[ -f $r/$1 ]] && { echo "$r/$1"; return 0; }
355 done
356 return 1
359 # udev rules always get installed in the same place, so
360 # create a function to install them to make life simpler.
361 inst_rules() {
362 local target=/etc/udev/rules.d rule found
364 inst_dir "/lib/udev/rules.d"
365 inst_dir "$target"
366 for rule in "$@"; do
367 found=$(find_rule "$rule") && \
368 inst_simple "$found" "$target/${found##*/}" \
369 || dinfo "Skipping udev rule: $rule"
370 done
373 # general purpose installation function
374 # Same args as above.
375 inst() {
376 case $# in
377 1) ;;
379 [[ -z $initdir ]] && [[ -d $2 ]] && export initdir=$2
380 [[ $initdir = $2 ]] && set $1
383 [[ -z $initdir ]] && export initdir=$2
384 set $1 $3
387 derror "inst only takes 1 or 2 or 3 arguments"
388 exit 1
390 esac
391 for x in inst_symlink inst_script inst_binary inst_simple; do
392 $x "$@" && return 0
393 done
394 return 1
397 # install function specialized for hooks
398 # $1 = type of hook, $2 = hook priority (lower runs first), $3 = hook
399 # All hooks should be POSIX/SuS compliant, they will be sourced by init.
400 inst_hook() {
401 if ! [[ -f $3 ]]; then
402 derror "Cannot install a hook ($3) that does not exist."
403 derror "Aborting initrd creation."
404 exit 1
405 elif ! strstr "$hookdirs" "$1"; then
406 derror "No such hook type $1. Aborting initrd creation."
407 exit 1
409 inst_simple "$3" "/${1}/${2}${3##*/}"
412 dracut_install() {
413 if [[ $1 = '-o' ]]; then
414 local optional=yes
415 shift
417 while (($# > 0)); do
418 if ! inst "$1" ; then
419 if [[ $optional = yes ]]; then
420 dwarning "Skipping program $1 as it cannot be found and is flagged to be optional"
421 else
422 derror "Failed to install $1"
423 exit 1
426 shift
427 done
430 # install function decompressing the target and handling symlinks
431 # $@ = list of compressed (gz or bz2) files or symlinks pointing to such files
433 # Function install targets in the same paths inside overlay but decompressed
434 # and without extensions (.gz, .bz2).
435 inst_decompress() {
436 local src dst realsrc realdst cmd
438 for src in $@
440 case ${src} in
441 *.gz) cmd='gzip -d' ;;
442 *.bz2) cmd='bzip2 -d' ;;
443 *) return 1 ;;
444 esac
446 if [[ -L ${src} ]]
447 then
448 realsrc="$(readlink -f ${src})" # symlink target with extension
449 dst="${src%.*}" # symlink without extension
450 realdst="${realsrc%.*}" # symlink target without extension
451 mksubdirs "${initdir}/${src}"
452 # Create symlink without extension to target without extension.
453 ln -s "${realdst}" "${initdir}/${dst}"
456 # If the source is symlink we operate on its target.
457 [[ ${realsrc} ]] && src=${realsrc}
458 inst ${src}
459 # Decompress with chosen tool. We assume that tool changes name e.g.
460 # from 'name.gz' to 'name'.
461 ${cmd} "${initdir}${src}"
462 done
465 # It's similar to above, but if file is not compressed, performs standard
466 # install.
467 # $@ = list of files
468 inst_opt_decompress() {
469 local src
471 for src in $@
473 inst_decompress "${src}" || inst "${src}"
474 done
477 check_module_deps() {
478 local moddir dep ret
479 # if we are already set to be loaded, we do not have to be checked again.
480 strstr " $mods_to_load " " $1 " && return
481 strstr " $omit_dracutmodules " " $1 " && return 1
482 # turn a module name into a directory, if we can.
483 moddir=$(echo ${dracutbasedir}/modules.d/??${1})
484 [[ -d $moddir && -x $moddir/install ]] || return 1
485 # if we do not have a check script, we are unconditionally included
486 if [[ -x $moddir/check ]]; then
487 "$moddir/check"
488 ret=$?
489 # a return value of 255 = load module only as a dependency.
490 ((ret==0||ret==255)) || return 1
491 for dep in $("$moddir/check" -d); do
492 check_module_deps "$dep" && continue
493 dwarning "Dependency $mod failed."
494 return 1
495 done
497 mods_to_load+=" $1 "
500 should_source_module() {
501 local dep
502 local ret
503 if [[ $kernel_only = yes ]]; then
504 [[ -x $1/installkernel ]] && return 0
505 return 1
507 [[ -x $1/install ]] || [[ -x $1/installkernel ]] || return 1
508 [[ -x $1/check ]] || return 0
509 "$1/check" $hostonly || continue
510 for dep in $("$1/check" -d); do
511 check_module_deps "$dep" && continue
512 dwarning "Cannot load dracut module \"$mod\", dependencies failed."
513 return 1
514 done
517 check_modules() {
518 local modcheck;
519 local mod;
520 for moddir in "$dracutbasedir/modules.d"/[0-9][0-9]*; do
521 local mod=${moddir##*/}; mod=${mod#[0-9][0-9]}
522 # If we are already scheduled to be loaded, no need to check again.
523 strstr " $mods_to_load " " $mod " && continue
524 # This should never happen, but...
525 [[ -d $moddir ]] || continue
526 strstr " $omit_dracutmodules " " $mod " && continue
528 if ! strstr " $dracutmodules $add_dracutmodules " " $mod "; then
529 # module not in our list
530 if [[ $dracutmodules = all ]]; then
531 # check, if we can install this module
532 should_source_module "$moddir" || continue
533 else
534 # skip this module
535 continue
537 else
538 if [ -x "$moddir/check" ] \
539 && "$moddir/check" -d > /dev/null 2>&1; then
540 check_module_deps "$mod" || {
541 dwarning "Cannot load dracut module \"$mod\", dependencies failed."
542 continue
547 mods_to_load+=" $mod "
548 done
550 modcheck=$add_dracutmodules
551 [[ $dracutmodules != all ]] && modcheck="$m $dracutmodules"
552 for mod in $modcheck; do
553 strstr " $mods_to_load " " $mod " && continue
554 strstr " $omit_dracutmodules " " $mod " && continue
555 dwarning "Dracut module \"$mod\" cannot be found."
556 done
559 # Install a single kernel module along with any firmware it may require.
560 # $1 = full path to kernel module to install
561 install_kmod_with_fw() {
562 local modname=${1##*/} fwdir found
563 modname=${modname%.ko*}
564 inst_simple "$1" "/lib/modules/$kernel/${1##*/lib/modules/$kernel/}" || \
565 return 0 # no need to go further if the module is already installed
566 for fw in $(modinfo -k $kernel -F firmware $1 2>/dev/null); do
567 found=''
568 for fwdir in $fw_dir; do
569 if [[ -d $fwdir && -f $fwdir/$fw ]]; then
570 inst_simple "$fwdir/$fw" "/lib/firmware/$fw"
571 found=yes
573 done
574 if [[ $found != yes ]]; then
575 dinfo "Possible missing firmware \"${fw}\" for kernel module \"${mod}.ko\""
577 done
580 # Do something with all the dependencies of a kernel module.
581 # Note that kernel modules depend on themselves using the technique we use
582 # $1 = function to call for each dependency we find
583 # It will be passed the full path to the found kernel module
584 # $2 = module to get dependencies for
585 # rest of args = arguments to modprobe
586 for_each_kmod_dep() {
587 local func=$1 kmod=$2 cmd modpapth options
588 shift 2
589 modprobe "$@" --ignore-install --show-depends $kmod 2>/dev/null | \
590 while read cmd modpath options; do
591 [[ $cmd = insmod ]] || continue
592 $func $modpath
593 done
596 # filter kernel modules to install certain modules that meet specific
597 # requirements.
598 # $1 = function to call with module name to filter.
599 # This function will be passed the full path to the module to test.
600 # The behaviour of this function can vary depending on whether $hostonly is set.
601 # If it is, we will only look at modules that are already in memory.
602 # If it is not, we will look at all kernel modules
603 # This function returns the full filenames of modules that match $1
604 filter_kernel_modules () (
605 if ! [[ $hostonly ]]; then
606 filtercmd='find "$srcmods/kernel/drivers" -name "*.ko" -o -name "*.ko.gz"'
607 else
608 filtercmd='cut -d " " -f 1 </proc/modules|xargs modinfo -F filename -k $kernel'
610 for modname in $(eval $filtercmd); do
611 case $modname in
612 *.ko)
613 "$1" "$modname" && echo "$modname"
615 *.ko.gz)
616 gzip -dc "$modname" > $initdir/$$.ko
617 $1 $initdir/$$.ko && echo "$modname"
618 rm -f $initdir/$$.ko
620 esac
621 done
624 # install kernel modules along with all their dependencies.
625 instmods() {
626 [[ $no_kernel = yes ]] && return
627 local mod mpargs modpath modname cmd moddirname
628 while (($# > 0)); do
629 mod=${1%.ko*}
630 case $mod in
631 =*) # This introduces 2 incompatible meanings for =* arguments
632 # to instmods. We need to decide which one to keep.
633 if [[ $mod = =ata && -f $srcmods/modules.block ]] ; then
634 instmods $mpargs $(egrep 'ata|ahci' "${srcmods}/modules.block")
635 elif [ -f $srcmods/modules.${mod#=} ]; then
636 instmods $mpargs $(cat ${srcmods}/modules.${mod#=} )
637 else
638 instmods $mpargs $(find "$srcmods" -path "*/${mod#=}/*")
641 --*)
642 mod=${mod##*/}
643 mpargs+=" $mod";;
644 i2o_scsi)
645 # Must never run this diagnostic-only module
646 shift; continue;
649 mod=${mod##*/}
650 # if we are already installed, skip this module and go on
651 # to the next one.
652 [[ -f $initdir/$1 ]] && { shift; continue; }
653 # If we are building a host-specific initramfs and this
654 # module is not already loaded, move on to the next one.
655 [[ $hostonly ]] && ! grep -qe "\<${mod//-/_}\>" /proc/modules && \
656 ! echo $add_drivers | grep -qe "\<${mod}\>" && {
657 shift; continue;
660 # We use '-d' option in modprobe only if modules prefix path
661 # differs from default '/'. This allows us to use Dracut with
662 # old version of modprobe which doesn't have '-d' option.
663 moddirname=${srcmods%%/lib/modules/*}
664 [[ -n ${moddirname} ]] && moddirname="-d ${moddirname}/"
666 # ok, load the module, all its dependencies, and any firmware
667 # it may require
668 for_each_kmod_dep install_kmod_with_fw $mod \
669 --set-version $kernel ${moddirname}
671 esac
672 shift
673 done
676 # vim:ts=8:sw=4:sts=4:et