/* loader.c
 * firmware loads loader from DS card;
 * linked with nintendo released SDK;
 * authored as normal DS game;
 */

#include <es.h>
#include "loader.h"

/*
 * globals;
 */
char pulled = 0;			// a card has been pulled out;

#define	NC_PULLED	1
#define	DS_PULLED	2

/*
 * callback for NC pulled out;
 * set a flag and let main loop handle it;
 */
static BOOL
PulledOutNC(void)
{
	pulled |= NC_PULLED;
	return(FALSE);
}

/*
 * callback for DS pulled out;
 * set a flag and let main loop handle it;
 */
static BOOL
PulledOutDS(void)
{
	pulled |= DS_PULLED;
	return(FALSE);
}

/*
 * check cards pulled out;
 */
static void
ChkCards(void)
{
	if(pulled & NC_PULLED)
		guiPanic(NCLD_NC_PULLED);
	if(pulled & DS_PULLED)
		guiPanic(NCLD_DS_PULLED);
}

/*
 * send DS request to NC;
 * NC will map DS viewer into cartridge space;
 */
static void
NcDsReq(IOSResourceRequest *req, u8 *key)
{
	IOSResourceRequest *ipc;
	s32 n, sts;
	u16 val;
	u32 addr, cmd;

	// prepare request;

	req->cmd = IOS_DSMODE;
	req->status = 0;
	req->handle = 0;
	for(n = 0; n < sizeof(req->ds.key); n++)
		req->ds.key[n] = *key++;

	// wait 1 sec for ipc ready;
	// NC sends ack, we must clear it;

	for(n = 1*60;;) {
		if(n-- <= 0)
			guiPanic(NCLD_IPC_NOT_READY);
		CTRDG_Read16((u16 *)IPC_CTRL_REG, &val);
		if(val & IPC_CTRL_IN_ACK_MASK)
			break;
		ChkCards();
		OS_WaitVBlankIntr();
	}
	CTRDG_Write16((u16 *)IPC_CTRL_REG, IPC_CTRL_IN_ACK_MASK);

	// copy cmd buffer to cartridge space;
	// send ipc request;

	addr = IPC_BUF;
	CTRDG_CpuCopy32((u32 *)req, (u32 *)addr, sizeof(*req));
	CTRDG_Write16((u16 *)IPC_OUT_L_REG, (u16)(addr & 0xffff));
	CTRDG_Write16((u16 *)IPC_OUT_H_REG, (u16)(addr >> 16));
	CTRDG_Write16((u16 *)IPC_CTRL_REG, IPC_CTRL_OUT_MSG_MASK);

	// NC needs time to process overlay;
	// wait 3 secs for reply;
	// spin on cartridge memory for status;
	// copy back reply;

	ipc = (IOSResourceRequest *)IPC_BUF;
	for(n = 3*60; n >= 0; n--) {
		CTRDG_Read32(&ipc->cmd, (u32 *)&cmd);
		if(cmd != IOS_REPLY) {
			ChkCards();
			OS_WaitVBlankIntr();
			continue;
		}
		CTRDG_Read32(&ipc->status, (u32 *)&sts);
		guiDebug(0, 2, GUI_PURPLE, " status %d", sts);
		if(sts != IOS_ERROR_OK)
			break;
		CTRDG_CpuCopy32((u32 *)addr, (u32 *)req, sizeof(*req));
		return;
	}
	guiPanic(NCLD_IPC_NO_REPLY);
}

/*
 * nitro main loader entry;
 * the loader loads the viewer boot overlay from the NC;
 */
void
NitroMain(void)
{
	IOSResourceRequest req;
	u8 key[16];

	// initialization;
	// the firmware has loaded the loader from the DS card;

	OS_Init();
    ES_InitLib();

	// init loader gui;
	// needs a gui for when things go wrong;

	guiInit();
	guiDebug(0, 0, GUI_WHITE, "NC Loader");

	// init cartridge core;

	CTRDG_Enable(TRUE);
	MI_SetCartridgeRomCycle1st(MI_CTRDG_ROMCYCLE1_18);
	MI_SetCartridgeRomCycle2nd(MI_CTRDG_ROMCYCLE2_6);
	MI_SetCartridgeRamCycle(MI_CTRDG_RAMCYCLE_18);

	// check cartridge;

	if(CTRDG_IsExisting() != TRUE)
		guiPanic(NCLD_NO_NC);
/*XXX
	if(CTRDG_IsAgbCartridge() != TRUE)
		guiPanic(NCLD_NO_NC);
	if(CTRDG_IsOptionCartridge() != TRUE)
		guiPanic(NCLD_NO_NC);
*/

	// set pullout callback;

	CTRDG_SetPulledOutCallback(PulledOutNC);
	CARD_SetPulledOutCallback(PulledOutDS);

	// make up a key for overlay;
	// key is sent to NC to sign/crypt lauch code;
	// this prevents all existing PassMe hardware from working,
	// or misusing our DS card code as a launcher;
	// XXX fill key[];

	// send DS ipc command to NC;
	// NC will map viewer overlay into cartridge space;
	// loader will jump to this code, which finishes loading the viewer;
	// all isfs/es code and NC SDK will be in the overlay,
	// thus separating the two SDK libraries cleanly;

	guiDebug(0, 1, GUI_WHITE, "Sending NC DS request");
    ES_CloseLib();
	NcDsReq(&req, key);

	// DS ROM appear at address returned by reply;
	// decrypt/hash overlay with key;
	// hmac validates data from NC, do not check ranges on DS;

	guiDebug(0, 2, GUI_WHITE, "DS ROM @ 0x%x", req.ds.rom_base);
	//XXX hmac/decrypt ?

	// print some DS ROM header info;

#ifdef	DEBUG
	{
	CARDRomHeader rom;

	CTRDG_CpuCopy32((u32 *)req.ds.rom_base, (u32 *)&rom, sizeof(rom));
	guiDebug(0, 3, GUI_WHITE, "arm9 off %x entry %x",
		rom.main_rom_offset, rom.main_entry_address);
	guiDebug(0, 4, GUI_WHITE, "arm9 ram %x size %x",
		rom.main_ram_address, rom.main_size);
	guiDebug(0, 5, GUI_WHITE, "arm7 off %x entry %x",
		rom.sub_rom_offset, rom.sub_entry_address);
	guiDebug(0, 6, GUI_WHITE, "arm7 ram %x size %x",
		rom.sub_ram_address, rom.sub_size);
	OS_WaitVBlankIntr();
	}
#endif	// DEBUG

	// launch code is already in i/d tcms;
	// launch the loaded title;
	// return only for error;

	Launch(req.ds.rom_base);
	guiPanic(NCLD_BAD_LAUNCH);
}

