#ident "$Id: arm9-switch.c,v 1.5 2007/04/04 20:21:41 craig Exp $"

#include <string.h>
#include <nitro.h>
#include <nitro/card.h>
#include <nitro/fs.h>
#include <nitro/os/common/systemCall.h>

#define PRINT(...)      OS_Printf(__VA_ARGS__)
// #define PRINT(...)      printf(__VA_ARGS__)

#define MAIN_PROC_STATE * (volatile u32 *) 0x02300000
#define SUB_PROC_STATE  * (volatile u32 *) 0x02300004

#define         AGB_REQ     15
#define         AGB_ACK     17

static void IPL2i_DrawAgbFrame(void);
static void IPL2i_AGBMode(void);
static void IPL2i_ChangeAGBMode(void);
void ChangeAGBMode();
void arm7Synchronize( void );

volatile int     goAhead = 0;

/*---------------------------------------------------------------------------*
  Name:         VBlankIntr

  Description:  V-blank callback

  Arguments:    None.

  Returns:      None.
 *---------------------------------------------------------------------------*/
static void VBlankIntr(void)
{
    OS_SetIrqCheckFlag(OS_IE_V_BLANK);
}

/*---------------------------------------------------------------------------*
  Name:         NitroMain

  Description:  main entry point

  Arguments:    None.

  Returns:      None.
 *---------------------------------------------------------------------------*/

extern int zeroVar;

void NitroMain(void)
{
    arm7Synchronize();
    /*
    while (goAhead == 0) {
    }
    */

    IPL2i_ChangeAGBMode();

    PRINT ("Error - this code should not be executing:\n");

    while (1) {
    }
}

/*---------------------------------------------------------------------------*/

#define GetNcdWorkAddr() ((NVRAMConfigData *)(HW_NVRAM_USER_INFO))

// ============================================================================
// AGB Boot Processing
// ============================================================================

// The switching processing to the AGB mode
static void IPL2i_ChangeAGBMode(void)
{
//	while( GetIpl2WorkAddr()->subp_state != SUBP_STATE_BOOT_AGB ) {
//		SVC_WaitByLoop(0x1000);
//	}
	
    // Which LCD displays AGB screen?
    /*
    if (     (GetNcdWorkAddr()->option.agbLcd)
          && (GetIpl2WorkAddr()->ncd_invalid == 0)) {
        PRINT("Bottom screen active\n");
    }
    else {
        PRINT("Top screen active\n");
    }
    */

    /*
    if ((GetNcdWorkAddr()->option.agbLcd)) {
        (void) PM_SetBackLight(PM_LCD_TOP,    PM_BACKLIGHT_OFF);
    }
    else {
        (void) PM_SetBackLight(PM_LCD_BOTTOM, PM_BACKLIGHT_OFF);
    }
    */

    // For some reason calling these functions breaks going into
    // GBA mode.
    // PM_Init();
    // (void) PM_SetBackLight(PM_LCD_BOTTOM, PM_BACKLIGHT_OFF);

    (void)OS_DisableIrq();
    (void)OS_SetIrqMask(0);
    
    (void)GX_DisableBankForBG ();
    (void)GX_DisableBankForOBJ();
    (void)GX_DisableBankForSubBG ();
    (void)GX_DisableBankForSubOBJ();
    (void)GX_DisableBankForARM7();
    GX_SetBankForLCDC( GX_VRAM_LCDC_ALL );			// VRAM clear
    MI_CpuClearFast( (void*)HW_LCDC_VRAM, HW_LCDC_VRAM_SIZE );
    (void)GX_DisableBankForLCDC();
    // Drawing the picture frame before changing to the AGB mode
    IPL2i_DrawAgbFrame();
    
    GX_DispOn();
    // Turning on the power with the circuit to use by the AGB mode
    GX_Power2DMain(TRUE);
    GX_Power2DSub(FALSE);
    GX_Power3D(FALSE);

    if (GetNcdWorkAddr()->option.agbLcd) {
        GX_SetDispSelect(GX_DISP_SELECT_SUB_MAIN);
    }
    else {
        GX_SetDispSelect(GX_DISP_SELECT_MAIN_SUB);
    }
    
    SVC_CpuCopyFast(IPL2i_AGBMode, HW_ITCM, 0x400);
    
    /*
    while (goAhead == 0) {
    }
    */
    // Running ChangeAGBMode() on ITCM
    ( (void (*)(void))HW_ITCM )();
}

// Drawing the picture frame in the AGB mode
static void IPL2i_DrawAgbFrame(void)
{
    // Allocating VRAM in the AGB mode
    GX_SetBankForLCDC( GX_VRAM_LCDC_A | GX_VRAM_LCDC_B );
    // Clearing VRAM-A, B to have allocated for LCDC
    // in the background color (black)
    MI_CpuClearFast( (void *)HW_LCDC_VRAM, 0x40000 );
}

// Switching to the AGB mode
#define REG_MI_EXMEMCNT_MMEM_BURST_MASK			0x4000
#define MI_ResetMmemBurst() 					(reg_MI_EXMEMCNT &= (~0) ^ REG_MI_EXMEMCNT_MMEM_BURST_MASK)

#include <nitro/code32.h>											// Compiling with the ARM code
static void IPL2i_AGBMode(void)
{

    MAIN_PROC_STATE = AGB_REQ;
    
    while (SUB_PROC_STATE != AGB_ACK) {
        // SVC_WaitByLoop(0x400) is described with the in-line assembler.
        asm {
            mov		r0, #0x400
            swi		3 << 16	
        }
    }

#ifndef __IPL2_DEBUG
    // Resetting the burst mode of the main memory & stopping the clock supply
    MI_ResetMmemBurst();
#endif															
    // ŠProhibition a main memory accessibly since this
    //	OS_Halt() is described with the in-line assembler.
    asm {
            mov     r0, #0
            mcr     p15, 0, r0, c7, c0, 4
    }
}

asm void arm7Synchronize( void )
{
    
    //---- synchronism with ARM7
    ldr         r1, =REG_SUBPINTF_ADDR
@1:
    ldrh        r0, [r1]
    and         r0, r0, #0x000f
    cmp         r0, #0x0001
    bne         @1                              // wait till subp status == 1
    mov         r0, #0x0100
    strh        r0, [r1]                        // mainp status == 1

    
    //---- syncronism with ARM7
    ldr         r1, =REG_SUBPINTF_ADDR
@2:
    ldrh        r0, [r1]
    and         r0, r0, #0x000f
    cmp         r0, #0x0001                     // wait till subp status == 0
    beq         @2
    mov         r0, #0
    strh        r0, [r1]                        // mainp status == 0
}
