/* IPC test code to be run on the IOP. Does the following:
 *  - registers an event handler for IPCIOP event
 *  - enables IPCIOP interrupt  
 *  - sets up IPCIOCTRL for IPC
 *  - when an IPCIOP event occurs, clears interrupt in 
 *    IPC subsystem.
 *  - clears and re-enables IPC interrupts.
 *   
 *   Actions that require access to kernel-only regs happen
 *   via system calls. 
 *
 *   You can test this code without PPC support by manually setting
 *   IPCPPCCTRL register in the debugger to generate IPCIOP events.
 *
 *   XXX horti: Later, access controls will be added 
 *   to prevent processes other than the IPC process from 
 *   using these system calls.
 */
#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;


static int
ipc_test(void)
{
    IOSMessageQueueId mqid;
    IOSMessage array;
    u32 stat;

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

    stat = (IOS_ReadIPCIOPCtrlReg() & IPCIOPCTRL_ACK_INTR_MASK)
        | IPCIOPCTRL_MSG_INTR_MASK;
    IOS_WriteIPCIOPCtrlReg(stat);
    while(1) {
        printf("Waiting for IPCIOP event\n");
        if (IOS_ReceiveMessage(mqid, NULL, IOS_MESSAGE_BLOCK) == IOS_ERROR_OK) {
            printf("Received IPCIOP event\n");
        }
        /* At this point the IPC interrupt has been masked by the OS */

        /* Do IPC processing ....*/
        
       /* Clear interrupt in IPC subsystem */ 
        stat = IOS_ReadIPCIOPCtrlReg();
        stat &= (IPCPPCCTRL_MSG_INTR_MASK
                |IPCPPCCTRL_ACK_INTR_MASK
                | IPCPPCCTRL_IN_MSG_MASK);
        IOS_WriteIPCIOPCtrlReg(stat);
        
        /* Clear the system IPCIOP interrupt and reenable the
         * interrrupt.
         */
        IOS_ClearAndEnableIPCIOPIntr();
    }
done:
    return 0;
}

int
main(void)
{
    ipc_test();
    return 0;
}
