/*
 *               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 <arm.h>
#include "ahbops.h"
#include <sys.h>

#define LOCK_CACHE  __iosDisableInt
#define UNLOCK_CACHE(mask)  __iosRestoreInt((mask))

u32 __iosDisableInt(void);
void __iosRestoreInt(u32 mask);
extern void __iosFlushDCache(void);
extern void __iosFlushDCacheByRegion(u32 ptr, u32 lines);
extern void __iosInvalidateDCacheByRegion(u32 ptr, u32 lines);
extern void __iosDrainWriteBuffer(void);

#define CACHE_LINE_SIZE (1<<CLINE)
#define CACHE_LINE_MASK (CACHE_LINE_SIZE -1)

static u32 
getLines(void *ptr, u32 *startp, u32 bytes)
{
    u32 end;
    /* round down */
    *startp = ((u32) ptr) & ~CACHE_LINE_MASK;
    /* round up */
    end  = (((u32) ptr + bytes + CACHE_LINE_MASK) & ~CACHE_LINE_MASK) - 1;
    return (end - *startp + 1)/CACHE_LINE_SIZE;
}

/* XXX horti: checks on address sent in ptr */
void
iosInvalidateDCache(void *ptr, u32 bytes)
{
    if ( bytes > 0 ) {
        u32 mask = LOCK_CACHE();

        u32 start, lines;
        lines = getLines(ptr, &start, bytes);
        __iosInvalidateDCacheByRegion(start, lines); 
        ahbMemRBInvalidate(IOS_RB_IOD);
    
        UNLOCK_CACHE(mask);
    }
    return;
}

void
iosFlushDCache(void *ptr, u32 bytes)
{
    if ( bytes > 0 ) {
        u32 mask = LOCK_CACHE();

        if ( bytes > (1<<DCACHE_SIZE)) {/* flush whole cache using test-clean */
            __iosFlushDCache();
        } else {  /* flush specified region */
            u32 start, lines;
            lines = getLines(ptr, &start, bytes);
            __iosFlushDCacheByRegion(start, lines); 
        } 
        __iosDrainWriteBuffer(); /* drain write buffers */
        ahbMemFlush(IOS_WB_IOD);

        UNLOCK_CACHE(mask);
    }
    return;
}
