db7d74
#!/bin/sh
db7d74
#
db7d74
# Kdump common variables and functions
db7d74
#
db7d74
db7d74
DEFAULT_PATH="/var/crash/"
db7d74
FENCE_KDUMP_CONFIG_FILE="/etc/sysconfig/fence_kdump"
db7d74
FENCE_KDUMP_SEND="/usr/libexec/fence_kdump_send"
db7d74
FADUMP_ENABLED_SYS_NODE="/sys/kernel/fadump_enabled"
db7d74
db7d74
is_fadump_capable()
db7d74
{
db7d74
    # Check if firmware-assisted dump is enabled
db7d74
    # if no, fallback to kdump check
db7d74
    if [ -f $FADUMP_ENABLED_SYS_NODE ]; then
db7d74
        rc=`cat $FADUMP_ENABLED_SYS_NODE`
db7d74
        [ $rc -eq 1 ] && return 0
db7d74
    fi
db7d74
    return 1
db7d74
}
db7d74
db7d74
is_squash_available() {
db7d74
    for kmodule in squashfs overlay loop; do
db7d74
        if [ -z "$KDUMP_KERNELVER" ]; then
db7d74
            modprobe --dry-run $kmodule &>/dev/null || return 1
db7d74
        else
db7d74
            modprobe -S $KDUMP_KERNELVER --dry-run $kmodule &>/dev/null || return 1
db7d74
        fi
db7d74
    done
db7d74
}
db7d74
db7d74
perror_exit() {
db7d74
    derror "$@"
db7d74
    exit 1
db7d74
}
db7d74
db7d74
is_fs_type_nfs()
db7d74
{
db7d74
    [ "$1" = "nfs" ] || [ "$1" = "nfs4" ]
db7d74
}
db7d74
db7d74
is_ssh_dump_target()
db7d74
{
db7d74
    grep -q "^ssh[[:blank:]].*@" /etc/kdump.conf
db7d74
}
db7d74
db7d74
is_nfs_dump_target()
db7d74
{
db7d74
    if grep -q "^nfs" /etc/kdump.conf; then
db7d74
        return 0;
db7d74
    fi
db7d74
db7d74
    if is_fs_type_nfs $(get_dracut_args_fstype "$(grep "^dracut_args .*\-\-mount" /etc/kdump.conf)"); then
db7d74
        return 0
db7d74
    fi
db7d74
db7d74
    local _save_path=$(get_save_path)
db7d74
    local _target=$(get_target_from_path $_save_path)
db7d74
    local _fstype=$(get_fs_type_from_target $_target)
db7d74
db7d74
    if is_fs_type_nfs $_fstype; then
db7d74
        return 0
db7d74
    fi
db7d74
db7d74
    return 1
db7d74
}
db7d74
db7d74
is_raw_dump_target()
db7d74
{
db7d74
    grep -q "^raw" /etc/kdump.conf
db7d74
}
db7d74
db7d74
is_fs_dump_target()
db7d74
{
db7d74
    egrep -q "^ext[234]|^xfs|^btrfs|^minix" /etc/kdump.conf
db7d74
}
db7d74
db7d74
strip_comments()
db7d74
{
db7d74
    echo $@ | sed -e 's/\(.*\)#.*/\1/'
db7d74
}
db7d74
db7d74
# Read from kdump config file stripping all comments
db7d74
read_strip_comments()
db7d74
{
db7d74
    # strip heading spaces, and print any content starting with
db7d74
    # neither space or #, and strip everything after #
db7d74
    sed -n -e "s/^\s*\([^# \t][^#]\+\).*/\1/gp" $1
db7d74
}
db7d74
db7d74
# Check if fence kdump is configured in Pacemaker cluster
db7d74
is_pcs_fence_kdump()
db7d74
{
db7d74
    # no pcs or fence_kdump_send executables installed?
db7d74
    type -P pcs > /dev/null || return 1
db7d74
    [ -x $FENCE_KDUMP_SEND ] || return 1
db7d74
db7d74
    # fence kdump not configured?
db7d74
    (pcs cluster cib | grep 'type="fence_kdump"') &> /dev/null || return 1
db7d74
}
db7d74
db7d74
# Check if fence_kdump is configured using kdump options
db7d74
is_generic_fence_kdump()
db7d74
{
db7d74
    [ -x $FENCE_KDUMP_SEND ] || return 1
db7d74
db7d74
    grep -q "^fence_kdump_nodes" /etc/kdump.conf
db7d74
}
db7d74
db7d74
to_dev_name() {
db7d74
    local dev="${1//\"/}"
db7d74
db7d74
    case "$dev" in
db7d74
    UUID=*)
db7d74
        dev=`blkid -U "${dev#UUID=}"`
db7d74
        ;;
db7d74
    LABEL=*)
db7d74
        dev=`blkid -L "${dev#LABEL=}"`
db7d74
        ;;
db7d74
    esac
db7d74
    echo $dev
db7d74
}
db7d74
db7d74
is_user_configured_dump_target()
db7d74
{
db7d74
    grep -E -q "^ext[234]|^xfs|^btrfs|^minix|^raw|^nfs|^ssh" /etc/kdump.conf || is_mount_in_dracut_args;
db7d74
}
db7d74
db7d74
get_user_configured_dump_disk()
db7d74
{
db7d74
    local _target
db7d74
db7d74
    _target=$(egrep "^ext[234]|^xfs|^btrfs|^minix|^raw" /etc/kdump.conf 2>/dev/null |awk '{print $2}')
db7d74
    [ -n "$_target" ] && echo $_target && return
db7d74
db7d74
    _target=$(get_dracut_args_target "$(grep "^dracut_args .*\-\-mount" /etc/kdump.conf)")
db7d74
    [ -b "$_target" ] && echo $_target
db7d74
}
db7d74
db7d74
get_root_fs_device()
db7d74
{
db7d74
    findmnt -k -f -n -o SOURCE /
db7d74
}
db7d74
db7d74
get_save_path()
db7d74
{
db7d74
    local _save_path=$(awk '$1 == "path" {print $2}' /etc/kdump.conf)
db7d74
    [ -z "$_save_path" ] && _save_path=$DEFAULT_PATH
db7d74
db7d74
    # strip the duplicated "/"
db7d74
    echo $_save_path | tr -s /
db7d74
}
db7d74
db7d74
get_block_dump_target()
db7d74
{
db7d74
    local _target _path
db7d74
db7d74
    if is_ssh_dump_target || is_nfs_dump_target; then
db7d74
        return
db7d74
    fi
db7d74
db7d74
    _target=$(get_user_configured_dump_disk)
db7d74
    [ -n "$_target" ] && echo $(to_dev_name $_target) && return
db7d74
db7d74
    # Get block device name from local save path
db7d74
    _path=$(get_save_path)
db7d74
    _target=$(get_target_from_path $_path)
db7d74
    [ -b "$_target" ] && echo $(to_dev_name $_target)
db7d74
}
db7d74
db7d74
is_dump_to_rootfs()
db7d74
{
db7d74
    grep -E "^(failure_action|default)[[:space:]]dump_to_rootfs" /etc/kdump.conf >/dev/null
db7d74
}
db7d74
db7d74
get_failure_action_target()
db7d74
{
db7d74
    local _target
db7d74
db7d74
    if is_dump_to_rootfs; then
db7d74
        # Get rootfs device name
db7d74
        _target=$(get_root_fs_device)
db7d74
        [ -b "$_target" ] && echo $(to_dev_name $_target) && return
db7d74
        # Then, must be nfs root
db7d74
        echo "nfs"
db7d74
    fi
db7d74
}
db7d74
db7d74
# Get kdump targets(including root in case of dump_to_rootfs).
db7d74
get_kdump_targets()
db7d74
{
db7d74
    local _target _root
db7d74
    local kdump_targets
db7d74
db7d74
    _target=$(get_block_dump_target)
db7d74
    if [ -n "$_target" ]; then
db7d74
        kdump_targets=$_target
db7d74
    elif is_ssh_dump_target; then
db7d74
        kdump_targets="ssh"
db7d74
    else
db7d74
        kdump_targets="nfs"
db7d74
    fi
db7d74
db7d74
    # Add the root device if dump_to_rootfs is specified.
db7d74
    _root=$(get_failure_action_target)
db7d74
    if [ -n "$_root" -a "$kdump_targets" != "$_root" ]; then
db7d74
        kdump_targets="$kdump_targets $_root"
db7d74
    fi
db7d74
db7d74
    echo "$kdump_targets"
db7d74
}
db7d74
db7d74
# Return the bind mount source path, return the path itself if it's not bind mounted
db7d74
# Eg. if /path/to/src is bind mounted to /mnt/bind, then:
db7d74
# /mnt/bind -> /path/to/src, /mnt/bind/dump -> /path/to/src/dump
db7d74
#
db7d74
# findmnt uses the option "-v, --nofsroot" to exclusive the [/dir]
db7d74
# in the SOURCE column for bind-mounts, then if $_src equals to
db7d74
# $_src_nofsroot, the mountpoint is not bind mounted directory.
db7d74
#
db7d74
# Below is just an example for mount info
db7d74
# /dev/mapper/atomicos-root[/ostree/deploy/rhel-atomic-host/var], if the
db7d74
# directory is bind mounted. The former part represents the device path, rest
db7d74
# part is the bind mounted directory which quotes by bracket "[]".
db7d74
get_bind_mount_source()
db7d74
{
db7d74
    local _mnt=$(df $1 | tail -1 | awk '{print $NF}')
db7d74
    local _path=${1#$_mnt}
db7d74
db7d74
    local _src=$(get_mount_info SOURCE target $_mnt -f)
db7d74
    local _opt=$(get_mount_info OPTIONS target $_mnt -f)
db7d74
    local _fstype=$(get_mount_info FSTYPE target $_mnt -f)
db7d74
db7d74
    # bind mount in fstab
db7d74
    if [[ -d "$_src" ]] && [[ "$_fstype" = none ]] && (echo "$_opt" | grep -q "\bbind\b"); then
db7d74
        echo $_src$_path && return
db7d74
    fi
db7d74
db7d74
    # direct mount
db7d74
    local _src_nofsroot=$(get_mount_info SOURCE target $_mnt -v -f)
db7d74
    if [[ $_src_nofsroot = $_src ]]; then
db7d74
        echo $_mnt$_path && return
db7d74
    fi
db7d74
db7d74
    local _fsroot=${_src#$_src_nofsroot[}
db7d74
    _fsroot=${_fsroot%]}
db7d74
    _mnt=$(get_mount_info TARGET source $_src_nofsroot -f)
db7d74
db7d74
    # for btrfs, _fsroot will also contain the subvol value as well, strip it
db7d74
    if [[ "$_fstype" = btrfs ]]; then
db7d74
        local _subvol
db7d74
        _subvol=${_opt#*subvol=}
db7d74
        _subvol=${_subvol%,*}
db7d74
        _fsroot=${_fsroot#$_subvol}
db7d74
    fi
db7d74
    echo $_mnt$_fsroot$_path
db7d74
}
db7d74
db7d74
# Return the current underlaying device of a path, ignore bind mounts
db7d74
get_target_from_path()
db7d74
{
db7d74
    local _target
db7d74
db7d74
    _target=$(df $1 2>/dev/null | tail -1 |  awk '{print $1}')
db7d74
    [[ "$_target" == "/dev/root" ]] && [[ ! -e /dev/root ]] && _target=$(get_root_fs_device)
db7d74
    echo $_target
db7d74
}
db7d74
db7d74
is_mounted()
db7d74
{
db7d74
    findmnt -k -n $1 &>/dev/null
db7d74
}
db7d74
db7d74
get_mount_info()
db7d74
{
db7d74
    local _info_type=$1 _src_type=$2 _src=$3; shift 3
db7d74
    local _info=$(findmnt -k -n -r -o $_info_type --$_src_type $_src $@)
db7d74
db7d74
    [ -z "$_info" ] && [ -e "/etc/fstab" ] && _info=$(findmnt -s -n -r -o $_info_type --$_src_type $_src $@)
db7d74
db7d74
    echo $_info
db7d74
}
db7d74
db7d74
get_fs_type_from_target()
db7d74
{
db7d74
    get_mount_info FSTYPE source $1 -f
db7d74
}
db7d74
db7d74
get_mntopt_from_target()
db7d74
{
db7d74
    get_mount_info OPTIONS source $1 -f
db7d74
}
db7d74
# Find the general mount point of a dump target, not the bind mount point
db7d74
get_mntpoint_from_target()
db7d74
{
db7d74
    # Expcilitly specify --source to findmnt could ensure non-bind mount is returned
db7d74
    get_mount_info TARGET source $1 -f
db7d74
}
db7d74
db7d74
# Get the path where the target will be mounted in kdump kernel
db7d74
# $1: kdump target device
db7d74
get_kdump_mntpoint_from_target()
db7d74
{
db7d74
    local _mntpoint=$(get_mntpoint_from_target $1)
db7d74
db7d74
    # mount under /sysroot if dump to root disk or mount under
db7d74
    # mount under /kdumproot if dump target is not mounted in first kernel
db7d74
    # mount under /kdumproot/$_mntpoint in other cases in 2nd kernel.
db7d74
    # systemd will be in charge to umount it.
db7d74
    if [ -z "$_mntpoint" ];then
db7d74
        _mntpoint="/kdumproot"
db7d74
    else
db7d74
        if [ "$_mntpoint" = "/" ];then
db7d74
            _mntpoint="/sysroot"
db7d74
        else
db7d74
            _mntpoint="/kdumproot/$_mntpoint"
db7d74
        fi
db7d74
    fi
db7d74
db7d74
    # strip duplicated "/"
db7d74
    echo $_mntpoint | tr -s "/"
db7d74
}
db7d74
db7d74
# get_option_value <option_name>
db7d74
# retrieves value of option defined in kdump.conf
db7d74
get_option_value() {
db7d74
    strip_comments `grep "^$1[[:space:]]\+" /etc/kdump.conf | tail -1 | cut -d\  -f2-`
db7d74
}
db7d74
db7d74
kdump_get_persistent_dev() {
db7d74
    local dev="${1//\"/}"
db7d74
db7d74
    case "$dev" in
db7d74
    UUID=*)
db7d74
        dev=`blkid -U "${dev#UUID=}"`
db7d74
        ;;
db7d74
    LABEL=*)
db7d74
        dev=`blkid -L "${dev#LABEL=}"`
db7d74
        ;;
db7d74
    esac
db7d74
    echo $(get_persistent_dev "$dev")
db7d74
}
db7d74
db7d74
is_atomic()
db7d74
{
db7d74
    grep -q "ostree" /proc/cmdline
db7d74
}
db7d74
db7d74
is_ipv6_address()
db7d74
{
db7d74
    echo $1 | grep -q ":"
db7d74
}
db7d74
db7d74
# get ip address or hostname from nfs/ssh config value
db7d74
get_remote_host()
db7d74
{
db7d74
    local _config_val=$1
db7d74
db7d74
    # ipv6 address in kdump.conf is around with "[]",
db7d74
    # factor out the ipv6 address
db7d74
    _config_val=${_config_val#*@}
db7d74
    _config_val=${_config_val%:/*}
db7d74
    _config_val=${_config_val#[}
db7d74
    _config_val=${_config_val%]}
db7d74
    echo $_config_val
db7d74
}
db7d74
db7d74
is_hostname()
db7d74
{
db7d74
    local _hostname=`echo $1 | grep ":"`
db7d74
db7d74
    if [ -n "$_hostname" ]; then
db7d74
        return 1
db7d74
    fi
db7d74
    echo $1 | grep -q "[a-zA-Z]"
db7d74
}
db7d74
db7d74
# Copied from "/etc/sysconfig/network-scripts/network-functions"
db7d74
get_hwaddr()
db7d74
{
db7d74
    if [ -f "/sys/class/net/${1}/address" ]; then
db7d74
        awk '{ print toupper($0) }' < /sys/class/net/${1}/address
db7d74
    elif [ -d "/sys/class/net/${1}" ]; then
db7d74
       LC_ALL= LANG= ip -o link show ${1} 2>/dev/null | \
db7d74
            awk '{ print toupper(gensub(/.*link\/[^ ]* ([[:alnum:]:]*).*/,
db7d74
                                        "\\1", 1)); }'
db7d74
    fi
db7d74
}
db7d74
db7d74
db7d74
# Get value by a field using "nmcli -g"
db7d74
#
db7d74
# "nmcli --get-values" allows us to retrive value(s) by field, for example,
db7d74
# nmcli --get-values <field> connection show /org/freedesktop/NetworkManager/ActiveConnection/1
db7d74
# returns the following value for the corresponding field respectively,
db7d74
#   Field                                  Value
db7d74
#   IP4.DNS                                "10.19.42.41 | 10.11.5.19 | 10.5.30.160"
db7d74
#   802-3-ethernet.s390-subchannels        ""
db7d74
#   bond.options                           "mode=balance-rr"
db7d74
get_nmcli_value_by_field()
db7d74
{
db7d74
    local _nm_show_cmd=$1
db7d74
    local _field=$2
db7d74
db7d74
    local val=$(LANG=C nmcli --get-values $_field $_nm_show_cmd)
db7d74
db7d74
    echo -n "$val"
db7d74
}
db7d74
db7d74
# Get nmcli connection apath (a D-Bus active connection path ) by ifname
db7d74
#
db7d74
# apath is used for nmcli connection operations, e.g.
db7d74
#  $ nmcli connection show $apath
db7d74
get_nmcli_connection_apath_by_ifname()
db7d74
{
db7d74
    local _ifname=$1
db7d74
    local _nm_show_cmd="device show $_ifname"
db7d74
db7d74
    local _apath=$(get_nmcli_value_by_field "$_nm_show_cmd" "GENERAL.CON-PATH")
db7d74
db7d74
    echo -n "$_apath"
db7d74
}
db7d74
db7d74
# Get nmcli connection show cmd by ifname
db7d74
#
db7d74
# "$_apath" is supposed to not contain any chracter that
db7d74
# need to be escapded, e.g. space. Otherwise get_nmcli_value_by_field
db7d74
# would fail.
db7d74
get_nmcli_connection_show_cmd_by_ifname()
db7d74
{
db7d74
    local _ifname="$1"
db7d74
    local _apath=$(get_nmcli_connection_apath_by_ifname "$_ifname")
db7d74
    local _nm_show_cmd="connection show $_apath"
db7d74
db7d74
    echo -n "$_nm_show_cmd"
db7d74
}
db7d74
db7d74
get_ifcfg_by_device()
db7d74
{
db7d74
    grep -E -i -l "^[[:space:]]*DEVICE=\"*${1}\"*[[:space:]]*$" \
db7d74
         /etc/sysconfig/network-scripts/ifcfg-* 2>/dev/null | head -1
db7d74
}
db7d74
db7d74
get_ifcfg_by_hwaddr()
db7d74
{
db7d74
    grep -E -i -l "^[[:space:]]*HWADDR=\"*${1}\"*[[:space:]]*$" \
db7d74
         /etc/sysconfig/network-scripts/ifcfg-* 2>/dev/null | head -1
db7d74
}
db7d74
db7d74
get_ifcfg_by_uuid()
db7d74
{
db7d74
    grep -E -i -l "^[[:space:]]*UUID=\"*${1}\"*[[:space:]]*$" \
db7d74
         /etc/sysconfig/network-scripts/ifcfg-* 2>/dev/null | head -1
db7d74
}
db7d74
db7d74
get_ifcfg_by_name()
db7d74
{
db7d74
    grep -E -i -l "^[[:space:]]*NAME=\"*${1}\"*[[:space:]]*$" \
db7d74
         /etc/sysconfig/network-scripts/ifcfg-* 2>/dev/null | head -1
db7d74
}
db7d74
db7d74
is_nm_running()
db7d74
{
db7d74
    [ "$(LANG=C nmcli -t --fields running general status 2>/dev/null)" = "running" ]
db7d74
}
db7d74
db7d74
is_nm_handling()
db7d74
{
db7d74
    LANG=C nmcli -t --fields device,state  dev status 2>/dev/null \
db7d74
          | grep -q "^\(${1}:connected\)\|\(${1}:connecting.*\)$"
db7d74
}
db7d74
db7d74
# $1: netdev name
db7d74
get_ifcfg_nmcli()
db7d74
{
db7d74
    local nm_uuid nm_name
db7d74
    local ifcfg_file
db7d74
db7d74
    # Get the active nmcli config name of $1
db7d74
    if is_nm_running && is_nm_handling "${1}" ; then
db7d74
        # The configuration "uuid" and "name" generated by nm is wrote to
db7d74
        # the ifcfg file as "UUID=<nm_uuid>" and "NAME=<nm_name>".
db7d74
        nm_uuid=$(LANG=C nmcli -t --fields uuid,device c show --active 2>/dev/null \
db7d74
                  | grep "${1}" | head -1 | cut -d':' -f1)
db7d74
        nm_name=$(LANG=C nmcli -t --fields name,device c show --active 2>/dev/null \
db7d74
                  | grep "${1}" | head -1 | cut -d':' -f1)
db7d74
        ifcfg_file=$(get_ifcfg_by_uuid "${nm_uuid}")
db7d74
        [ -z "${ifcfg_file}" ] && ifcfg_file=$(get_ifcfg_by_name "${nm_name}")
db7d74
    fi
db7d74
db7d74
    echo -n "${ifcfg_file}"
db7d74
}
db7d74
db7d74
# $1: netdev name
db7d74
get_ifcfg_legacy()
db7d74
{
db7d74
    local ifcfg_file
db7d74
db7d74
    ifcfg_file="/etc/sysconfig/network-scripts/ifcfg-${1}"
db7d74
    [ -f "${ifcfg_file}" ] && echo -n "${ifcfg_file}" && return
db7d74
db7d74
    ifcfg_file=$(get_ifcfg_by_name "${1}")
db7d74
    [ -f "${ifcfg_file}" ] && echo -n "${ifcfg_file}" && return
db7d74
db7d74
    local hwaddr=$(get_hwaddr "${1}")
db7d74
    if [ -n "$hwaddr" ]; then
db7d74
        ifcfg_file=$(get_ifcfg_by_hwaddr "${hwaddr}")
db7d74
        [ -f "${ifcfg_file}" ] && echo -n "${ifcfg_file}" && return
db7d74
    fi
db7d74
db7d74
    ifcfg_file=$(get_ifcfg_by_device "${1}")
db7d74
db7d74
    echo -n "${ifcfg_file}"
db7d74
}
db7d74
db7d74
# $1: netdev name
db7d74
# Return the ifcfg file whole name(including the path) of $1 if any.
db7d74
get_ifcfg_filename() {
db7d74
    local ifcfg_file
db7d74
db7d74
    ifcfg_file=$(get_ifcfg_nmcli "${1}")
db7d74
    if [ -z "${ifcfg_file}" ]; then
db7d74
        ifcfg_file=$(get_ifcfg_legacy "${1}")
db7d74
    fi
db7d74
db7d74
    echo -n "${ifcfg_file}"
db7d74
}
db7d74
db7d74
# returns 0 when omission of a module is desired in dracut_args
db7d74
# returns 1 otherwise
db7d74
is_dracut_mod_omitted() {
db7d74
    local dracut_args dracut_mod=$1
db7d74
db7d74
    set -- $(grep  "^dracut_args" /etc/kdump.conf)
db7d74
    while [ $# -gt 0 ]; do
db7d74
        case $1 in
db7d74
            -o|--omit)
db7d74
                [[ " ${2//[^[:alnum:]]/ } " ==  *" $dracut_mod "* ]] && return 0
db7d74
        esac
db7d74
        shift
db7d74
    done
db7d74
db7d74
    return 1
db7d74
}
db7d74
db7d74
is_wdt_active() {
db7d74
    local active
db7d74
db7d74
    [ -d /sys/class/watchdog ] || return 1
db7d74
    for dir in /sys/class/watchdog/*; do
db7d74
        [ -f "$dir/state" ] || continue
db7d74
        active=$(< "$dir/state")
db7d74
        [ "$active" =  "active" ] && return 0
db7d74
    done
db7d74
    return 1
db7d74
}
db7d74
db7d74
# If "dracut_args" contains "--mount" information, use it
db7d74
# directly without any check(users are expected to ensure
db7d74
# its correctness).
db7d74
is_mount_in_dracut_args()
db7d74
{
db7d74
    grep -q "^dracut_args .*\-\-mount" /etc/kdump.conf
db7d74
}
db7d74
db7d74
# If $1 contains dracut_args "--mount", return <filesystem type>
db7d74
get_dracut_args_fstype()
db7d74
{
db7d74
    echo $1 | grep "\-\-mount" | sed "s/.*--mount .\(.*\)/\1/" | cut -d' ' -f3
db7d74
}
db7d74
db7d74
# If $1 contains dracut_args "--mount", return <device>
db7d74
get_dracut_args_target()
db7d74
{
db7d74
    echo $1 | grep "\-\-mount" | sed "s/.*--mount .\(.*\)/\1/" | cut -d' ' -f1
db7d74
}
db7d74
db7d74
check_crash_mem_reserved()
db7d74
{
db7d74
    local mem_reserved
db7d74
db7d74
    mem_reserved=$(cat /sys/kernel/kexec_crash_size)
db7d74
    if [ $mem_reserved -eq 0 ]; then
db7d74
        derror "No memory reserved for crash kernel"
db7d74
        return 1
db7d74
    fi
db7d74
db7d74
    return 0
db7d74
}
db7d74
db7d74
check_kdump_feasibility()
db7d74
{
db7d74
    if [ ! -e /sys/kernel/kexec_crash_loaded ]; then
db7d74
        derror "Kdump is not supported on this kernel"
db7d74
        return 1
db7d74
    fi
db7d74
    check_crash_mem_reserved
db7d74
    return $?
db7d74
}
db7d74
db7d74
check_current_kdump_status()
db7d74
{
db7d74
    if [ ! -f /sys/kernel/kexec_crash_loaded ];then
db7d74
        derror "Perhaps CONFIG_CRASH_DUMP is not enabled in kernel"
db7d74
        return 1
db7d74
    fi
db7d74
db7d74
    rc=`cat /sys/kernel/kexec_crash_loaded`
db7d74
    if [ $rc == 1 ]; then
db7d74
        return 0
db7d74
    else
db7d74
        return 1
db7d74
    fi
db7d74
}
db7d74
db7d74
# remove_cmdline_param <kernel cmdline> <param1> [<param2>] ... [<paramN>]
db7d74
# Remove a list of kernel parameters from a given kernel cmdline and print the result.
db7d74
# For each "arg" in the removing params list, "arg" and "arg=xxx" will be removed if exists.
db7d74
remove_cmdline_param()
db7d74
{
db7d74
    local cmdline=$1
db7d74
    shift
db7d74
db7d74
    for arg in $@; do
db7d74
        cmdline=`echo $cmdline | \
db7d74
                 sed -e "s/\b$arg=[^ ]*//g" \
db7d74
                 -e "s/^$arg\b//g" \
db7d74
                 -e "s/[[:space:]]$arg\b//g" \
db7d74
                 -e "s/\s\+/ /g"`
db7d74
    done
db7d74
    echo $cmdline
db7d74
}
db7d74
db7d74
#
db7d74
# This function returns the "apicid" of the boot
db7d74
# cpu (cpu 0) if present.
db7d74
#
db7d74
get_bootcpu_apicid()
db7d74
{
db7d74
    awk '                                                       \
db7d74
        BEGIN { CPU = "-1"; }                                   \
db7d74
        $1=="processor" && $2==":"      { CPU = $NF; }          \
db7d74
        CPU=="0" && /^apicid/           { print $NF; }          \
db7d74
        '                                                       \
db7d74
        /proc/cpuinfo
db7d74
}
db7d74
db7d74
#
db7d74
# append_cmdline <kernel cmdline> <parameter name> <parameter value>
db7d74
# This function appends argument "$2=$3" to string ($1) if not already present.
db7d74
#
db7d74
append_cmdline()
db7d74
{
db7d74
    local cmdline=$1
db7d74
    local newstr=${cmdline/$2/""}
db7d74
db7d74
    # unchanged str implies argument wasn't there
db7d74
    if [ "$cmdline" == "$newstr" ]; then
db7d74
        cmdline="${cmdline} ${2}=${3}"
db7d74
    fi
db7d74
db7d74
    echo $cmdline
db7d74
}
db7d74
db7d74
# This function check iomem and determines if we have more than
db7d74
# 4GB of ram available. Returns 1 if we do, 0 if we dont
db7d74
need_64bit_headers()
db7d74
{
db7d74
    return `tail -n 1 /proc/iomem | awk '{ split ($1, r, "-"); \
db7d74
    print (strtonum("0x" r[2]) > strtonum("0xffffffff")); }'`
db7d74
}
db7d74
db7d74
# Check if secure boot is being enforced.
db7d74
#
db7d74
# Per Peter Jones, we need check efivar SecureBoot-$(the UUID) and
db7d74
# SetupMode-$(the UUID), they are both 5 bytes binary data. The first four
db7d74
# bytes are the attributes associated with the variable and can safely be
db7d74
# ignored, the last bytes are one-byte true-or-false variables. If SecureBoot
db7d74
# is 1 and SetupMode is 0, then secure boot is being enforced.
db7d74
#
db7d74
# Assume efivars is mounted at /sys/firmware/efi/efivars.
db7d74
is_secure_boot_enforced()
db7d74
{
db7d74
    local secure_boot_file setup_mode_file
db7d74
    local secure_boot_byte setup_mode_byte
db7d74
db7d74
    # On powerpc, os-secureboot-enforcing DT property indicates whether secureboot
db7d74
    # is enforced. Return success, if it is found.
db7d74
    if [ -f /proc/device-tree/ibm,secureboot/os-secureboot-enforcing ]; then
db7d74
		return 0
db7d74
    fi
db7d74
db7d74
    # Detect secure boot on x86 and arm64
db7d74
    secure_boot_file=$(find /sys/firmware/efi/efivars -name SecureBoot-* 2>/dev/null)
db7d74
    setup_mode_file=$(find /sys/firmware/efi/efivars -name SetupMode-* 2>/dev/null)
db7d74
db7d74
    if [ -f "$secure_boot_file" ] && [ -f "$setup_mode_file" ]; then
db7d74
        secure_boot_byte=$(hexdump -v -e '/1 "%d\ "' $secure_boot_file|cut -d' ' -f 5)
db7d74
        setup_mode_byte=$(hexdump -v -e '/1 "%d\ "' $setup_mode_file|cut -d' ' -f 5)
db7d74
db7d74
        if [ "$secure_boot_byte" = "1" ] && [ "$setup_mode_byte" = "0" ]; then
db7d74
            return 0
db7d74
        fi
db7d74
    fi
db7d74
db7d74
    # Detect secure boot on s390x
db7d74
    if [[ -e "/sys/firmware/ipl/secure" && "$(cat /sys/firmware/ipl/secure)" == "1" ]]; then
db7d74
        return 0
db7d74
    fi
db7d74
db7d74
    return 1
db7d74
}
db7d74
db7d74
#
db7d74
# prepare_kexec_args <kexec args>
db7d74
# This function prepares kexec argument.
db7d74
#
db7d74
prepare_kexec_args()
db7d74
{
db7d74
    local kexec_args=$1
db7d74
    local found_elf_args
db7d74
db7d74
    ARCH=`uname -m`
db7d74
    if [ "$ARCH" == "i686" -o "$ARCH" == "i386" ]
db7d74
    then
db7d74
        need_64bit_headers
db7d74
        if [ $? == 1 ]
db7d74
        then
db7d74
            found_elf_args=`echo $kexec_args | grep elf32-core-headers`
db7d74
            if [ -n "$found_elf_args" ]
db7d74
            then
db7d74
                dwarn "Warning: elf32-core-headers overrides correct elf64 setting"
db7d74
            else
db7d74
                kexec_args="$kexec_args --elf64-core-headers"
db7d74
            fi
db7d74
        else
db7d74
            found_elf_args=`echo $kexec_args | grep elf64-core-headers`
db7d74
            if [ -z "$found_elf_args" ]
db7d74
            then
db7d74
                kexec_args="$kexec_args --elf32-core-headers"
db7d74
            fi
db7d74
        fi
db7d74
    fi
db7d74
    echo $kexec_args
db7d74
}
db7d74
db7d74
#
db7d74
# Detect initrd and kernel location, results are stored in global enviromental variables:
db7d74
# KDUMP_BOOTDIR, KDUMP_KERNELVER, KDUMP_KERNEL, DEFAULT_INITRD, and KDUMP_INITRD
db7d74
#
db7d74
# Expectes KDUMP_BOOTDIR, KDUMP_IMG, KDUMP_IMG_EXT, KDUMP_KERNELVER to be loaded from config already
db7d74
# and will prefer already set values so user can specify custom kernel/initramfs location
db7d74
#
db7d74
prepare_kdump_bootinfo()
db7d74
{
db7d74
    local boot_imglist boot_dirlist boot_initrdlist curr_kver="$(uname -r)"
db7d74
    local machine_id
db7d74
db7d74
    if [ -z "$KDUMP_KERNELVER" ]; then
db7d74
        KDUMP_KERNELVER="$(uname -r)"
db7d74
    fi
db7d74
db7d74
    read machine_id < /etc/machine-id
db7d74
    boot_dirlist=${KDUMP_BOOTDIR:-"/boot /boot/efi /efi /"}
db7d74
    boot_imglist="$KDUMP_IMG-$KDUMP_KERNELVER$KDUMP_IMG_EXT $machine_id/$KDUMP_KERNELVER/$KDUMP_IMG"
db7d74
db7d74
    # Use BOOT_IMAGE as reference if possible, strip the GRUB root device prefix in (hd0,gpt1) format
db7d74
    local boot_img="$(cat /proc/cmdline | sed "s/^BOOT_IMAGE=\((\S*)\)\?\(\S*\) .*/\2/")"
db7d74
    if [ -n "$boot_img" ]; then
db7d74
        boot_imglist="$boot_img $boot_imglist"
db7d74
    fi
db7d74
db7d74
    for dir in $boot_dirlist; do
db7d74
        for img in $boot_imglist; do
db7d74
            if [ -f "$dir/$img" ]; then
db7d74
                KDUMP_KERNEL=$(echo $dir/$img | tr -s '/')
db7d74
                break 2
db7d74
            fi
db7d74
        done
db7d74
    done
db7d74
db7d74
    if ! [ -e "$KDUMP_KERNEL" ]; then
db7d74
        derror "Failed to detect kdump kernel location"
db7d74
        return 1
db7d74
    fi
db7d74
db7d74
    # Set KDUMP_BOOTDIR to where kernel image is stored
db7d74
    KDUMP_BOOTDIR=$(dirname $KDUMP_KERNEL)
db7d74
db7d74
    # Default initrd should just stay aside of kernel image, try to find it in KDUMP_BOOTDIR
db7d74
    boot_initrdlist="initramfs-$KDUMP_KERNELVER.img initrd"
db7d74
    for initrd in $boot_initrdlist; do
db7d74
        if [ -f "$KDUMP_BOOTDIR/$initrd" ]; then
db7d74
            defaut_initrd_base="$initrd"
db7d74
            DEFAULT_INITRD="$KDUMP_BOOTDIR/$defaut_initrd_base"
db7d74
            break
db7d74
        fi
db7d74
    done
db7d74
db7d74
    # Create kdump initrd basename from default initrd basename
db7d74
    # initramfs-5.7.9-200.fc32.x86_64.img => initramfs-5.7.9-200.fc32.x86_64kdump.img
db7d74
    # initrd => initrdkdump
db7d74
    if [[ -z "$defaut_initrd_base" ]]; then
db7d74
        kdump_initrd_base=initramfs-${KDUMP_KERNELVER}kdump.img
db7d74
    elif [[ $defaut_initrd_base == *.* ]]; then
db7d74
        kdump_initrd_base=${defaut_initrd_base%.*}kdump.${DEFAULT_INITRD##*.}
db7d74
    else
db7d74
        kdump_initrd_base=${defaut_initrd_base}kdump
db7d74
    fi
db7d74
db7d74
    # Place kdump initrd in `/var/lib/kdump` if `KDUMP_BOOTDIR` not writable
db7d74
    if [[ ! -w "$KDUMP_BOOTDIR" ]];then
db7d74
        var_target_initrd_dir="/var/lib/kdump"
db7d74
        mkdir -p "$var_target_initrd_dir"
db7d74
        KDUMP_INITRD="$var_target_initrd_dir/$kdump_initrd_base"
db7d74
    else
db7d74
        KDUMP_INITRD="$KDUMP_BOOTDIR/$kdump_initrd_base"
db7d74
    fi
db7d74
}
db7d74
db7d74
get_watchdog_drvs()
db7d74
{
db7d74
    local _wdtdrvs _drv _dir
db7d74
db7d74
    for _dir in /sys/class/watchdog/*; do
db7d74
        # device/modalias will return driver of this device
db7d74
        [[ -f "$_dir/device/modalias" ]] || continue
db7d74
        _drv=$(< "$_dir/device/modalias")
db7d74
        _drv=$(modprobe --set-version "$KDUMP_KERNELVER" -R $_drv 2>/dev/null)
db7d74
        for i in $_drv; do
db7d74
            if ! [[ " $_wdtdrvs " == *" $i "* ]]; then
db7d74
                _wdtdrvs="$_wdtdrvs $i"
db7d74
            fi
db7d74
        done
db7d74
    done
db7d74
db7d74
    echo $_wdtdrvs
db7d74
}
db7d74
db7d74
#
db7d74
# prepare_cmdline <commandline> <commandline remove> <commandline append>
db7d74
# This function performs a series of edits on the command line.
db7d74
# Store the final result in global $KDUMP_COMMANDLINE.
db7d74
prepare_cmdline()
db7d74
{
db7d74
    local cmdline id
db7d74
db7d74
    if [ -z "$1" ]; then
db7d74
        cmdline=$(cat /proc/cmdline)
db7d74
    else
db7d74
        cmdline="$1"
db7d74
    fi
db7d74
db7d74
    # These params should always be removed
db7d74
    cmdline=$(remove_cmdline_param "$cmdline" crashkernel panic_on_warn)
db7d74
    # These params can be removed configurably
db7d74
    cmdline=$(remove_cmdline_param "$cmdline" "$2")
db7d74
db7d74
    # Always remove "root=X", as we now explicitly generate all kinds
db7d74
    # of dump target mount information including root fs.
db7d74
    #
db7d74
    # We do this before KDUMP_COMMANDLINE_APPEND, if one really cares
db7d74
    # about it(e.g. for debug purpose), then can pass "root=X" using
db7d74
    # KDUMP_COMMANDLINE_APPEND.
db7d74
    cmdline=$(remove_cmdline_param "$cmdline" root)
db7d74
db7d74
    # With the help of "--hostonly-cmdline", we can avoid some interitage.
db7d74
    cmdline=$(remove_cmdline_param "$cmdline" rd.lvm.lv rd.luks.uuid rd.dm.uuid rd.md.uuid fcoe)
db7d74
db7d74
    # Remove netroot, rd.iscsi.initiator and iscsi_initiator since
db7d74
    # we get duplicate entries for the same in case iscsi code adds
db7d74
    # it as well.
db7d74
    cmdline=$(remove_cmdline_param "$cmdline" netroot rd.iscsi.initiator iscsi_initiator)
db7d74
db7d74
    cmdline="${cmdline} $3"
db7d74
db7d74
    id=$(get_bootcpu_apicid)
db7d74
    if [ ! -z ${id} ] ; then
db7d74
        cmdline=$(append_cmdline "${cmdline}" disable_cpu_apicid ${id})
db7d74
    fi
db7d74
db7d74
    # If any watchdog is used, set it's pretimeout to 0. pretimeout let
db7d74
    # watchdog panic the kernel first, and reset the system after the
db7d74
    # panic. If the system is already in kdump, panic is not helpful
db7d74
    # and only increase the chance of watchdog failure.
db7d74
    for i in $(get_watchdog_drvs); do
db7d74
        cmdline+=" $i.pretimeout=0"
db7d74
db7d74
        if [[ $i == hpwdt ]]; then
db7d74
            # hpwdt have a special parameter kdumptimeout, is's only suppose
db7d74
            # to be set to non-zero in first kernel. In kdump, non-zero
db7d74
            # value could prevent the watchdog from resetting the system.
db7d74
            cmdline+=" $i.kdumptimeout=0"
db7d74
        fi
db7d74
    done
db7d74
db7d74
    echo ${cmdline}
db7d74
}
db7d74
db7d74
#get system memory size in the unit of GB
db7d74
get_system_size()
db7d74
{
db7d74
    result=$(cat /proc/iomem  | grep "System RAM" | awk -F ":" '{ print $1 }' | tr [:lower:] [:upper:] | paste -sd+)
db7d74
    result="+$result"
db7d74
    # replace '-' with '+0x' and '+' with '-0x'
db7d74
    sum=$( echo $result | sed -e 's/-/K0x/g' | sed -e 's/+/-0x/g' | sed -e 's/K/+/g' )
db7d74
    size=$(printf "%d\n" $(($sum)))
db7d74
    let size=$size/1024/1024/1024
db7d74
db7d74
    echo $size
db7d74
}
db7d74
db7d74
get_recommend_size()
db7d74
{
db7d74
    local mem_size=$1
db7d74
    local _ck_cmdline=$2
db7d74
    local OLDIFS="$IFS"
db7d74
db7d74
    last_sz=""
db7d74
    last_unit=""
db7d74
db7d74
    start=${_ck_cmdline: :1}
db7d74
    if [ $mem_size -lt $start ]; then
db7d74
        echo "0M"
db7d74
        return
db7d74
    fi
db7d74
    IFS=','
db7d74
    for i in $_ck_cmdline; do
db7d74
        end=$(echo $i | awk -F "-" '{ print $2 }' | awk -F ":" '{ print $1 }')
db7d74
        recommend=$(echo $i | awk -F "-" '{ print $2 }' | awk -F ":" '{ print $2 }')
db7d74
        size=${end: : -1}
db7d74
        unit=${end: -1}
db7d74
        if [ $unit == 'T' ]; then
db7d74
            let size=$size*1024
db7d74
        fi
db7d74
        if [ $mem_size -lt $size ]; then
db7d74
            echo $recommend
db7d74
            IFS="$OLDIFS"
db7d74
            return
db7d74
        fi
db7d74
    done
db7d74
    IFS="$OLDIFS"
db7d74
}
db7d74
db7d74
# return recommended size based on current system RAM size
db7d74
# $1: kernel version, if not set, will defaults to `uname -r`
db7d74
kdump_get_arch_recommend_size()
db7d74
{
db7d74
    local kernel=$1 arch
db7d74
db7d74
    if ! [ -r "/proc/iomem" ] ; then
db7d74
        echo "Error, can not access /proc/iomem."
db7d74
        return 1
db7d74
    fi
db7d74
db7d74
    [ -z "$kernel" ] && kernel=$(uname -r)
db7d74
    ck_cmdline=$(cat "/usr/lib/modules/$kernel/crashkernel.default" 2>/dev/null)
db7d74
db7d74
    if [ -n "$ck_cmdline" ]; then
db7d74
        ck_cmdline=${ck_cmdline#crashkernel=}
db7d74
    else
db7d74
        arch=$(lscpu | grep Architecture | awk -F ":" '{ print $2 }' | tr '[:lower:]' '[:upper:]')
db7d74
        if [ "$arch" = "X86_64" ] || [ "$arch" = "S390X" ]; then
db7d74
            ck_cmdline="1G-4G:160M,4G-64G:192M,64G-1T:256M,1T-:512M"
db7d74
        elif [ "$arch" = "AARCH64" ]; then
db7d74
            ck_cmdline="2G-:448M"
db7d74
        elif [ "$arch" = "PPC64LE" ]; then
db7d74
            if is_fadump_capable; then
db7d74
                ck_cmdline="4G-16G:768M,16G-64G:1G,64G-128G:2G,128G-1T:4G,1T-2T:6G,2T-4T:12G,4T-8T:20G,8T-16T:36G,16T-32T:64G,32T-64T:128G,64T-:180G"
db7d74
            else
db7d74
                ck_cmdline="2G-4G:384M,4G-16G:512M,16G-64G:1G,64G-128G:2G,128G-:4G"
db7d74
            fi
db7d74
        fi
db7d74
    fi
db7d74
db7d74
    ck_cmdline=$(echo $ck_cmdline | sed -e 's/-:/-102400T:/g')
db7d74
    sys_mem=$(get_system_size)
db7d74
db7d74
    get_recommend_size "$sys_mem" "$ck_cmdline"
db7d74
}
db7d74
db7d74
# Print all underlying crypt devices of a block device
db7d74
# print nothing if device is not on top of a crypt device
db7d74
# $1: the block device to be checked in maj:min format
db7d74
get_luks_crypt_dev()
db7d74
{
db7d74
    [[ -b /dev/block/$1 ]] || return 1
db7d74
db7d74
    local _type=$(eval "$(blkid -u filesystem,crypto -o export -- /dev/block/$1); echo \$TYPE")
db7d74
    [[ $_type == "crypto_LUKS" ]] && echo $1
db7d74
db7d74
    for _x in /sys/dev/block/$1/slaves/*; do
db7d74
        [[ -f $_x/dev ]] || continue
db7d74
        [[ $_x/subsystem -ef /sys/class/block ]] || continue
db7d74
        get_luks_crypt_dev "$(< "$_x/dev")"
db7d74
    done
db7d74
}
db7d74
db7d74
# kdump_get_maj_min <device>
db7d74
# Prints the major and minor of a device node.
db7d74
# Example:
db7d74
# $ get_maj_min /dev/sda2
db7d74
# 8:2
db7d74
kdump_get_maj_min() {
db7d74
    local _majmin
db7d74
    _majmin="$(stat -L -c '%t:%T' "$1" 2> /dev/null)"
db7d74
    printf "%s" "$((0x${_majmin%:*})):$((0x${_majmin#*:}))"
db7d74
}
db7d74
db7d74
get_all_kdump_crypt_dev()
db7d74
{
db7d74
    local _dev _crypt
db7d74
db7d74
    for _dev in $(get_block_dump_target); do
db7d74
        _crypt=$(get_luks_crypt_dev $(kdump_get_maj_min "$_dev"))
db7d74
        [[ -n "$_crypt" ]] && echo $_crypt
db7d74
    done
db7d74
}
db7d74
db7d74
check_vmlinux()
db7d74
{
db7d74
    # Use readelf to check if it's a valid ELF
db7d74
    readelf -h $1 &>/dev/null || return 1
db7d74
}
db7d74
db7d74
get_vmlinux_size()
db7d74
{
db7d74
    local size=0
db7d74
db7d74
    while read _type _offset _virtaddr _physaddr _fsize _msize _flg _aln; do
db7d74
        size=$(( $size + $_msize ))
db7d74
    done <<< $(readelf -l -W $1 | grep "^  LOAD" 2>/dev/stderr)
db7d74
db7d74
    echo $size
db7d74
}
db7d74
db7d74
try_decompress()
db7d74
{
db7d74
    # The obscure use of the "tr" filter is to work around older versions of
db7d74
    # "grep" that report the byte offset of the line instead of the pattern.
db7d74
db7d74
    # Try to find the header ($1) and decompress from here
db7d74
    for pos in `tr "$1\n$2" "\n$2=" < "$4" | grep -abo "^$2"`
db7d74
    do
db7d74
        if ! type -P $3 > /dev/null; then
db7d74
            ddebug "Signiature detected but '$3' is missing, skip this decompressor"
db7d74
            break
db7d74
        fi
db7d74
db7d74
        pos=${pos%%:*}
db7d74
        tail -c+$pos "$img" | $3 > $5 2> /dev/null
db7d74
        if check_vmlinux $5; then
db7d74
            ddebug "Kernel is extracted with '$3'"
db7d74
            return 0
db7d74
        fi
db7d74
    done
db7d74
db7d74
    return 1
db7d74
}
db7d74
db7d74
# Borrowed from linux/scripts/extract-vmlinux
db7d74
get_kernel_size()
db7d74
{
db7d74
    # Prepare temp files:
db7d74
    local img=$1 tmp=$(mktemp /tmp/vmlinux-XXX)
db7d74
    trap "rm -f $tmp" 0
db7d74
db7d74
    # Try to check if it's a vmlinux already
db7d74
    check_vmlinux $img && get_vmlinux_size $img && return 0
db7d74
db7d74
    # That didn't work, so retry after decompression.
db7d74
    try_decompress '\037\213\010' xy    gunzip    $img $tmp || \
db7d74
    try_decompress '\3757zXZ\000' abcde unxz      $img $tmp || \
db7d74
    try_decompress 'BZh'          xy    bunzip2   $img $tmp || \
db7d74
    try_decompress '\135\0\0\0'   xxx   unlzma    $img $tmp || \
db7d74
    try_decompress '\211\114\132' xy    'lzop -d' $img $tmp || \
db7d74
    try_decompress '\002!L\030'   xxx   'lz4 -d'  $img $tmp || \
db7d74
    try_decompress '(\265/\375'   xxx   unzstd    $img $tmp
db7d74
db7d74
    # Finally check for uncompressed images or objects:
db7d74
    [[ $? -eq 0 ]] && get_vmlinux_size $tmp && return 0
db7d74
db7d74
    # Fallback to use iomem
db7d74
    local _size=0
db7d74
    for _seg in $(cat /proc/iomem  | grep -E "Kernel (code|rodata|data|bss)" | cut -d ":" -f 1); do
db7d74
	    _size=$(( $_size + 0x${_seg#*-} - 0x${_seg%-*} ))
db7d74
    done
db7d74
    echo $_size
db7d74
}