/*
 *               Copyright (C) 2005, BroadOn Communications Corp.
 *
 *  These coded instructions, statements, and computer programs contain
 *  unpublished  proprietary information of BroadOn Communications Corp.,
 *  and  are protected by Federal copyright law. They may not be disclosed
 *  to  third  parties or copied or duplicated in any form, in whole or in
 *  part, without the prior written consent of BroadOn Communications Corp.
 *
 */
#include <iostypes.h>
#include <ios.h>
#include <iop.h>
#include <ioslibc.h>

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

#include "iosusb.h"
/* When total number of pending async calls hits the system wide 
 * max of IOS_ASYNC_CMD_MAX (128), we get IOS_ERROR_MAX for later calls.
 * OHCI0 will get IOS_ASYNC_CMD_MAX ioctl requests, before the threads
 * start getting IOS_ERROR_MAX. When a thread gets this error, it prints 
 * a message and exits.
 */
#define IOS_ASYNC_CMD_MAX 128 /* match definition in ios/resource.c */
#define ASYNC_MAX 32 
#define THREAD_MAX 4     /* Need ASYNC_MAX * THREAD_MAX = IOS_ASYNC_CMD_MAX */

u8 stacks[THREAD_MAX][1024];

void
thd(u32 arg)
{
    IOSError rc;
    IOSFd fd;
    IOSMessage msgQ[1];
    IOSMessageQueueId qid;
    IOSResourceRequest reply; 
    int i;
    qid = IOS_CreateMessageQueue(msgQ, 1);
    if (qid < 0) {
        printf("Create message queue failed: %d\n", qid);
        goto out;
    }
    
    fd = IOS_Open("/dev/usb/oh0", 0);
    if (fd < 0) {
        printf("open failed: %d\n", fd);
        goto out;
    }
    for (i = 0; i < ASYNC_MAX; ++i) {
        rc = IOS_IoctlAsync(fd, OHC_IPCTEST_MSG, 0, 0, 0, 0, qid, &reply);
        if (rc < 0) {
            printf("thd [%d] ioctl async [%d] error %d. Exiting...\n", arg, i, rc);
            goto out;
        }
    }
out:
    IOS_DestroyThread(0, NULL);
    return;
}

void
main()
{
    IOSError rv;
    u32 i, id, pri;
    
    pri = IOS_GetThreadPriority(0);
    
    printf("Expect OHCI0 to get %u async requests\n", IOS_ASYNC_CMD_MAX);
    printf("Expect next async call to get error %d and exit\n", IOS_ERROR_MAX);
    
    for (i = 0; i < THREAD_MAX; ++i) {
        id = IOS_CreateThread((IOSEntryProc)thd, (void*)i, stacks[i] + sizeof(stacks[i]), sizeof(stacks[i]), pri, IOS_THREAD_CREATE_DETACHED);
        IOS_StartThread(id);
    }
    IOS_SetThreadPriority(0, pri -1); 
    {
        IOSMessage msgQ[1];
        IOSMessageQueueId qid;
        IOSResourceRequest reply; 
        IOSFd fd;
        qid = IOS_CreateMessageQueue(msgQ, 1);
        fd = IOS_Open("/dev/usb/oh0", 0);
            rv = IOS_IoctlAsync(fd, OHC_IPCTEST_MSG, 0, 0, 0, 0, qid, &reply);
            if ((rv  == IOS_ERROR_MAX)) {
                    printf("PASSED: Got expected error IOS_ERROR_MAX (%d)\n", rv);
            } else {
                    printf("FAILED: Unexpected return value %d\n", rv);
            }
    }
} 
