#!/bin/sh

#
# This script triggers a asic module warm memory dump to a buffer.
# Then the kernel buffer is copied to a file.
#
# To-Do for new modules:
# * update usage function
# * update case $2 statement for the new module

function usage() {
	echo "Syntax: $0 <slot#/mini#/chip#> <module>"
	echo "  where module = lpm, exm, tcam, hawk_stat, wlv_stat ...."
	echo ""
	exit -1
}

if [ $# -lt 2 ]; then
	usage
fi

case $2 in
	exm) dump_file="/var/exmdump.dmp"
		cmd="db $1 rte dump exm"
		;;

	lpm) dump_file="/var/lpmdump.dmp"
		cmd="db $1 rte dump lpm"
		;;

	tcam) dump_file="/var/tcamdump.dmp"
		cmd="db $1 rte dump tcam"
		;;

	hawk_stat) dump_file="/var/hawk_stat_dump.dmp"
		cmd="db $1 hawk_stat dump_buf"
		;;

	wlv_stat) dump_file="/var/wlv_stat_dump.dmp"
		cmd="db $1 wlv_stat dump_buf"
		;;

	#
	# define dump_file and cmd for your module here
	#
	*) usage
		;;
esac


# Does the chip exist?
chip=$1
if [ ! -e /proc/fabos/blade/$chip ]; then
	echo "Chip $chip not in /proc"
	exit -1
fi

# Trigger ASIC register dump
#cmd="db -f $chip dbg dump chip"
str=`$cmd`

if [ -z "$str" ]; then
	echo "db command fails: $cmd"
	exit -1
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 -1
fi

if [ $((size)) -eq 0 ]; then
	echo "Invalid size: $size"
	exit -1
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))

dd if=/dev/kmem of=$dump_file count=$blocks bs=$page_size skip=$offset &> /dev/nul

if [ $? -eq 0 ]; then
	echo "Module db info dumped to $dump_file for $chip"
else
	echo "Failed to dump module db information"
fi
