#!/bin/sh

export PATH=$PATH:/fabos/link_bin:/bin:/usr/bin:/sbin:/usr/sbin:/fabos/link_abin:/fabos/link_sbin:/fabos/link_rbin:/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
#chip=0/0/0
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_ge2=`/fabos/link_bin/bladeportmap $slot | grep -c "GEYE2"`
num_c2=`/fabos/link_bin/bladeportmap $slot | grep -c "CONDOR2"`
if [ $num_ge2 -eq 0 ] && [ $num_c2 -eq 0 ]; then
	echo "regdump supported on GoldenEye2 or Condor2"
	exit -53
fi

# Trigger ASIC register dump
cmd="db $chip dbg show cdump c2"
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

#
# Copy kernel buffer to file
#
page_size_bit=12
page_size=$((1 << page_size_bit))
blocks=$(((size + page_size - 1) / page_size))
offset=$((addr >> page_size_bit))

# Bash 2.4.0 does not support unsigned integer. Need to mask off "sign
# extended" bits for the offset.
mask=$((0x7fffffff >> (page_size_bit - 1)))
offset=$((offset & mask))

SWBD=`sin | swbd 2> /dev/null`
if [ ${SWBD##SWBD} == '141' ] ; then
    /fabos/link_bin/regdump_c2 $size
else
	dd if=/dev/kmem of=$dump_file count=$blocks bs=$page_size skip=$offset &> /dev/nul
fi

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