#!/bin/sh

## Testing the dataflash: AT45DB642 
##
##	This test use mtd-tools (mtd_debug) to check all the dataflash
## 
## Page = 1056 bytes (1K + 32) => 0x420 (0x400+0x020) 
## Block = 8448 bytes (8K + 256) =>  8 x Pages => 0x2000
## Sector = 32 Blocks (Except Sector 0 = 1 x block (0); Sector [1-31] = 31 x blocks). 
## 
## Total: 32 sectors = 1024 blocks = 8192 pages = 8650752 bytes
##	: 0x84'0000 bytes
##
## Linux devices: 
##		wrs# cat /proc/mtd
##		dev:    size   erasesize  name
##		mtd0: 00800000 00020000 "Kernel"
##		mtd1: 08000000 00020000 "Filesystem"
##		mtd2: 00040000 00020000 "Barebox Environment"
##		mtd3: 14000000 00020000 "Available"
##		mtd4: 00840000 00000420 "spi0.0-AT45DB642x" <------------- This one is DF
##
##
## Authors: 
##	- Benoit Rat (Seven Solutions, www.sevensols.com)
##
## GNU Lesser General Public License Usage
## This file may be used under the terms of the GNU Lesser
## General Public License version 2.1 as published by the Free Software
## Foundation and appearing in the file LICENSE.LGPL included in the
## packaging of this file.  Please review the following information to
## ensure the GNU Lesser General Public License version 2.1 requirements
## will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
#######################################################################################################	  	

printf "======: $0\n"
. 000-functions.sh

nblock=1024
iblock=0
sizeblock=8192
device=/dev/mtd4
f2w=/tmp/w-df.bin
f2r=/tmp/r-df.bin
nOK=0
nKO=0
ddopt="bs=1k count=8"


printf "Testing DF memory\n"
while [ $iblock -lt $nblock ]; do
	
	startaddr=$(expr $iblock \* ${sizeblock})
	
	printf "> Checking Block: %04d @ 0x%08X " $iblock $startaddr

	dd $ddopt if=/dev/urandom of=${f2w} 		  2> /dev/null
	printf "..."
	mtd_debug erase ${device} ${startaddr} ${sizeblock} &> /dev/null
	printf "..."
	mtd_debug write ${device} ${startaddr} ${sizeblock} ${f2w} &> /dev/null
	printf "..."
	mtd_debug read ${device} ${startaddr} ${sizeblock} ${f2r} &> /dev/null
	printf "..."

	md5w=`md5sum ${f2w} | cut -f1 -d" "`
	md5r=`md5sum ${f2r} | cut -f1 -d" "`

	if [ "$md5w" != "$md5r" ]; then
		nKO=$(expr ${nKO} + 1)		
		printf "ERROR (%02d %%) \n" $(expr $(expr $iblock \* 100 ) / $nblock)
	else
		nOK=$(expr ${nOK} + 1) 
		printf " %02d %% \\r" $(expr $(expr $iblock \* 100 ) / $nblock)
	fi

	iblock=$(expr $iblock + 1)         


done

echo ""
echo "Result DF testing: OK=${nOK}/${nblock}"

exit_errpercent ${nOK} ${nblock}

