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