]> git.ipfire.org Git - thirdparty/dracut.git/blob - dracut-functions.sh
Renamed all shell scripts to *.sh
[thirdparty/dracut.git] / dracut-functions.sh
1 #!/bin/bash
2 # -*- mode: shell-script; indent-tabs-mode: nil; sh-basic-offset: 4; -*-
3 # ex: ts=8 sw=4 sts=4 et filetype=sh
4 #
5 # functions used by dracut and other tools.
6 #
7 # Copyright 2005-2009 Red Hat, Inc. All rights reserved.
8 #
9 # This program is free software; you can redistribute it and/or modify
10 # it under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 2 of the License, or
12 # (at your option) any later version.
13 #
14 # This program is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with this program. If not, see <http://www.gnu.org/licenses/>.
21 #
22
23 if ! [[ $dracutbasedir ]]; then
24 dracutbasedir=${BASH_SOURCE[0]%/*}
25 [[ $dracutbasedir = "dracut-functions" ]] && dracutbasedir="."
26 [[ $dracutbasedir ]] || dracutbasedir="."
27 dracutbasedir="$(readlink -f $dracutbasedir)"
28 fi
29
30 if ! type dinfo >/dev/null 2>&1; then
31 . "$dracutbasedir/dracut-logger.sh"
32 dlog_init
33 fi
34
35 # export standard hookdirs
36 [[ $hookdirs ]] || {
37 hookdirs="cmdline pre-udev pre-trigger netroot initqueue pre-mount"
38 hookdirs+=" pre-pivot mount emergency shutdown-emergency shutdown cleanup"
39 export hookdirs
40 }
41
42 # Generic substring function. If $2 is in $1, return 0.
43 strstr() { [[ $1 =~ $2 ]]; }
44
45 # Create all subdirectories for given path without creating the last element.
46 # $1 = path
47 mksubdirs() { mkdir -m 0755 -p ${1%/*}; }
48
49 # Version comparision function. Assumes Linux style version scheme.
50 # $1 = version a
51 # $2 = comparision op (gt, ge, eq, le, lt, ne)
52 # $3 = version b
53 vercmp() {
54 local _n1=(${1//./ }) _op=$2 _n2=(${3//./ }) _i _res
55
56 for ((_i=0; ; _i++))
57 do
58 if [[ ! ${_n1[_i]}${_n2[_i]} ]]; then _res=0
59 elif ((${_n1[_i]:-0} > ${_n2[_i]:-0})); then _res=1
60 elif ((${_n1[_i]:-0} < ${_n2[_i]:-0})); then _res=2
61 else continue
62 fi
63 break
64 done
65
66 case $_op in
67 gt) ((_res == 1));;
68 ge) ((_res != 2));;
69 eq) ((_res == 0));;
70 le) ((_res != 1));;
71 lt) ((_res == 2));;
72 ne) ((_res != 0));;
73 esac
74 }
75
76 # is_func <command>
77 # Check whether $1 is a function.
78 is_func() {
79 [[ $(type -t $1) = "function" ]]
80 }
81
82 # Function prints global variables in format name=value line by line.
83 # $@ = list of global variables' name
84 print_vars() {
85 local _var _value
86
87 for _var in $@
88 do
89 _value=$(eval echo \$$_var)
90 [[ ${_value} ]] && echo "${_var}=\"${_value}\""
91 done
92 }
93
94 # normalize_path <path>
95 # Prints the normalized path, where it removes any duplicated
96 # and trailing slashes.
97 # Example:
98 # $ normalize_path ///test/test//
99 # /test/test
100 normalize_path() {
101 shopt -q -s extglob
102 set -- "${1//+(\/)//}"
103 shopt -q -u extglob
104 echo "${1%/}"
105 }
106
107 # convert_abs_rel <from> <to>
108 # Prints the relative path, when creating a symlink to <to> from <from>.
109 # Example:
110 # $ convert_abs_rel /usr/bin/test /bin/test-2
111 # ../../bin/test-2
112 # $ ln -s $(convert_abs_rel /usr/bin/test /bin/test-2) /usr/bin/test
113 convert_abs_rel() {
114 local __current __absolute __abssize __cursize __newpath __oldifs
115 local -i __i __level
116
117 set -- "$(normalize_path "$1")" "$(normalize_path "$2")"
118
119 # corner case #1 - self looping link
120 [[ "$1" == "$2" ]] && { echo "${1##*/}"; return; }
121
122 # corner case #2 - own dir link
123 [[ "${1%/*}" == "$2" ]] && { echo "."; return; }
124
125 __oldifs="$IFS"
126 IFS="/"
127 __current=($1)
128 __absolute=($2)
129 IFS="$__oldifs"
130
131 __abssize=${#__absolute[@]}
132 __cursize=${#__current[@]}
133
134 while [[ ${__absolute[__level]} == ${__current[__level]} ]]
135 do
136 (( __level++ ))
137 if (( __level > __abssize || __level > __cursize ))
138 then
139 break
140 fi
141 done
142
143 for ((__i = __level; __i < __cursize-1; __i++))
144 do
145 if ((__i > __level))
146 then
147 __newpath=$__newpath"/"
148 fi
149 __newpath=$__newpath".."
150 done
151
152 for ((__i = __level; __i < __abssize; __i++))
153 do
154 if [[ -n $__newpath ]]
155 then
156 __newpath=$__newpath"/"
157 fi
158 __newpath=$__newpath${__absolute[__i]}
159 done
160
161 echo "$__newpath"
162 }
163
164 # get_fs_env <device>
165 # Get and set the ID_FS_TYPE and ID_FS_UUID variable from udev for a device.
166 # Example:
167 # $ get_fs_env /dev/sda2; echo $ID_FS_TYPE; echo $ID_FS_UUID
168 # ext4
169 # 551a39aa-4ae9-4e70-a262-ef665cadb574
170 get_fs_env() {
171 [[ $1 ]] || return
172 unset ID_FS_TYPE
173 unset ID_FS_UUID
174 eval $(udevadm info --query=env --name=$1|egrep 'ID_FS_(TYPE|UUID)=')
175 [[ $ID_FS_TYPE ]] && return
176
177 if [[ -x /lib/udev/vol_id ]]; then
178 eval $(/lib/udev/vol_id --export $1)
179 elif find_binary blkid >/dev/null; then
180 eval $(blkid -o udev $1)
181 else
182 return 1
183 fi
184 }
185
186 # get_fs_uuid <device>
187 # Prints the filesystem UUID for a device.
188 # Example:
189 # $ get_fs_uuid /dev/sda2
190 # 551a39aa-4ae9-4e70-a262-ef665cadb574
191 get_fs_uuid() (
192 get_fs_env $1 || return
193 echo $ID_FS_UUID
194 )
195
196 # get_fs_type <device>
197 # Prints the filesystem type for a device.
198 # Example:
199 # $ get_fs_type /dev/sda1
200 # ext4
201 get_fs_type() (
202 [[ $1 ]] || return
203 if [[ $1 != ${1#/dev/block/nfs:} ]] \
204 || [[ $1 != ${1#/dev/block/nfs3:} ]] \
205 || [[ $1 != ${1#/dev/block/nfs4:} ]]; then
206 echo "nfs"
207 return
208 fi
209 if get_fs_env $1; then
210 echo $ID_FS_TYPE
211 return
212 fi
213 find_dev_fstype $1
214 )
215
216 # get_maj_min <device>
217 # Prints the major and minor of a device node.
218 # Example:
219 # $ get_maj_min /dev/sda2
220 # 8:2
221 get_maj_min() {
222 local _dev
223 _dev=$(stat -L -c '$((0x%t)):$((0x%T))' "$1" 2>/dev/null)
224 _dev=$(eval "echo $_dev")
225 echo $_dev
226 }
227
228 # find_block_device <mountpoint>
229 # Prints the major and minor number of the block device
230 # for a given mountpoint.
231 # Unless $use_fstab is set to "yes" the functions
232 # uses /proc/self/mountinfo as the primary source of the
233 # information and only falls back to /etc/fstab, if the mountpoint
234 # is not found there.
235 # Example:
236 # $ find_block_device /usr
237 # 8:4
238 find_block_device() {
239 local _x _mpt _majmin _dev _fs _maj _min
240 if [[ $use_fstab != yes ]]; then
241 while read _x _x _majmin _x _mpt _x _x _fs _dev _x; do
242 [[ $_mpt = $1 ]] || continue
243 [[ $_fs = nfs ]] && { echo $_dev; return 0;}
244 [[ $_fs = nfs3 ]] && { echo $_dev; return 0;}
245 [[ $_fs = nfs4 ]] && { echo $_dev; return 0;}
246 [[ $_fs = btrfs ]] && {
247 get_maj_min $_dev
248 return 0;
249 }
250 if [[ ${_majmin#0:} = $_majmin ]]; then
251 echo $_majmin
252 return 0 # we have a winner!
253 fi
254 done < /proc/self/mountinfo
255 fi
256 # fall back to /etc/fstab
257 while read _dev _mpt _fs _x; do
258 if [[ $_mpt = $1 ]]; then
259 [[ $_fs = nfs ]] && { echo $_dev; return 0;}
260 [[ $_fs = nfs3 ]] && { echo $_dev; return 0;}
261 [[ $_fs = nfs4 ]] && { echo $_dev; return 0;}
262 [[ $_dev != ${_dev#UUID=} ]] && _dev=/dev/disk/by-uuid/${_dev#UUID=}
263 [[ $_dev != ${_dev#LABEL=} ]] && _dev=/dev/disk/by-label/${_dev#LABEL=}
264 [[ -b $_dev ]] || return 1 # oops, not a block device.
265 get_maj_min "$_dev" && return 0
266 fi
267 done < /etc/fstab
268
269 return 1
270 }
271
272 # find_dev_fstype <device>
273 # Echo the filesystem type for a given device.
274 # /proc/self/mountinfo is taken as the primary source of information
275 # and /etc/fstab is used as a fallback.
276 # No newline is appended!
277 # Example:
278 # $ find_dev_fstype /dev/sda2;echo
279 # ext4
280 find_dev_fstype() {
281 local _x _mpt _majmin _dev _fs _maj _min
282 while read _x _x _majmin _x _mpt _x _x _fs _dev _x; do
283 [[ $_dev = $1 ]] || continue
284 echo -n $_fs;
285 return 0;
286 done < /proc/self/mountinfo
287
288 # fall back to /etc/fstab
289 while read _dev _mpt _fs _x; do
290 [[ $_dev = $1 ]] || continue
291 echo -n $_fs;
292 return 0;
293 done < /etc/fstab
294
295 return 1
296 }
297
298 # finds the major:minor of the block device backing the root filesystem.
299 find_root_block_device() { find_block_device /; }
300
301 # for_each_host_dev_fs <func>
302 # Execute "<func> <dev> <filesystem>" for every "<dev>|<fs>" pair found
303 # in ${host_fs_types[@]}
304 for_each_host_dev_fs()
305 {
306 local _func="$1"
307 local _dev
308 local _fs
309 for f in ${host_fs_types[@]}; do
310 OLDIFS="$IFS"
311 IFS="|"
312 set -- $f
313 IFS="$OLDIFS"
314 _dev="$1"
315 [[ -b "$_dev" ]] || continue
316 _fs="$2"
317 $_func $_dev $_fs
318 done
319 }
320
321 # Walk all the slave relationships for a given block device.
322 # Stop when our helper function returns success
323 # $1 = function to call on every found block device
324 # $2 = block device in major:minor format
325 check_block_and_slaves() {
326 local _x
327 [[ -b /dev/block/$2 ]] || return 1 # Not a block device? So sorry.
328 "$1" $2 && return
329 check_vol_slaves "$@" && return 0
330 if [[ -f /sys/dev/block/$2/../dev ]]; then
331 check_block_and_slaves $1 $(cat "/sys/dev/block/$2/../dev") && return 0
332 fi
333 [[ -d /sys/dev/block/$2/slaves ]] || return 1
334 for _x in /sys/dev/block/$2/slaves/*/dev; do
335 [[ -f $_x ]] || continue
336 check_block_and_slaves $1 $(cat "$_x") && return 0
337 done
338 return 1
339 }
340
341 # ugly workaround for the lvm design
342 # There is no volume group device,
343 # so, there are no slave devices for volume groups.
344 # Logical volumes only have the slave devices they really live on,
345 # but you cannot create the logical volume without the volume group.
346 # And the volume group might be bigger than the devices the LV needs.
347 check_vol_slaves() {
348 local _lv _vg _pv
349 for i in /dev/mapper/*; do
350 _lv=$(get_maj_min $i)
351 if [[ $_lv = $2 ]]; then
352 _vg=$(lvm lvs --noheadings -o vg_name $i 2>/dev/null)
353 # strip space
354 _vg=$(echo $_vg)
355 if [[ $_vg ]]; then
356 for _pv in $(lvm vgs --noheadings -o pv_name "$_vg" 2>/dev/null)
357 do
358 check_block_and_slaves $1 $(get_maj_min $_pv) && return 0
359 done
360 fi
361 fi
362 done
363 return 1
364 }
365
366 # Install a directory, keeping symlinks as on the original system.
367 # Example: if /lib points to /lib64 on the host, "inst_dir /lib/file"
368 # will create ${initdir}/lib64, ${initdir}/lib64/file,
369 # and a symlink ${initdir}/lib -> lib64.
370 inst_dir() {
371 [[ -e ${initdir}/"$1" ]] && return 0 # already there
372
373 local _dir="$1" _part="${1%/*}" _file
374 while [[ "$_part" != "${_part%/*}" ]] && ! [[ -e "${initdir}/${_part}" ]]; do
375 _dir="$_part $_dir"
376 _part=${_part%/*}
377 done
378
379 # iterate over parent directories
380 for _file in $_dir; do
381 if [[ -L $_file ]]; then
382 # create link as the original
383 local target=$(readlink -f "$_file")
384 # resolve relative path and recursively install destination
385 [[ $target == ${target#/} ]] && target="$(dirname "$_file")/$target"
386 inst_dir "$target"
387 inst_symlink "$_file"
388 else
389 [[ -h ${initdir}/$_file ]] && _file=$(readlink "${initdir}/$_file")
390 # create directory
391 [[ -e "${initdir}/$_file" ]] || mkdir -m 0755 -p "${initdir}/$_file" || return 1
392 if [[ -d "$_file" ]]; then
393 chmod --reference="$_file" "${initdir}/$_file"
394 chmod u+w "${initdir}/$_file"
395 fi
396 fi
397 done
398 }
399
400 # $1 = file to copy to ramdisk
401 # $2 (optional) Name for the file on the ramdisk
402 # Location of the image dir is assumed to be $initdir
403 # We never overwrite the target if it exists.
404 inst_simple() {
405 [[ -f "$1" ]] || return 1
406 strstr "$1" "/" || return 1
407
408 local _src=$1 target="${2:-$1}"
409 if ! [[ -d ${initdir}/$target ]]; then
410 [[ -e ${initdir}/$target ]] && return 0
411 [[ -h ${initdir}/$target ]] && return 0
412 inst_dir "${target%/*}"
413 fi
414 # install checksum files also
415 if [[ -e "${_src%/*}/.${_src##*/}.hmac" ]]; then
416 inst "${_src%/*}/.${_src##*/}.hmac" "${target%/*}/.${target##*/}.hmac"
417 fi
418 ddebug "Installing $_src"
419 cp --sparse=always -pfL "$_src" "${initdir}/$target"
420 }
421
422 # find symlinks linked to given library file
423 # $1 = library file
424 # Function searches for symlinks by stripping version numbers appended to
425 # library filename, checks if it points to the same target and finally
426 # prints the list of symlinks to stdout.
427 #
428 # Example:
429 # rev_lib_symlinks libfoo.so.8.1
430 # output: libfoo.so.8 libfoo.so
431 # (Only if libfoo.so.8 and libfoo.so exists on host system.)
432 rev_lib_symlinks() {
433 [[ ! $1 ]] && return 0
434
435 local fn="$1" orig="$(readlink -f "$1")" links=''
436
437 [[ ${fn} =~ .*\.so\..* ]] || return 1
438
439 until [[ ${fn##*.} == so ]]; do
440 fn="${fn%.*}"
441 [[ -L ${fn} && $(readlink -f "${fn}") == ${orig} ]] && links+=" ${fn}"
442 done
443
444 echo "${links}"
445 }
446
447 # Same as above, but specialized to handle dynamic libraries.
448 # It handles making symlinks according to how the original library
449 # is referenced.
450 inst_library() {
451 local _src="$1" _dest=${2:-$1} _lib _reallib _symlink
452 strstr "$1" "/" || return 1
453 [[ -e $initdir/$_dest ]] && return 0
454 if [[ -L $_src ]]; then
455 # install checksum files also
456 if [[ -e "${_src%/*}/.${_src##*/}.hmac" ]]; then
457 inst "${_src%/*}/.${_src##*/}.hmac" "${_dest%/*}/.${_dest##*/}.hmac"
458 fi
459 _reallib=$(readlink -f "$_src")
460 inst_simple "$_reallib" "$_reallib"
461 inst_dir "${_dest%/*}"
462 ln -sfn $(convert_abs_rel "${_dest}" "${_reallib}") "${initdir}/${_dest}"
463 else
464 inst_simple "$_src" "$_dest"
465 fi
466
467 # Create additional symlinks. See rev_symlinks description.
468 for _symlink in $(rev_lib_symlinks $_src) $(rev_lib_symlinks $_reallib); do
469 [[ ! -e $initdir/$_symlink ]] && {
470 ddebug "Creating extra symlink: $_symlink"
471 inst_symlink $_symlink
472 }
473 done
474 }
475
476 # find a binary. If we were not passed the full path directly,
477 # search in the usual places to find the binary.
478 find_binary() {
479 if [[ -z ${1##/*} ]]; then
480 if [[ -x $1 ]] || ldd $1 &>/dev/null; then
481 echo $1
482 return 0
483 fi
484 fi
485
486 type -P $1
487 }
488
489 # Same as above, but specialized to install binary executables.
490 # Install binary executable, and all shared library dependencies, if any.
491 inst_binary() {
492 local _bin _target _f _self _so_regex _lib_regex _tlibdir _base _file _line
493
494 _bin=$(find_binary "$1") || return 1
495 _target=${2:-$_bin}
496 [[ -e $initdir/$_target ]] && return 0
497 inst_symlink $_bin $_target && return 0
498
499 # If the binary being installed is also a library, add it to the loop.
500 _so_regex='([^ ]*/lib[^/]*/[^ ]*\.so[^ ]*)'
501 [[ $_bin =~ $_so_regex ]] && _self="\t${_bin##*/} => ${_bin} (0x0)\n"
502
503 _lib_regex='^(/lib[^/]*).*'
504 # I love bash!
505 { LC_ALL=C ldd $_bin 2>/dev/null; echo -en "$_self"; } | while read _line; do
506 [[ $_line = 'not a dynamic executable' ]] && return 1
507 if [[ $_line =~ not\ found ]]; then
508 dfatal "Missing a shared library required by $_bin."
509 dfatal "Run \"ldd $_bin\" to find out what it is."
510 dfatal "dracut cannot create an initrd."
511 exit 1
512 fi
513 [[ $_line =~ $_so_regex ]] || continue
514 _file=${BASH_REMATCH[1]}
515 [[ -e ${initdir}/$_file ]] && continue
516
517 # See if we are loading an optimized version of a shared lib.
518 if [[ $_file =~ $_lib_regex ]]; then
519 _tlibdir=${BASH_REMATCH[1]}
520 _base=${_file##*/}
521 # Prefer nosegneg libs to unoptimized ones.
522 for _f in "$_tlibdir/i686/nosegneg"; do
523 [[ -e $_f/$_base ]] || continue
524 inst_library $_f/$_base
525 break
526 done
527 fi
528 inst_library "$_file"
529 done
530
531 # Install the binary if it wasn't handled in the above loop.
532 [[ -z $_self ]] && inst_simple "$_bin" "$_target"
533 }
534
535 # same as above, except for shell scripts.
536 # If your shell script does not start with shebang, it is not a shell script.
537 inst_script() {
538 local _bin
539 _bin=$(find_binary "$1") || return 1
540 shift
541 local _line _shebang_regex
542 read -r -n 80 _line <"$_bin"
543 # If debug is set, clean unprintable chars to prevent messing up the term
544 [[ $debug ]] && _line=$(echo -n "$_line" | tr -c -d '[:print:][:space:]')
545 _shebang_regex='(#! *)(/[^ ]+).*'
546 [[ $_line =~ $_shebang_regex ]] || return 1
547 inst "${BASH_REMATCH[2]}" && inst_simple "$_bin" "$@"
548 }
549
550 # same as above, but specialized for symlinks
551 inst_symlink() {
552 local _src=$1 _target=${2:-$1} _realsrc
553 strstr "$1" "/" || return 1
554 [[ -L $1 ]] || return 1
555 [[ -L $initdir/$_target ]] && return 0
556 _realsrc=$(readlink -f "$_src")
557 [[ -d ${_target%/*} ]] && _target=$(readlink -f ${_target%/*})/${_target##*/}
558 if [[ -d $_realsrc ]]; then
559 inst_dir "$_realsrc"
560 else
561 {
562 local _t
563 _t=${2:-$1}
564 _t="${_t%/*}"
565 [[ $_t ]] && inst_dir "$_t"
566 inst "$_realsrc"
567 }
568 fi
569 if [[ -e "${_src}" ]]; then
570 ln -sfn $(convert_abs_rel "${_target}" "${_realsrc}") "$initdir/$_target"
571 else
572 ln -sfn "$_realsrc" "$initdir/$_target"
573 fi
574 }
575
576 # attempt to install any programs specified in a udev rule
577 inst_rule_programs() {
578 local _prog _bin
579
580 if grep -qE 'PROGRAM==?"[^ "]+' "$1"; then
581 for _prog in $(grep -E 'PROGRAM==?"[^ "]+' "$1" | sed -r 's/.*PROGRAM==?"([^ "]+).*/\1/'); do
582 if [ -x /lib/udev/$_prog ]; then
583 _bin=/lib/udev/$_prog
584 else
585 _bin=$(find_binary "$_prog") || {
586 dinfo "Skipping program $_prog using in udev rule $(basename $1) as it cannot be found"
587 continue;
588 }
589 fi
590
591 #dinfo "Installing $_bin due to it's use in the udev rule $(basename $1)"
592 dracut_install "$_bin"
593 done
594 fi
595 }
596
597 # udev rules always get installed in the same place, so
598 # create a function to install them to make life simpler.
599 inst_rules() {
600 local _target=/etc/udev/rules.d _rule _found
601
602 inst_dir "/lib/udev/rules.d"
603 inst_dir "$_target"
604 for _rule in "$@"; do
605 if [ "${rule#/}" = "$rule" ]; then
606 for r in /lib/udev/rules.d /etc/udev/rules.d; do
607 if [[ -f $r/$_rule ]]; then
608 _found="$r/$_rule"
609 inst_simple "$_found"
610 inst_rule_programs "$_found"
611 fi
612 done
613 fi
614 for r in '' ./ $dracutbasedir/rules.d/; do
615 if [[ -f ${r}$_rule ]]; then
616 _found="${r}$_rule"
617 inst_simple "$_found" "$_target/${_found##*/}"
618 inst_rule_programs "$_found"
619 fi
620 done
621 [[ $_found ]] || dinfo "Skipping udev rule: $_rule"
622 done
623 }
624
625 # general purpose installation function
626 # Same args as above.
627 inst() {
628 local _x
629
630 case $# in
631 1) ;;
632 2) [[ ! $initdir && -d $2 ]] && export initdir=$2
633 [[ $initdir = $2 ]] && set $1;;
634 3) [[ -z $initdir ]] && export initdir=$2
635 set $1 $3;;
636 *) dfatal "inst only takes 1 or 2 or 3 arguments"
637 exit 1;;
638 esac
639 for _x in inst_symlink inst_script inst_binary inst_simple; do
640 $_x "$@" && return 0
641 done
642 return 1
643 }
644
645 # install function specialized for hooks
646 # $1 = type of hook, $2 = hook priority (lower runs first), $3 = hook
647 # All hooks should be POSIX/SuS compliant, they will be sourced by init.
648 inst_hook() {
649 if ! [[ -f $3 ]]; then
650 dfatal "Cannot install a hook ($3) that does not exist."
651 dfatal "Aborting initrd creation."
652 exit 1
653 elif ! strstr "$hookdirs" "$1"; then
654 dfatal "No such hook type $1. Aborting initrd creation."
655 exit 1
656 fi
657 inst_simple "$3" "/lib/dracut/hooks/${1}/${2}${3##*/}"
658 }
659
660 # install any of listed files
661 #
662 # If first argument is '-d' and second some destination path, first accessible
663 # source is installed into this path, otherwise it will installed in the same
664 # path as source. If none of listed files was installed, function return 1.
665 # On first successful installation it returns with 0 status.
666 #
667 # Example:
668 #
669 # inst_any -d /bin/foo /bin/bar /bin/baz
670 #
671 # Lets assume that /bin/baz exists, so it will be installed as /bin/foo in
672 # initramfs.
673 inst_any() {
674 local to f
675
676 [[ $1 = '-d' ]] && to="$2" && shift 2
677
678 for f in "$@"; do
679 if [[ -e $f ]]; then
680 [[ $to ]] && inst "$f" "$to" && return 0
681 inst "$f" && return 0
682 fi
683 done
684
685 return 1
686 }
687
688 # dracut_install [-o ] <file> [<file> ... ]
689 # Install <file> to the initramfs image
690 # -o optionally install the <file> and don't fail, if it is not there
691 dracut_install() {
692 local _optional=no
693 if [[ $1 = '-o' ]]; then
694 _optional=yes
695 shift
696 fi
697 while (($# > 0)); do
698 if ! inst "$1" ; then
699 if [[ $_optional = yes ]]; then
700 dinfo "Skipping program $1 as it cannot be found and is" \
701 "flagged to be optional"
702 else
703 dfatal "Failed to install $1"
704 exit 1
705 fi
706 fi
707 shift
708 done
709 }
710
711 # install function decompressing the target and handling symlinks
712 # $@ = list of compressed (gz or bz2) files or symlinks pointing to such files
713 #
714 # Function install targets in the same paths inside overlay but decompressed
715 # and without extensions (.gz, .bz2).
716 inst_decompress() {
717 local _src _dst _realsrc _realdst _cmd
718
719 for _src in $@
720 do
721 case ${_src} in
722 *.gz) _cmd='gzip -d' ;;
723 *.bz2) _cmd='bzip2 -d' ;;
724 *) return 1 ;;
725 esac
726
727 if [[ -L ${_src} ]]
728 then
729 _realsrc="$(readlink -f ${_src})" # symlink target with extension
730 _dst="${_src%.*}" # symlink without extension
731 _realdst="${_realsrc%.*}" # symlink target without extension
732 mksubdirs "${initdir}/${_src}"
733 # Create symlink without extension to target without extension.
734 ln -sfn "${_realdst}" "${initdir}/${_dst}"
735 fi
736
737 # If the source is symlink we operate on its target.
738 [[ ${_realsrc} ]] && _src=${_realsrc}
739 inst ${_src}
740 # Decompress with chosen tool. We assume that tool changes name e.g.
741 # from 'name.gz' to 'name'.
742 ${_cmd} "${initdir}${_src}"
743 done
744 }
745
746 # It's similar to above, but if file is not compressed, performs standard
747 # install.
748 # $@ = list of files
749 inst_opt_decompress() {
750 local _src
751
752 for _src in $@
753 do
754 inst_decompress "${_src}" || inst "${_src}"
755 done
756 }
757
758 # module_check <dracut module>
759 # execute the check() function of module-setup.sh of <dracut module>
760 # or the "check" script, if module-setup.sh is not found
761 # "check $hostonly" is called
762 module_check() {
763 local _moddir=$(echo ${dracutbasedir}/modules.d/??${1})
764 local _ret
765 local _forced=0
766 local _hostonly=$hostonly
767 [ $# -eq 2 ] && _forced=$2
768 [[ -d $_moddir ]] || return 1
769 if [[ ! -f $_moddir/module-setup.sh ]]; then
770 # if we do not have a check script, we are unconditionally included
771 [[ -x $_moddir/check ]] || return 0
772 [ $_forced -ne 0 ] && unset hostonly
773 $_moddir/check $hostonly
774 _ret=$?
775 else
776 unset check depends install installkernel
777 . $_moddir/module-setup.sh
778 is_func check || return 0
779 [ $_forced -ne 0 ] && unset hostonly
780 check $hostonly
781 _ret=$?
782 unset check depends install installkernel
783 fi
784 hostonly=$_hostonly
785 return $_ret
786 }
787
788 # module_check_mount <dracut module>
789 # execute the check() function of module-setup.sh of <dracut module>
790 # or the "check" script, if module-setup.sh is not found
791 # "mount_needs=1 check 0" is called
792 module_check_mount() {
793 local _moddir=$(echo ${dracutbasedir}/modules.d/??${1})
794 local _ret
795 mount_needs=1
796 [[ -d $_moddir ]] || return 1
797 if [[ ! -f $_moddir/module-setup.sh ]]; then
798 # if we do not have a check script, we are unconditionally included
799 [[ -x $_moddir/check ]] || return 0
800 mount_needs=1 $_moddir/check 0
801 _ret=$?
802 else
803 unset check depends install installkernel
804 . $_moddir/module-setup.sh
805 is_func check || return 1
806 check 0
807 _ret=$?
808 unset check depends install installkernel
809 fi
810 unset mount_needs
811 return $_ret
812 }
813
814 # module_depends <dracut module>
815 # execute the depends() function of module-setup.sh of <dracut module>
816 # or the "depends" script, if module-setup.sh is not found
817 module_depends() {
818 local _moddir=$(echo ${dracutbasedir}/modules.d/??${1})
819 local _ret
820 [[ -d $_moddir ]] || return 1
821 if [[ ! -f $_moddir/module-setup.sh ]]; then
822 # if we do not have a check script, we have no deps
823 [[ -x $_moddir/check ]] || return 0
824 $_moddir/check -d
825 return $?
826 else
827 unset check depends install installkernel
828 . $_moddir/module-setup.sh
829 is_func depends || return 0
830 depends
831 _ret=$?
832 unset check depends install installkernel
833 return $_ret
834 fi
835 }
836
837 # module_install <dracut module>
838 # execute the install() function of module-setup.sh of <dracut module>
839 # or the "install" script, if module-setup.sh is not found
840 module_install() {
841 local _moddir=$(echo ${dracutbasedir}/modules.d/??${1})
842 local _ret
843 [[ -d $_moddir ]] || return 1
844 if [[ ! -f $_moddir/module-setup.sh ]]; then
845 [[ -x $_moddir/install ]] && . "$_moddir/install"
846 return $?
847 else
848 unset check depends install installkernel
849 . $_moddir/module-setup.sh
850 is_func install || return 0
851 install
852 _ret=$?
853 unset check depends install installkernel
854 return $_ret
855 fi
856 }
857
858 # module_installkernel <dracut module>
859 # execute the installkernel() function of module-setup.sh of <dracut module>
860 # or the "installkernel" script, if module-setup.sh is not found
861 module_installkernel() {
862 local _moddir=$(echo ${dracutbasedir}/modules.d/??${1})
863 local _ret
864 [[ -d $_moddir ]] || return 1
865 if [[ ! -f $_moddir/module-setup.sh ]]; then
866 [[ -x $_moddir/installkernel ]] && . "$_moddir/installkernel"
867 return $?
868 else
869 unset check depends install installkernel
870 . $_moddir/module-setup.sh
871 is_func installkernel || return 0
872 installkernel
873 _ret=$?
874 unset check depends install installkernel
875 return $_ret
876 fi
877 }
878
879 # check_mount <dracut module>
880 # check_mount checks, if a dracut module is needed for the given
881 # device and filesystem types in "${host_fs_types[@]}"
882 check_mount() {
883 local _mod=$1
884 local _moddir=$(echo ${dracutbasedir}/modules.d/??${1})
885 local _ret
886 local _moddep
887 # If we are already scheduled to be loaded, no need to check again.
888 strstr " $mods_to_load " " $_mod " && return 0
889 strstr " $mods_checked_as_dep " " $_mod " && return 1
890
891 # This should never happen, but...
892 [[ -d $_moddir ]] || return 1
893
894 [[ $2 ]] || mods_checked_as_dep+=" $_mod "
895
896 strstr " $omit_dracutmodules " " $_mod " && return 1
897
898 if [ "${#host_fs_types[*]}" -gt 0 ]; then
899 module_check_mount $_mod || return 1
900 else
901 # skip this module
902 return 1
903 fi
904
905 for _moddep in $(module_depends $_mod); do
906 # handle deps as if they were manually added
907 strstr " $add_dracutmodules " " $_moddep " || \
908 add_dracutmodules+=" $_moddep "
909 strstr " $force_add_dracutmodules " " $_moddep " || \
910 force_add_dracutmodules+=" $_moddep "
911 # if a module we depend on fail, fail also
912 check_module $_moddep || return 1
913 done
914
915 strstr " $mods_to_load " " $_mod " || \
916 mods_to_load+=" $_mod "
917
918 return 0
919 }
920
921 # check_module <dracut module> [<use_as_dep>]
922 # check if a dracut module is to be used in the initramfs process
923 # if <use_as_dep> is set, then the process also keeps track
924 # that the modules were checked for the dependency tracking process
925 check_module() {
926 local _mod=$1
927 local _moddir=$(echo ${dracutbasedir}/modules.d/??${1})
928 local _ret
929 local _moddep
930 # If we are already scheduled to be loaded, no need to check again.
931 strstr " $mods_to_load " " $_mod " && return 0
932 strstr " $mods_checked_as_dep " " $_mod " && return 1
933
934 # This should never happen, but...
935 [[ -d $_moddir ]] || return 1
936
937 [[ $2 ]] || mods_checked_as_dep+=" $_mod "
938
939 strstr " $omit_dracutmodules " " $_mod " && return 1
940
941 if strstr " $dracutmodules $add_dracutmodules $force_add_dracutmodules" " $_mod "; then
942 if strstr " $force_add_dracutmodules" " $_mod"; then
943 module_check $_mod 1; ret=$?
944 else
945 module_check $_mod 0; ret=$?
946 fi
947 # explicit module, so also accept ret=255
948 [[ $ret = 0 || $ret = 255 ]] || return 1
949 else
950 # module not in our list
951 if [[ $dracutmodules = all ]]; then
952 # check, if we can and should install this module
953 module_check $_mod || return 1
954 else
955 # skip this module
956 return 1
957 fi
958 fi
959
960 for _moddep in $(module_depends $_mod); do
961 # handle deps as if they were manually added
962 strstr " $add_dracutmodules " " $_moddep " || \
963 add_dracutmodules+=" $_moddep "
964 strstr " $force_add_dracutmodules " " $_moddep " || \
965 force_add_dracutmodules+=" $_moddep "
966 # if a module we depend on fail, fail also
967 check_module $_moddep || return 1
968 done
969
970 strstr " $mods_to_load " " $_mod " || \
971 mods_to_load+=" $_mod "
972
973 return 0
974 }
975
976 # for_each_module_dir <func>
977 # execute "<func> <dracut module> 1"
978 for_each_module_dir() {
979 local _modcheck
980 local _mod
981 local _moddir
982 local _func
983 _func=$1
984 for _moddir in "$dracutbasedir/modules.d"/[0-9][0-9]*; do
985 _mod=${_moddir##*/}; _mod=${_mod#[0-9][0-9]}
986 $_func $_mod 1
987 done
988
989 # Report any missing dracut modules, the user has specified
990 _modcheck="$add_dracutmodules $force_add_dracutmodules"
991 [[ $dracutmodules != all ]] && _modcheck="$m $dracutmodules"
992 for _mod in $_modcheck; do
993 strstr "$mods_to_load" "$_mod" && continue
994 strstr "$omit_dracutmodules" "$_mod" && continue
995 derror "Dracut module \"$_mod\" cannot be found."
996 done
997 }
998
999 # Install a single kernel module along with any firmware it may require.
1000 # $1 = full path to kernel module to install
1001 install_kmod_with_fw() {
1002 # no need to go further if the module is already installed
1003 [[ -e "${initdir}/lib/modules/$kernel/${1##*/lib/modules/$kernel/}" ]] \
1004 && return 0
1005
1006 if [[ $omit_drivers ]]; then
1007 local _kmod=${1##*/}
1008 _kmod=${_kmod%.ko}
1009 _kmod=${_kmod/-/_}
1010 if strstr " $omit_drivers " " $_kmod " ; then
1011 dinfo "Omitting driver $_kmod"
1012 return 1
1013 fi
1014 fi
1015
1016 inst_simple "$1" "/lib/modules/$kernel/${1##*/lib/modules/$kernel/}" \
1017 || return $?
1018
1019 local _modname=${1##*/} _fwdir _found _fw
1020 _modname=${_modname%.ko*}
1021 for _fw in $(modinfo -k $kernel -F firmware $1 2>/dev/null); do
1022 _found=''
1023 for _fwdir in $fw_dir; do
1024 if [[ -d $_fwdir && -f $_fwdir/$_fw ]]; then
1025 inst_simple "$_fwdir/$_fw" "/lib/firmware/$_fw"
1026 _found=yes
1027 fi
1028 done
1029 if [[ $_found != yes ]]; then
1030 if ! grep -qe "\<${_modname//-/_}\>" /proc/modules; then
1031 dinfo "Possible missing firmware \"${_fw}\" for kernel module" \
1032 "\"${_modname}.ko\""
1033 else
1034 dwarn "Possible missing firmware \"${_fw}\" for kernel module" \
1035 "\"${_modname}.ko\""
1036 fi
1037 fi
1038 done
1039 return 0
1040 }
1041
1042 # Do something with all the dependencies of a kernel module.
1043 # Note that kernel modules depend on themselves using the technique we use
1044 # $1 = function to call for each dependency we find
1045 # It will be passed the full path to the found kernel module
1046 # $2 = module to get dependencies for
1047 # rest of args = arguments to modprobe
1048 # _fderr specifies FD passed from surrounding scope
1049 for_each_kmod_dep() {
1050 local _func=$1 _kmod=$2 _cmd _modpath _options _found=0
1051 shift 2
1052 modprobe "$@" --ignore-install --show-depends $_kmod 2>&${_fderr} | (
1053 while read _cmd _modpath _options; do
1054 [[ $_cmd = insmod ]] || continue
1055 $_func ${_modpath} || exit $?
1056 _found=1
1057 done
1058 [[ $_found -eq 0 ]] && exit 1
1059 exit 0
1060 )
1061 }
1062
1063 # filter kernel modules to install certain modules that meet specific
1064 # requirements.
1065 # $1 = search only in subdirectory of /kernel/$1
1066 # $2 = function to call with module name to filter.
1067 # This function will be passed the full path to the module to test.
1068 # The behaviour of this function can vary depending on whether $hostonly is set.
1069 # If it is, we will only look at modules that are already in memory.
1070 # If it is not, we will look at all kernel modules
1071 # This function returns the full filenames of modules that match $1
1072 filter_kernel_modules_by_path () (
1073 local _modname _filtercmd
1074 if ! [[ $hostonly ]]; then
1075 _filtercmd='find "$srcmods/kernel/$1" "$srcmods/extra"'
1076 _filtercmd+=' "$srcmods/weak-updates" -name "*.ko" -o -name "*.ko.gz"'
1077 _filtercmd+=' -o -name "*.ko.xz"'
1078 _filtercmd+=' 2>/dev/null'
1079 else
1080 _filtercmd='cut -d " " -f 1 </proc/modules|xargs modinfo -F filename '
1081 _filtercmd+='-k $kernel 2>/dev/null'
1082 fi
1083 for _modname in $(eval $_filtercmd); do
1084 case $_modname in
1085 *.ko) "$2" "$_modname" && echo "$_modname";;
1086 *.ko.gz) gzip -dc "$_modname" > $initdir/$$.ko
1087 $2 $initdir/$$.ko && echo "$_modname"
1088 rm -f $initdir/$$.ko
1089 ;;
1090 *.ko.xz) xz -dc "$_modname" > $initdir/$$.ko
1091 $2 $initdir/$$.ko && echo "$_modname"
1092 rm -f $initdir/$$.ko
1093 ;;
1094 esac
1095 done
1096 )
1097 find_kernel_modules_by_path () (
1098 if ! [[ $hostonly ]]; then
1099 find "$srcmods/kernel/$1" "$srcmods/extra" "$srcmods/weak-updates" \
1100 -name "*.ko" -o -name "*.ko.gz" -o -name "*.ko.xz" 2>/dev/null
1101 else
1102 cut -d " " -f 1 </proc/modules \
1103 | xargs modinfo -F filename -k $kernel 2>/dev/null
1104 fi
1105 )
1106
1107 filter_kernel_modules () {
1108 filter_kernel_modules_by_path drivers "$1"
1109 }
1110
1111 find_kernel_modules () {
1112 find_kernel_modules_by_path drivers
1113 }
1114
1115 # instmods <kernel module> [<kernel module> ... ]
1116 # instmods <kernel subsystem>
1117 # install kernel modules along with all their dependencies.
1118 # <kernel subsystem> can be e.g. "=block" or "=drivers/usb/storage"
1119 instmods() {
1120 [[ $no_kernel = yes ]] && return
1121 # called [sub]functions inherit _fderr
1122 local _fderr=9
1123
1124 function inst1mod() {
1125 local _mod="$1"
1126 case $_mod in
1127 =*)
1128 # This introduces 2 incompatible meanings for =* arguments
1129 # to instmods. We need to decide which one to keep.
1130 if [[ $_mod = =ata && -f $srcmods/modules.block ]]; then
1131 ( [[ "$_mpargs" ]] && echo $_mpargs
1132 egrep 'ata|ahci' "${srcmods}/modules.block" ) \
1133 | instmods
1134 elif [ -f $srcmods/modules.${_mod#=} ]; then
1135 ( [[ "$_mpargs" ]] && echo $_mpargs
1136 cat "${srcmods}/modules.${_mod#=}" ) \
1137 | instmods
1138 else
1139 ( [[ "$_mpargs" ]] && echo $_mpargs
1140 find "$srcmods" -path "*/${_mod#=}/*" ) \
1141 | instmods
1142 fi
1143 ;;
1144 --*) _mpargs+=" $_mod" ;;
1145 i2o_scsi) return ;; # Do not load this diagnostic-only module
1146 *) _mod=${_mod##*/}
1147
1148 # if we are already installed, skip this module and go on
1149 # to the next one.
1150 [[ -f $initdir/$1 ]] && return
1151
1152 # If we are building a host-specific initramfs and this
1153 # module is not already loaded, move on to the next one.
1154 [[ $hostonly ]] && ! grep -qe "\<${_mod//-/_}\>" /proc/modules \
1155 && ! echo $add_drivers | grep -qe "\<${_mod}\>" \
1156 && return
1157
1158 # We use '-d' option in modprobe only if modules prefix path
1159 # differs from default '/'. This allows us to use Dracut with
1160 # old version of modprobe which doesn't have '-d' option.
1161 local _moddirname=${srcmods%%/lib/modules/*}
1162 [[ -n ${_moddirname} ]] && _moddirname="-d ${_moddirname}/"
1163
1164 # ok, load the module, all its dependencies, and any firmware
1165 # it may require
1166 for_each_kmod_dep install_kmod_with_fw $_mod \
1167 --set-version $kernel ${_moddirname} $_mpargs
1168 ((_ret+=$?))
1169 ;;
1170 esac
1171 }
1172
1173 function instmods_1() {
1174 local _ret=0 _mod _mpargs
1175 if (($# == 0)); then # filenames from stdin
1176 while read _mod; do
1177 inst1mod "${_mod%.ko*}"
1178 done
1179 fi
1180 while (($# > 0)); do # filenames as arguments
1181 inst1mod ${1%.ko*}
1182 shift
1183 done
1184 return $_ret
1185 }
1186
1187 # Capture all stderr from modprobe to _fderr. We could use {var}>...
1188 # redirections, but that would make dracut require bash4 at least.
1189 eval "( instmods_1 \"\$@\" ) ${_fderr}>&1" \
1190 | egrep -v 'FATAL: Module .* not found.' | derror
1191 return $?
1192 }