/*
 *               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 <stdio.h>
#include <stdlib.h>

typedef unsigned int u32;
typedef signed int s32;
typedef s32 IOSMessage;

typedef struct IOSContext {
    u32 cpsr;
    u32 r[13];
    u32 sp;
    u32 lr;
    u32 pc;
} IOSContext;

typedef struct IOSThread {
    IOSContext context;
    struct IOSThread *next;
    s32 priority;
    u32 state;
    u32 pid;
    u32 attribute;
    void *val;
    struct IOSThread *joinQueue;
    struct IOSThread **queue;
    IOSContext extra;
#ifdef IOS_STACK_CHECK
    u32 stackBottom;
#endif
} IOSThread;
#define IOS_MESSAGE_QUEUE_MAX 64
typedef struct {
    IOSThread *emptyQ;
    IOSThread *fullQ;
    u32 owner;
    s32 count;
    s32 rptr;
    s32 size;
    IOSMessage *buffer;
} IOSMessageQueue;

IOSMessageQueue __iosQueues[IOS_MESSAGE_QUEUE_MAX];

char *__processes[] = {
    "kernel", "eticket", "fs", "di", "oh0", "oh1", "sdi", "usbeth", "net", "kd", "wd", "wl", "kd", "ncd", "stm", "ppcboot"
};
u32 nqueues;

int
initQueues(FILE *fp)
{
  nqueues = fread(__iosQueues, sizeof(IOSMessageQueue), IOS_MESSAGE_QUEUE_MAX, fp); 
 if (nqueues <= 0) {
     printf("Did not find any queues in the file\n");
     return -1;
 }

 /* Convert from be to le */
 {
     int i;
     u32 *tmp = (u32 *) __iosQueues;
     for ( i = 0; i < sizeof(__iosQueues)/sizeof(u32); ++i) {
         *tmp =  (((*tmp) & 0xff)    << 24) |
             (((*tmp) & 0xff00)  << 8)  |
             (((*tmp) & 0xff0000) >> 8) |
             (((*tmp) & 0xff000000) >> 24);
         tmp = ((u32 *)__iosQueues) + i;
     }
 }
 return 0;
}

void
__iosGetQueueUsage(int i)
{
    IOSMessageQueue *mq;
    mq = __iosQueues + i;

    if (mq->size) {
        printf("Queue: %d owner: %d (%s)\n", i, mq->owner, __processes[mq->owner]);
        printf("  size: %d, count: %d\n", mq->size, mq->count);
        printf("  emptyQ: %p, fullQ: %p\n", mq->emptyQ, mq->fullQ);
    } else {
        printf("Queue: %d (unused)\n", i);
    }
}

void
__iosGetQueuesUsage(void)
{
    int i;
    for (i = 0; i < nqueues; ++i) {
        __iosGetQueueUsage(i);
    }
    printf("\n");
}
int
main(int argc, char *argv[])
{
    FILE *fp;
    printf("total size = %u\n", IOS_MESSAGE_QUEUE_MAX*sizeof(IOSMessageQueue));
    if (argc < 2) {
        printf("Usage: %s <file>\n", argv[0]);
        printf("Total size of message queue area = %u bytes\n", IOS_MESSAGE_QUEUE_MAX*sizeof(IOSMessageQueue));
        goto done;
    }
    fp = fopen(argv[1],"r");

    if (initQueues(fp) < 0) goto done;
    __iosGetQueuesUsage();
done:
    return 0;
}
