/*

	wiisd.c

	Hardware routines for reading and writing to the Wii's internal
	SD slot.

	Most of those functions are based on the sd loading code in twilight hack elf
	loader by bushing, marcan, segher and tmbinc

 Copyright (c) 2008 Sven "svpe" Peter <svpe@gmx.net>
	
 Redistribution and use in source and binary forms, with or without modification,
 are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice,
     this list of conditions and the following disclaimer.
  2. Redistributions in binary form must reproduce the above copyright notice,
     this list of conditions and the following disclaimer in the documentation and/or
     other materials provided with the distribution.
  3. The name of the author may not be used to endorse or promote products derived
     from this software without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
 WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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; 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.
*/

#include "wiisd.h"

#include <string.h>
#include <stdio.h>

/*const IO_INTERFACE __io_wiisd = {
	DEVICE_TYPE_WII,
	FEATURE_MEDIUM_CANREAD | FEATURE_MEDIUM_CANWRITE,
	(FN_MEDIUM_STARTUP)&__wiisd_startup,
	(FN_MEDIUM_ISINSERTED)&__wiisd_isInserted,
	(FN_MEDIUM_READSECTORS)&__wiisd_readSectors,
	(FN_MEDIUM_WRITESECTORS)&__wiisd_writeSectors,
	(FN_MEDIUM_CLEARSTATUS)&__wiisd_clearStatus,
	(FN_MEDIUM_SHUTDOWN)&__wiisd_shutdown
} ;
*/
#ifdef __gamecube__
bool __wiisd_startup(void)
{
	return false;
}

bool __wiisd_isInserted(void)
{
	return false;
}

bool __wiisd_readSectors(u32 sector, u32 numSectors, void *ptr)
{
	return false;
}

bool __wiisd_writeSectors(u32 sector, u32 numSectors, void *ptr)
{
	return false;
}

bool __wiisd_clearStatus(void)
{
	return false;
}

bool __wiisd_shutdown(void)
{
	return false;
}
#endif

#define __wii__ 1
#ifdef __wii__
#define SD_HEAP_SIZE	8192

static s32 sd_fd = -1;
static s32 sd_hid = -1;
static u32 sd_status __attribute__((aligned(32)));
static char sd_path[] __attribute__((aligned(32))) = "/dev/sdio/slot0";

static s32 __wiisd_send_cmd(u32 cmd, u32 type, u32 resp, u32 arg, u32 blocks, u32 bsize, u32 addr)
{
	u32 *request;
	u32 *reply;
	u32 r;

	request = iosAlloc(sd_hid, 9 * sizeof(u32));
	reply = iosAlloc(sd_hid, 4 * sizeof(u32));

	if(request == NULL || reply == NULL)
	{
		r = -1;
		goto error;
	}

	memset(request, 0, sizeof(request));
	memset(reply, 0, sizeof(reply));

	request[0] = cmd;
	request[1] = type;
	request[2] = resp;
	request[3] = arg;
	request[4] = blocks;
	request[5] = bsize;
	request[6] = addr;
	request[7] = 0;
	request[8] = 0;

	r = IOS_Ioctl(sd_fd, 7, (u8 *)request, 36, (u8 *)reply, 0x10);

	error:
	if(request != NULL)
		iosFree(sd_hid, request);
	if(reply != NULL)
		iosFree(sd_hid, reply);
	return r;
}

static s32 __wiisd_reset()
{
	s32 r;
	
	r = IOS_Ioctl(sd_fd, 4, 0, 0, (u8 *)&sd_status, 4);
	return r;
}

static s32 __wiisd_select()
{
	s32 r;

	r = __wiisd_send_cmd(7, 3, 2, sd_status & 0xFFFF0000, 0, 0, 0);
	return r;
}

static s32 __wiisd_set_blocklen(u32 len)
{
	s32 r;

	r = __wiisd_send_cmd(0x10, 3, 1, len, 0, 0, 0);
	return r;
}

static u8 __wiisd_get_hcreg()
{
	s32 r;
	u32 *data;
	u32 *query;
	u32 res;

	query = iosAlloc(sd_hid, 6 * sizeof(u32));
	data = iosAlloc(sd_hid, sizeof(u32));

	if(query == NULL || data == NULL)
		return 0; // FIXME

	memset(data, 0, 4);
	memset(query, 0, 0x18);

	query[0] = 0x28;
	query[3] = 1;
	query[4] = 0;
	
	r = IOS_Ioctl(sd_fd, 2, (u8 *)query, 0x18, (u8 *)data, 4);
	if(r < 0)
	{
		iosFree(sd_hid, query);
		iosFree(sd_hid, data);
		return 0; // FIXME
	}

	res = data[0] & 0xFF;
	iosFree(sd_hid, query);
	iosFree(sd_hid, data);
	return res;
}

static s32 __wiisd_set_hcreg(u8 value)
{
	s32 r;
	u32 *query;

	
	query = iosAlloc(sd_hid, 6 * sizeof(u32));
	if(query == NULL)
		return -1;

	memset(query, 0, 0x18);

	query[0] = 0x28;
	query[3] = 1;
	query[4] = value;
	
	r = IOS_Ioctl(sd_fd, 1, (u8 *)query, 0x18, 0, 0);
	iosFree(sd_hid, query);
	return r;
}

static s32 __wiisd_set_buswidth(u8 w)
{
	s32 r;
	u8 reg;

	r = __wiisd_send_cmd(0x37, 3, 1, sd_status & 0xFFFF0000, 0, 0, 0);
	if(r < 0)
		return r;
	r = __wiisd_send_cmd(6, 3, 1, (w == 4 ? 2 : 0), 0, 0, 0);
	if(r < 0)
		return r;
	reg = __wiisd_get_hcreg();
	
	reg &= ~2;
	if(w == 4)
		reg |= 2;
	return __wiisd_set_hcreg(reg);
}

static s32 __wiisd_clock()
{
	s32 r;
	static u32 c __attribute__((aligned(32))) = 1;

	r = IOS_Ioctl(sd_fd, 6, &c, 4, 0, 0);
	return r;
}

static s32 __wiisd_init()
{
	s32 r;

	if(sd_fd < 0)
		return -1;

	r = __wiisd_reset();
	if(r < 0)
		return r;
	__wiisd_select();
	r = __wiisd_set_blocklen(0x200);
	if(r < 0)
		return r;
	r = __wiisd_set_buswidth(4);
	if(r < 0)
	{
		r = __wiisd_set_buswidth(1);
		if(r < 0)
			return r;
	}
	r = __wiisd_clock(); 
	if(r < 0)
		return r;
	return r;
}

bool __wiisd_shutdown(void)
{
	__wiisd_reset();
	IOS_Close(sd_fd);
	iosDestroyHeap(sd_hid);
	sd_fd = -1;
	sd_hid = -1;
	return true;
}

bool __wiisd_startup(void)
{
	if (sd_fd >= 0) __wiisd_shutdown();
	sd_fd = IOS_Open(sd_path, 0);
	
	sd_hid = iosCreateHeap(SD_HEAP_SIZE);
	if(sd_hid < 0)
		goto error;

	if(__wiisd_init() < 0)
		goto error;


	return true;

	error:
	IOS_Close(sd_fd);
	return false;
}

bool __wiisd_isInserted(void)
{
	// FIXME: is there some better way of doing this?
	// looks like this isn't used anywhere so I don't care for now
	return TRUE;
	//return (__wiisd_init() < 0 ? false : true);

}

bool __wiisd_readSectors(u32 sector, u32 numSectors, void *ptr)
{
	s32 r;
	u32 i;
	u8 *buffer = NULL;
	u32 *query;
	u32 *res;

	if(sd_fd < 0)
		return false;

	query = (u32 *)iosAlloc(sd_hid, 9 * sizeof(u32));
	res = (u32 *)iosAlloc(sd_hid, 4 * sizeof(u32));
	buffer = (u8 *)iosAlloc(sd_hid, 0x200);

	if(query == NULL || res == NULL || buffer == NULL)
		goto error;

	for(i = 0; i < numSectors; i++)
	{
		memset(buffer, 0xAA, 0x200);
		memset(query, 0, 0x24);
		memset(res, 0, 0x10);

		query[0] = 0x12;
		query[1] = 3;
		query[2] = 1;
		query[3] = (sector + i) * 0x200;	// arg
		query[4] = 1;				// block_count
		query[5] = 0x200;			// sector size
		query[6] = (u32)buffer;
		query[7] = 1;				// ?
		query[8] = 0;				// ?

		r = IOS_IoctlvFormat(sd_hid, sd_fd, 7, "dd:d", (void *)query, 0x24, (void *)buffer, 0x200, (void *)res, 0x10);

		if(r != 0)
			goto error;

		memcpy(ptr + (i * 0x200), buffer, 0x200);
	}

	iosFree(sd_hid, query);
	iosFree(sd_hid, res);
	iosFree(sd_hid, buffer);
	return true;

	error:
	if(query != NULL)
		iosFree(sd_hid, query);
	if(res != NULL)
		iosFree(sd_hid, res);
	if(buffer != NULL)
		iosFree(sd_hid, buffer);
	return false;
}

bool __wiisd_writeSectors(u32 sector, u32 numSectors, void *ptr)
{
	s32 r;
	u32 i;
	u8 *buffer = NULL;
	u32 *query;
	u32 *res;

	if(sd_fd < 0)
		return false;
	
	query = (u32 *)iosAlloc(sd_hid, 9 * sizeof(u32));
	res = (u32 *)iosAlloc(sd_hid, 4 * sizeof(u32));
	buffer = (u8 *)iosAlloc(sd_hid, 0x200);

	if(query == NULL || res == NULL || buffer == NULL)
		goto error;

	for(i = 0; i < numSectors; i++)
	{
		memcpy(buffer, ptr + (i * 0x200), 0x200);
		memset(query, 0, 0x24);
		memset(res, 0, 0x10);

		query[0] = 0x19;
		query[1] = 3;
		query[2] = 1;
		query[3] = (sector + i) * 0x200;	// arg
		query[4] = 1;				// block_count
		query[5] = 0x200;			// sector size
		query[6] = (u32)buffer;
		query[7] = 1;				// ?
		query[8] = 0;				// ?

		r = IOS_IoctlvFormat(sd_hid, sd_fd, 7, "dd:d", (void *)query, 0x24, (void *)buffer, 0x200, (void *)res, 0x10);

		if(r != 0)
			goto error;
	}

	iosFree(sd_hid, query);
	iosFree(sd_hid, res);
	iosFree(sd_hid, buffer);

	return true;

	error:
	if(query != NULL)
		iosFree(sd_hid, query);
	if(res != NULL)
		iosFree(sd_hid, res);
	if(buffer != NULL)
		iosFree(sd_hid, buffer);
	return false;
}

bool __wiisd_clearStatus(void)
{
	return (__wiisd_init() < 0 ? false : true);
}

#endif
