#!/bin/bash
#
# rtirq_usb: change irq priority for soundcards detected by udev
#
# This script is called from a udev rule that detects the insertion
# or removal of a soundcard. It works when the name of the irq process
# coincides with the name of the kernel module for the card. For pci cards
# that is the case for kernels > 3.2.x. It also works for usb soundcards.
#
# arguments
#  $1: irq of soundcard
#  $2: name of kernel module
#
# An example udev rule:
#
# SUBSYSTEM=="sound", ATTRS{irq}=="[0-9]*", DRIVERS=="*", RUN+="/usr/bin/rtirq_udev $attr{irq} $driver"
#
# Copyright (c) 2012 Fernando Lopez-Lezcano
#
#   This program is free software; you can redistribute it and/or
#   modify it under the terms of the GNU General Public License
#   as published by the Free Software Foundation; either version 2
#   of the License, or (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License along
#   with this program; if not, write to the Free Software Foundation, Inc.,
#   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

IRQ=${1}
DRIVER=${2}

if [ -n "${IRQ}" -a -n "${DRIVER}" ] ; then
    if [ -r /etc/sysconfig/rtirq ] ; then
	source /etc/sysconfig/rtirq
    fi
    IRQPID=`/bin/ps -e -o pid,comm | /bin/egrep "irq.${IRQ}.${DRIVER:0:8}" | /usr/bin/awk '{print $1}'`
    if [ -n "${IRQPID}" ] ; then
	if [ "${ACTION}" == "remove" ] ; then
	    IRQPRIO=${RTIRQ_PRIO_DEFAULT:-50}
	else
	    IRQPRIO=${RTIRQ_PRIO_UDEV:-70}
	fi
	PRIO=`/bin/ps -p ${IRQPID} -o rtprio=`
	if [ ${PRIO} -ne ${IRQPRIO} ] ; then
	    /usr/bin/chrt -f -p ${IRQPRIO} ${IRQPID}
	fi
    fi
fi
