#include <ios.h>
#include <hw.h>
#include <iostypes.h>
#include <ioslibc.h>

#define STACK_SIZE 1024
const u8 _initStack[STACK_SIZE];
const u32 _initStackSize = sizeof(_initStack);
const u32 _initPriority = 10;

/* DMA 1 block = 16 bytes = 4 words */
__attribute__((aligned(64))) u8 src[16] = {0,1,2,3,4,5,6,7,8,9,0xa,0xb,0xc,0xd,0xe,0xf};
__attribute__((aligned(64))) u8 dst[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};


/* XXX horti
 * Most of this will be in the crypto library within the kernel.
 * Userspace will not have access to this except via system calls.
 */

void 
aes_intr_test(void)
{
  IOSMessageQueueId mqid;
  IOSMessage array;
  u32 numBlocks, reg;

  numBlocks = 1; /* DMA 1 block */

  /* Register handler for AES event */
  /* Create a message queue and register for timer events */
  if ((mqid = IOS_CreateMessageQueue(&array, 1)) < 0) {
	 printf("Unable to create timer message queue: %d\n", mqid);
         goto done;
  }
  if (IOS_HandleEvent(IOS_EVENT_AES, mqid, 0) != IOS_ERROR_OK) {
	 printf("Unable to register AES event handler: %d\n");
         goto done;
  }

  /* Enable AES access to SRAM */
  reg = busRd32(ACRSRNPROT_REG) | ACRSRNPROT_AESEN_MASK;
  busWrt32(ACRSRNPROT_REG, reg);

  /* IOS has enabled top-level AES interrupt. Only enable interrupt
   * in device.
   */

  while(1) {
	  printf("Will setup DMA for 1 block from 0x%x to 0x%x \n", src, dst);
	  /* Setup DMA with interrupt enabled */
	  busWrt32(AES_RPTR_REG, (u32)src);
	  busWrt32(AES_WPTR_REG, (u32)dst);
	  busWrt32(AES_CTRL_REG, (AES_CTRL_EXEC | 
				  (AES_CTRL_CMD(AES_DMA_CMD)) | AES_CTRL_MASK | 
				  ((numBlocks-1) & AES_CTRL_SIZE_MASK)));
	  if (IOS_ReceiveMessage(mqid, NULL, IOS_MESSAGE_BLOCK) == IOS_ERROR_OK) {
		  printf("Received AES completion event\n");
	  }
  }
done:
  while(1); 
}

void
main(u32 arg)
{ 
	aes_intr_test(); 
}
