#/bin/bash
########################
#
# Adjust priorities of system processes
#
# Look at end of file for actual process/priority associations
#
########################

#set -x

. /etc/sysconfig/rc
. $rc_functions

shopt -s extglob

# given process id, echo process name
process_name()
{
  PID="$1"
  cat /proc/${PID}/stat | sed 's/^[0-9]* (\([^(]*\)) .*/\1/'
}

# given the process name, echo process pid
# we need this because pidof sometimes returns wrong pids :(
# however we first try pidof because it is faster
pidof_sh()
{
  NAME=$1

  PID=`pidof "${NAME}"`
  TNAME=`process_name ${PID}`

  if test "x${TNAME}" == "x${NAME}"
  then
    echo ${PID}
    return 0
  fi

  #echo "pidof '${NAME}' returned ${PID}, but this is the PID of '${TNAME}'!!!" >&2

  for i in /proc/+([0-9])
  do
    PID=`echo ${i} | sed 's@^/proc/\([0-9][0-9]*\)$@\1@'`
    TNAME=`process_name ${PID}`
    #echo Comparing "x${NAME}" = "x${TNAME}"
    if test "x${NAME}" = "x${TNAME}"
    then
      echo $PID
      break
    fi
  done
}

# given irq number echo hardware attached to that irq
irq_description()
{
  IRQ="$1"
  cat /proc/interrupts |grep "^ *${IRQ}:" | sed 's/[^:]*: *[^ ]* *[^ ]* *\(.*\)$/\1/'
}

# given a hardware description, return associated IRQ
hw_irq()
{
  grep "${HW}" /proc/interrupts |sed 's/^ *\([0-9]*\):.*/\1/'
}

process_description()
{
  PID="$1"
  NAME=`process_name $PID`

  SUFFIX=''

  echo ${NAME} | grep -q '^IRQ [0-9][0-9]*$'

  if [ $? -eq 0 ]
  then
    IRQ=`echo ${NAME} | sed 's/^IRQ \([0-9][0-9]*\)$/\1/'`
    DESCR=`irq_description ${IRQ}`
    SUFFIX=" (${DESCR})"
  fi

  echo "'${NAME}'${SUFFIX}"
}

rt_pri_set()
{
  PID="$1"
  PRI="$2"
  PDESCR="$3"

  if test -z "$PID"
  then
    echo "rt_pri_setL no PID given!"
    return 1
  fi

  if test -z "$PID"
  then
    echo "rt_pri_setL no PID given!"
    return 0
  fi

  if test $PDESCR
  then
    echo "Setting priority to SCHED_FIFO ${PRI} for `process_description ${PID}` (${PDESCR})"
  else
    echo "Setting priority to SCHED_FIFO ${PRI} for `process_description ${PID}`"
  fi

  chrt -f -p ${PRI} ${PID}
}

kthread_set()
{
  KTHREAD="$1"
  PRI="$2"

  PID=`pidof_sh "$KTHREAD"`
  if test $? -ne 0
  then
    echo "pidof_sh ${KTHREAD} failed"
    return 1
  fi
  #echo $KTHREAD pid is $PID
  rt_pri_set ${PID} ${PRI}
}

irq_set()
{
  HW="$1"
  PRI="$2"

  IRQ=`hw_irq ${HW}`
  PID=`pidof_sh "IRQ-${IRQ}"`
  if test $? -ne 0
  then
    echo "pidof_sh ${KTHREAD} failed"
    return 1
  fi
  rt_pri_set ${PID} ${PRI} "`irq_description ${IRQ}`"
}

irq_set_boot()
{
  irq_set "${1}" "${2}"
  if test $? -ne 0
  then
    echo_failure
    exit 1
  fi

  echo_ok
}

kthread_set_boot()
{
  kthread_set "${1}" "${2}"
  if test $? -ne 0
  then
    echo_failure
    exit 1
  fi

  echo_ok
}

