/******************************************************************************
  Target Script for Cogent CSB637.

  Copyright (c) 2005 Rowley Associates Limited.

  This file may be distributed under the terms of the License Agreement
  provided with this software.

  THIS FILE IS PROVIDED AS IS WITH NO WARRANTY OF ANY KIND, INCLUDING THE
  WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 ******************************************************************************/

debugCodeLoadAddress = 0x20005000;
debugCodeOnStopOffset = 0;
debugCodeOnRunOffset = 64;
debugCode =
[
  // debug_stop:
  0xEE110F10, //    mrc     15, 0, r0, cr1, cr0, 0   ; Read MMU Control
  0xE58F0040, //    str     r0, [pc, #64]            ; Store MMU Control
  0xE3C00005, //    bic     r0, r0, #0x5             ; Disable MMU & Caches
  0xE3C00A01, //    bic     r0, r0, #0x1000
  0xEE010F10, //    mcr     15, 0, r0, cr1, cr0, 0
  0xE3A010E0, //    mov     r1, #0xe0                ; Clean D Cache
  0xE381333F, // 1: orr     r3, r1, #0xfc000000
  0xEE073F5E, // 2: mcr     15, 0, r3, cr7, cr14, 2
  0xE2533301, //    subs    r3, r3, #0x4000000
  0x2AFFFFFC, //    bcs     2b
  0xE2511020, //    subs    r1, r1, #0x20
  0x2AFFFFF9, //    bcs     1b
  0xE3A00000, //    mov     r0, #0x00000000
  0xEE070F15, //    mcr     15, 0, r0, cr7, cr5, 0  ; Invalidate I Cache
  0xEE070F9A, //    mcr     15, 0, r0, cr7, cr10, 4 ; Drain Write Buffer
  0xE1A0F00E, //    mov     pc, lr

  // debug_run:
  0xE59F0004, //    ldr     r0, [pc, #4]            ; Restore MMU Control
  0xEE010F10, //    mcr     15, 0, r0, cr1, cr0, 0
  0xE1A0F00E, //    mov     pc, lr

  // debug_mmu_control_state
  0x00000000 //     .word   0x00000000
];

function OnAttach()
{
  TargetInterface.pokeMultUint32(debugCodeLoadAddress, debugCode);
}

function OnStop()
{
  TargetInterface.executeFunction(debugCodeOnStopOffset + debugCodeLoadAddress, 0, 1000);
}

function OnRun()
{
  TargetInterface.executeFunction(debugCodeOnRunOffset + debugCodeLoadAddress, 0, 1000);
}


function Reset()
{
  TargetInterface.setICEBreakerBreakpoint(0, 0x00000000, 0xFFFFFFFF, 0x00000000, 0xFFFFFFFF, 0x100, 0xF7);
  TargetInterface.runTestIdle();
 // TargetInterface.setNSRST(0);
 // TargetInterface.setNSRST(1);
  TargetInterface.waitForDebugState(1000);
  TargetInterface.trst();

  OnAttach();
  OnStop();
}

function
internalRamIsMappedToZero()
{
  TargetInterface.pokeWord(0x00200000, 0x87654321);
  if (TargetInterface.peekWord(0x00000000) != 0x87654321)
    return false;
  TargetInterface.pokeWord(0x00200000, 0x12345678);
  if (TargetInterface.peekWord(0x00000000) != 0x12345678)
    return false;
  return true;
}

function RAMReset()
{
  Reset();
  if (!internalRamIsMappedToZero())
    TargetInterface.pokeWord(0xFFFFFF00, 1); // MC_RCR - Remap RAM to 0x00000000
}

function FLASHReset()
{
  Reset();
  if (internalRamIsMappedToZero())
    TargetInterface.pokeWord(0xFFFFFF00, 1); // MC_RCR - Remap FLASH to 0x00000000
}
