#! /bin/bash
#  Copyright (c) 2013 Intel Corporation, All rights reserved. 
#  Copyright (C) 2006, 2007, 2008 QLogic Corporation, All rights reserved.
#  Copyright (c) 2006 PathScale, Inc. All rights reserved.
#
#  Permission is granted to Intel customers to use this software in 
#  source and binary forms, with or without modification, provided that 
#  the following conditions are met: 
#  
#  + All copies of source code must retain the above copyright notice, 
#    this list of conditions and the following disclaimer. 
#  
#  + Customer has a valid license agreement from Intel Corporation. for the 
#    software product with which this software is originally distributed. 
#  
#  + Redistribution of original or modified versions to third parties is 
#    prohibited without specific prior written permission of Intel
#    Corporation. 
#  
#  + If customer makes modifications to this software, and provides those 
#    modifications to Intel, customer assigns to Intel Corporation. 
#    ownership of the provided modifications and all intellectual property 
#    rights embodied in those modifications. 
#  
#  + The name of Intel Corporation. may not be used to endorse or promote 
#    products derived from this software without specific prior written 
#    permission. 
#  
#  THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION. AND ITS LICENSORS "AS IS" 
#  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, 
#  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
#  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL INTEL CORPORATION. OR ITS 
#  LICENSORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
#  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
#  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
#  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 
#  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
#  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
#  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 

# This script is used primarily for testing purposes.   It provides
# low level access through the /sys filesystem into the InfiniPath drivers.

# Some functions require root permissions

PATH=/sbin:/bin:/usr/bin:/usr/sbin:$PATH

shopt -s extglob

prog=`basename $0`
unit=0 port=1 # default for all but -i
allunits=1 allports=1 # -i does all units, ports, unless -u
didvers=0 # for -i, only show driver version once, if multiple units
typeset -i exval=0 verbose=0 didsomething=0

usage() {
	exec 1>&2
	echo "Usage: $prog [-u unit#[:port#]] [-i (info) [-v (verbose)]] [-h (help)]"
	echo "  [-b [on|off] (Blinks LEDs to identify board)] [-d debug-level]"

	exit $1
}

# show info for a given port
show_port_info() {
        local u=$1 pdir=$2 p
	p=${pdir##*/}
	if [ "$p" = '*' ]; then
	    echo No ports found
	    return 1;
	elif [ ! -d ${pdir} ]; then
	    echo Port $p not present
	    return 1;
	fi
	read status_str < ${pdir}/linkcontrol/status_str
	read status < ${pdir}/linkcontrol/status
	read lid < ${pdir}/lid
	read gid < ${pdir}/gids/0
	guid=${gid##fe80:0000:0000:0000:}
	case "${status_str}" in
	*IB_link_up*) echo "${u},${p}: Status: ${status} ${status_str}" ;;
	*) echo "${u},${p}: Status: ${status} ${status_str} [IB link not Active]" ;;
	esac
	echo "${u},${p}: LID=${lid} GUID=${guid}"

	if [ $verbose -ge 1 ] ; then
		read hbe < ${pdir}/linkcontrol/hrtbt_enable
		case "${hbe}" in
		    0 ) hbe="Off" ;;
		    1 ) hbe="Enb" ;;
		    3 ) hbe="Auto" ;;
		    * ) hbe=InValid;; # Not sensible 
		esac
		read rate < ${pdir}/rate
		echo "${u},${p}: HRTBT:${hbe} LINK:${rate}"
	fi
}

# show info for a unit, specific port, or all ports
show_unit_info() {
        local errs=0 class thisunit=$1

	class=${sysbase}$thisunit
	if [ ! -f ${class}/version ]; then
		echo No InfiniPath info available for unit $thisunit
		return 1
	fi
	if [ $didvers -eq 0 ]; then
	    cat ${class}/version
	    didvers=1
	fi

	read serial < ${class}/serial
	read boardver < ${class}/boardversion
	echo $thisunit: Version: ${boardver}
	if [ $verbose -ge 1 ] ; then
	    read localbus < ${class}/localbus_info
	    echo $thisunit:  Serial: ${serial} LocalBus: ${localbus}
	else
	    echo $thisunit: Serial: ${serial}
	fi

	if [ $allports -eq 0 ]; then
	    show_port_info $thisunit ${class}/ports/$port
	    (( errs += $? ))
	else
	    for d in $(echo ${class}/ports/*); do
		show_port_info $thisunit $d
		(( errs += $? ))
	    done
	fi

}

show_status () {
        local errs=0
	if ! egrep -qs '^ib_qib' /proc/modules
	then
		echo 'InfiniPath driver not loaded ?'
		(( errs++ ))
	fi
	board="$(lspci -n | egrep -iw '1fc1|1077:7220|1077:7322')"
	if [ -z "${board}" ]
	then
		echo 'No InfiniPath hardware detected'
		(( errs++ ))
	fi
	if [ $errs -gt 0 ]; then
	    (( exval += errs ))
	    return $errs
	fi

	if [ $allunits -eq 0 ]; then
	    show_unit_info $unit
	    (( errs += $? ))
	else
	    for d in $(echo ${sysbase}*); do
		u=${d##*qib}
		show_unit_info $u
		(( errs += $? ))
	    done
	fi

	return $errs
}

validnumber() {
	case "$1" in
	0[xX]+([0-9a-fA-F])) ;;
	0*([0-7])) ;;
	[1-9]*([0-9])) ;;
	*) echo "$1" is not a valid numeric string
	   return 1;;
	esac
	return 0
}

while getopts "b:d:hil:s:u:vw:" C; do
    case $C in
	b) blink_state="$OPTARG"
	   case "${OPTARG}" in
	   [Oo][Nn]) blink_state=0x6021 ;; # 4 Hz alternation between Grn/Yel LEDs
	   [Oo][Ff][Ff]) blink_state=0 ;;
	   *) echo Unsupported blink_state "${OPTARG}"
	      usage 1
		  ;;
	   esac
	   ;;
	d) debuglvl="$OPTARG"
	   if ! validnumber "${debuglvl}"
	   then usage 1
	   fi
	   ;;
	h) usage 0 ;;
	i) getinfo=1 ;;
	l) lid="$OPTARG"
	   if ! validnumber "${lid}"
	   then usage 1
	   fi
	   ;;
	u) case "${OPTARG}" in
	   [0-9]|[1-9][0-9])
		unit=${OPTARG}
		allunits=0
		;;
	   [0-9]:[1-4]|[1-9][0-9]:[1-4])
	   	unit=${OPTARG%:*}
	   	port=${OPTARG#*:}
		allunits=0 allports=0
		;;
	   *) usage 1 ;;
   	   esac
	   ;;
	v) (( verbose++ ))
	   portverb=-v
	   ;;
	w) widopt="$OPTARG"
	   case "${OPTARG}" in
	   1) widdopt=1 ;;
	   4) widopt=2 ;;
	   A) widopt=3 ;;
	   *) echo Unsupported width option "${OPTARG}"
	      usage 1
		  ;;
	   esac
	   ;;
	*|'?') usage 1;;
	esac
done

OPTIND=$(($OPTIND-1))
if [ $OPTIND -lt $# ]; then usage 1; fi

sysbase=/sys/class/infiniband/qib
syspath=${sysbase}${unit}

if [ ! -e "${syspath}" ]; then
	echo "$prog: No InfiniPath module loaded?"
	exit 1
fi

if [ "${debuglvl}" ]
then
	(( didsomething++ ))
	ok=-1
	for dbg in /sys/module/ib_qib/parameters/debug \
		/sys/module/ib_qib/debug
	do	if [ -e ${dbg} ]
		then
			echo "Changing InfiniPath driver debug level from $(cat ${dbg}) to ${debuglvl}"
			echo -n "${debuglvl}" > ${dbg}
			ok=$?
			(( exval += $ok?1:0 ))
			break
		fi
	done
	if [ $ok -eq -1 ]
	then echo InfiniPath driver debug parameters are not available
	fi
fi

if [ "${blink_state}" ]
then
	(( didsomething++ ))
	echo -n ${blink_state} > ${syspath}/ports/${port}/linkcontrol/led_override
	(( exval += $??1:0 ))
fi

if [ "${getinfo}" ]
then
	(( didsomething++ ))
	show_status
fi

if [ $didsomething -eq 0 ]
then
	usage 1
fi

exit $exval

