#!/bin/sh
## History:
##
## 2019/05/08 - [Tao Wu] Created file
##
## Copyright (c) 2019 Ambarella International LP
##
## This file and its contents ("Software") are protected by intellectual
## property rights including, without limitation, U.S. and/or foreign
## copyrights. This Software is also the confidential and proprietary
## information of Ambarella International LP and its licensors. You may not use, reproduce,
## disclose, distribute, modify, or otherwise prepare derivative works of this
## Software or any portion thereof except pursuant to a signed license agreement
## or nondisclosure agreement with Ambarella International LP or its authorized affiliates.
## In the absence of such an agreement, you agree to promptly notify and return
## this Software to Ambarella International LP.
##
## This file includes sample code and is only for internal testing and evaluation.  If you
## distribute this sample code (whether in source, object, or binary code form), it will be
## without any warranty or indemnity protection from Ambarella International LP or its affiliates.
##
## THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
## INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF NON-INFRINGEMENT,
## MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
## IN NO EVENT SHALL AMBARELLA INTERNATIONAL LP OR ITS AFFILIATES BE LIABLE FOR ANY DIRECT,
## INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
## (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
## LOSS OF USE, DATA, OR PROFITS; COMPUTER FAILURE OR MALFUNCTION; OR BUSINESS
## INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
## CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
## ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
## POSSIBILITY OF SUCH DAMAGE.
##

proc_file=/proc/ambarella/cavalry_cma
app_exe=test_cavalry_mem

check_env()
{
	if [ "$(which $app_exe)" = "" ]; then
		echo "Not found $app_exe"
		exit 1
	fi

	if [ ! -f $proc_file ]; then
		echo "Not found $proc_file"
		exit 1
	fi
}

recover_mem()
{
	cat $proc_file |tail -n +4 | head -n -3 | while read line
	do
		#echo $line
		ref_cnt=$(echo $line | awk '{ print $5 }')
		if [ "$ref_cnt" = "0" ]; then
			phys=$(echo $line | awk '{ print $2 }')
			phys=${phys%-*}

			#echo "Found phys: $phys"
			$app_exe -d $phys
		fi
	done
	echo "Recover Done"
}

##main
check_env
recover_mem