#!/bin/sh
#
#    Broadcom Proprietary and Confidential. Copyright © 2018 Broadcom.
#    All Rights Reserved. The term "Broadcom" refers to Broadcom Inc.
#    and/or its subsidiaries.
#

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_ch=`/fabos/link_rbin/bladeportmap $slot | grep -c "CONDOR5"`
if [ $num_ch -eq 0 ]; then
	echo "This regdump utils supported on Condor5"
	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" "`
rev=`echo $str | grep kernel | cut -f7 -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

if [   "$rev" = "C" ]; then
# Mmap kernel memory and copy it to file
/fabos/link_rbin/asicregdump c5c $size
else
/fabos/link_rbin/asicregdump c5 $size
fi



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