/*
 *               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;

#define IOS_CHUNK_FREE   0xbabe0000
#define IOS_CHUNK_INUSE  0xbabe0001
#define IOS_CHUNK_INUSE_ALIGNED 0xbabe0002
typedef struct IOSChunk {
    u32 status;
    u32 size;
    struct IOSChunk *prevFree;
    struct IOSChunk *nextFree;
} IOSChunk;

typedef struct {
    void *base;
    u32 owner;
    u32 size;
    IOSChunk *freeList;
} IOSHeap;

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

int
initHeaps(FILE *fp)
{
  nqueues = fread(__heaps, sizeof(IOSHeap), IOS_HEAP_MAX, fp); 
 if (nqueues <= 0) {
     printf("Did not find any heaps in the file\n");
     return -1;
 }

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

void
__iosGetHeapUsage(int i)
{
    IOSHeap *h = __heaps + i;
    printf("Heap %d : ", i);
    if (!h->base) { 
        printf("unused\n");
        return;
    }
    printf("\n");
    printf("  base: %p, size: %d\n", h->base, h->size);
    printf("  owner: %d (%s)\n", h->owner, __processes[h->owner]);
    printf("  freeList: %p\n", h->freeList);
//    IOSChunk *p = h->freeList;
//    while (p) {
//        printf("    base: %08x, size: %d\n", p, p->size);
//        p = p->nextFree;
//    }
}

void
__iosGetHeapsUsage(void)
{
    int i;

    for (i = 0; i < IOS_HEAP_MAX; ++i) {
        __iosGetHeapUsage(i);
    }
    printf("\n");
}
int
main(int argc, char *argv[])
{
    FILE *fp;
    if (argc < 2) {
        printf("Usage: %s <file>\n", argv[0]);
        printf("Total size of heap area = %u bytes\n", IOS_HEAP_MAX*sizeof(IOSHeap));
        goto done;
    }
    fp = fopen(argv[1],"r");

    if (initHeaps(fp) < 0) goto done;
    __iosGetHeapsUsage();
done:
    return 0;
}
