#!/bin/csh -f

#
# set mtrr register to write-combining mode
# for the memory range mapped to the add-in cards' BAR2.
#

set cmdname  = $0:t;
set rootpath = $0:h/..
pushd $rootpath > /dev/null
set rootpath = `pwd`
popd > /dev/null

echo ''
echo "Searching for HIB(s)... "

if (-x /sbin/lspci) then
    set lspci = /sbin/lspci
else
    if (-x `which lspci`) then
        set lspci = `which lspci`
    else
      echo command \'lspci\' not found.
      echo you may need to set PATH so that it includes
      echo the directory where lspci is located.
      goto LABEL_ERROR_EXIT
    endif
endif

(${lspci} -d '1556:0070' | wc | awk '{print $1}' > /tmp/tmp$$) >& /dev/null
set nxhib = `cat /tmp/tmp$$`
\rm -f /tmp/tmp$$
echo "  Found ${nxhib} PCI-X HIB(s). "

(${lspci} -d '1556:0e70' | wc | awk '{print $1}' > /tmp/tmp$$) >& /dev/null
set nehib = `cat /tmp/tmp$$`
\rm -f /tmp/tmp$$
echo "  Found ${nehib} PLDA PCIe HIB(s)."

(${lspci} -d '1b1a:0e70' | wc | awk '{print $1}' > /tmp/tmp$$) >& /dev/null
set ngehib = `cat /tmp/tmp$$`
\rm -f /tmp/tmp$$
echo "  Found ${ngehib} KFCR PCIe HIB(s)."

set nhib = ${nxhib}
@ nhib += ${nehib}
@ nhib += ${ngehib}
echo "Found ${nhib} HIB(s) in total."
echo ''

set nreg = `wc /proc/mtrr | awk '{print $1}'`;

@ nreg--;
@ n = $nreg + $nhib;

#
# up to 8 mtrrs can be set.
# need to disable some if all 8 mtrrs are in use.
#
while ($n > 7) 
    if ($#argv != 0) then
	set regdel = $1;
	shift;
	echo "Disabling register$regdel..."
	echo "disable=$regdel" > /proc/mtrr;
	echo '    echo "disable='$regdel'" > /proc/mtrr';
	echo "Done."
	echo ''
	@ nreg--;
	@ n = $nreg + $nhib;
    else
	echo "All 8 MTRRs are already in use. Disable some by giving register IDs."
	echo '    eg) ./setmtrr.csh 2 5 7'
	echo "This would disable register 2, 5, 7 in this order, if necessary."
	echo ''
	echo ''
	echo "current setting of MTRRs:"
	cat /proc/mtrr
	echo ''
	exit 1;
    endif
end

#
# set mtrr for each card
#
echo "Trying to set $nhib MTRR(s)..."

while ($nhib > 0)
    @ nhib--;
    set base = `${rootpath}/hibutil/hibtest 0 $nhib | & awk '/0x00000018/{addr = $3; print $3}'`;

    echo `${rootpath}/hibutil/hibtest 0`
    echo base ${base}

    echo '    echo "base='$base' size=0x1000 type=write-combining" > /proc/mtrr';
    echo "base=$base size=0x1000 type=write-combining" > /proc/mtrr;
end
echo "Done."
echo ''
echo "current setting of MTRRs:"
cat /proc/mtrr
echo ''

exit 0

LABEL_ERROR_EXIT:

exit 1
