#!/bin/sh
export PATH=$PATH:/fabos/link_bin:/bin:/usr/bin:/sbin:/usr/sbin:/fabos/link_abin:/fabos/link_sbin:/fabos/factory:/fabos/xtool

swbd() {
	sed -n -e 's/^.\+\(SWBD[[:digit:]]\{1,\}\).\+$/\1/gp'
}

#
# This script triggers the ASIC register dump to a buffer. Then the kernel
# buffer is copied to a file.
#
# To-Do:
# * Walk through all blades/minis
# * Look for supporting ASIC

dump_file="/var/regdump.dmp"

if [ $# -lt 1 ]; then
	echo "Syntax: regdump <slot#/mini#/chip#>"
	exit -51
fi

# Does the chip exist?
chip=$1
slot=`echo $chip | cut -f1 -d"/"`

#mini=`echo $chip | cut -f2 -d"/"`
#chep=`echo $chip | cut -f3 -d"/"`

#if [ ! -e /proc/fabos/blade/$chip ]; then
#	echo "Chip $chip not in /proc"
#	echo "$dump_file" > $dump_file 
#	exit -52
#fi

num_ch=`/fabos/link_rbin/bladeportmap $slot | grep -c "CONDOR4\|GEYE4"`
if [ $num_ch -eq 0 ]; then
	echo "This regdump utils supported either Condor4 or GEYE4 only"
	exit -53
fi

# Trigger ASIC register dump
cmd="db $chip dbg show cdump"
str=`$cmd`
 
if [ -z "$str" ]; then
	echo "db command fails: $cmd"
	exit -54
fi

fail=`echo $str | grep -c invalid`
if [ $fail -gt 0 ]; then
	echo "regdump not supported on this chip"
	exit -55
fi

# Extract buffer address and size from string:
#   "kernel addr: 0x68d01000 size: 0x300000"
addr=`echo $str | grep kernel | cut -f3 -d" "`
size=`echo $str | grep kernel | cut -f5 -d" "`

if [ $((addr)) -eq 0 ]; then
	echo "Invalid addr: $addr"
	exit -56
fi

if [ $((size)) -eq 0 ]; then
	echo "Invalid size: $size"
	exit -57
fi

# Mmap kernel memory and copy it to file
/fabos/link_rbin/asicregdump c4P $size

if [ $? -eq 0 ]; then
	echo "ASIC registers dumped to $dump_file"
else
	echo "Fails to dump ASIC registers"
fi
