#!/bin/sh
#
# This script lists what mythbackend is polling on.
#
PATH=/files2/home/ali/wk/myth:$PATH
if [ -f /var/run/mythbackend.pid ]; then
    pid=`cat /var/run/mythbackend.pid` || exit 1
else
    echo Myth backend not running
    exit 1
fi
if [ -d /proc/$pid/task ]; then
    polling=`fgrep -lx poll_schedule_timeout /proc/$pid/task/*/wchan | \
      sed -e 's:.*/task/\([0-9]*\)/wchan:\1:'`
else
    echo Myth backend not running
    exit 1
fi
fds_to_list=`mktemp`
for task in $polling; do
    read callno arg0 arg1 arg2 arg3 arg4 arg5 sp pc < /proc/$task/syscall
    # syscall numbers are in /usr/include/syscall.h
    # NB: We should support ppoll, epoll and pselect (and others?),
    # but mythbackend doesn't seem to use them.
    case $callno in
	7)
	    if [ "$arg0" = "0x0" ]; then
		fds=$arg0
	    else
		fds="[`read_mem -t pollfd $pid $arg0 $arg1`]"
		read_mem -t pollfd $pid $arg0 $arg1 | \
		  sed -n -e 's/.*{fd=\([1-9][0-9]*\),.*/\1/p' >> $fds_to_list
	    fi
	    echo $task: poll fds=$fds nfds=$arg1
	    ;;
	23)
	    if [ "$arg1" = "0x0" ]; then
		readfds=$arg1
	    else
		readfds=`read_mem -t fdset $pid $arg1 1`
		echo $readfds | sed -n -e 's/.*\[\(.*\)\].*/\1/p' | \
		  tr ' ' '\012' >> $fds_to_list
	    fi
	    if [ "$arg2" = "0x0" ]; then
		writefds=$arg2
	    else
		writefds=`read_mem -t fdset $pid $arg2 1`
		echo $writefds | sed -n -e 's/.*\[\(.*\)\].*/\1/p' | \
		  tr ' ' '\012' >> $fds_to_list
	    fi
	    if [ "$arg3" = "0x0" ]; then
		exceptfds=$arg3
	    else
		exceptfds=`read_mem -t fdset $pid $arg3 1`
		echo $exceptfds | sed -n -e 's/.*\[\(.*\)\].*/\1/p' | \
		  tr ' ' '\012' >> $fds_to_list
	    fi
	    echo $task: select nfds=$arg0 readfds=$readfds writefds=$writefds \
	      exceptfds=$exceptfds
	    ;;
	219)
	    echo $task: restart_syscall
	    ;;
	running)
	    # task is no longer waiting in a syscall
	    ;;
	*)
	    echo $task: syscall no $callno
	    ;;
    esac
done
fds=`sort -n -u $fds_to_list | tr '\012' ',' | sed -e 's/^,//' -e 's/,$//'`
lsof -p $pid -a -d $fds
rm $fds_to_list
