

/*
 * Some routines for multi-core kernel operations.
 */

#include "u_kernel.h"

extern volatile kernelTable *KTBL;

unsigned int getCurrentCoreID()
{
    /* Query the USER1 bits in the PVR to determine the current core's ID. */
    pvr_t pvr_data;
    microblaze_get_pvr(&pvr_data);
    unsigned int core_id = (unsigned int) (pvr_data.pvr[0] & 0xFF);
    return core_id;
}

void enableCaches()
{
#if XPAR_MICROBLAZE_USE_ICACHE
	microblaze_enable_icache();
#endif
#if XPAR_MICROBLAZE_USE_DCACHE
	microblaze_enable_dcache();
#endif
}

void disableCaches()
{
#if XPAR_MICROBLAZE_USE_ICACHE
	microblaze_disable_icache();
#endif
#if XPAR_MICROBLAZE_USE_DCACHE
	microblaze_disable_dcache();
#endif
}


int mutex_lock(int mutex_num)
{
	unsigned int core_id = getCurrentCoreID();
    int LockPattern = ((core_id << 1) | 1);
    volatile int value;

    while(1)
    {
		putfsl(0, 2);//function = lock
		putfsl(mutex_num, 2);//mutex number
		putfsl(LockPattern, 2);//pattern
		getfsl(value, 0);
        if (value == LockPattern)
        {
            break;
        }
    }
    return value;
}


int mutex_unlock(int mutex_num)
{
	unsigned int core_id = getCurrentCoreID();
    int LockPattern = ((core_id << 1) | 1);
    volatile int value = 1;

    while(1)
    {
		putfsl(1, 2);//function = unlock
		putfsl(mutex_num, 2);//mutex number
		putfsl(LockPattern, 2);//pattern
		getfsl(value, 0);
        if (value == 0)
        {
            break;
        }
    }
    return (value == 0);
}


/*
 * The unit of return value is ticks.
 * Can be transformed into microseconds or milliseconds by
 * dividing TICKS_PER_MICROSECOND or TICKS_PER_MILLISECOND
 * ex:(int)(tmr_get_value() / (double) TICKS_PER_MILLISECOND)
 */

unsigned int tmr_get_value(void)
{
	int value;
	putfsl(1, 3);//no use,just trigger signal
	getfsl(value, 1);
	return value;
}



void *smp_malloc(size_t xWantedSize)
{
    void *pvReturn;

    mutex_lock(KENEL_MEM_MUTEX_NUM);
    pvReturn = malloc(xWantedSize);
    mutex_unlock(KENEL_MEM_MUTEX_NUM);

    return pvReturn;
}

void smp_free(void *pv)
{
    if (pv)
    {
        mutex_lock(KENEL_MEM_MUTEX_NUM);
        free(pv);
        mutex_unlock(KENEL_MEM_MUTEX_NUM);
    }
}

void smp_sleep(volatile long count)
{
	int *local_count;
	local_count = (void*)0x00003F00L;
	*local_count = 0;
	while((*local_count) < count)
		(*local_count)++;

}


/* local memory allocate */
union xRTOS_LM
{
	#if portBYTE_ALIGNMENT == 8
		volatile portDOUBLE dDummy;
	#else
		volatile unsigned long ulDummy;
	#endif
	unsigned char ucLocalMem[ configTOTAL_LM_SIZE ];
};


typedef struct A_BLOCK_LINK
{
	struct A_BLOCK_LINK *pxNextFreeBlock;	/*<< The next free block in the list. */
	size_t xBlockSize;						/*<< The size of the free block. */
} xBlockLink;

/* shared variable */
static const unsigned short  localMemSTRUCT_SIZE	= ( sizeof( xBlockLink ) + portBYTE_ALIGNMENT - ( sizeof( xBlockLink ) % portBYTE_ALIGNMENT ) );
#define localMemMINIMUM_BLOCK_SIZE	( ( size_t ) ( localMemSTRUCT_SIZE * 2 ) )
/* end */

/* private variable */
static union xRTOS_LM* xLM; /* xLM location */
static xBlockLink *xStart;
static xBlockLink *xEnd;
static size_t *xFreeBytesRemaining;
/* end */

#define prvInsertBlockIntoFreeList( pxBlockToInsert )								\
{																					\
xBlockLink *pxIterator;																\
size_t xBlockSize;																	\
																					\
	xBlockSize = pxBlockToInsert->xBlockSize;										\
																					\
	/* Iterate through the list until a block is found that has a larger size */	\
	/* than the block we are inserting. */											\
	for( pxIterator = xStart; pxIterator->pxNextFreeBlock->xBlockSize < xBlockSize; pxIterator = pxIterator->pxNextFreeBlock )	\
	{																				\
		/* There is nothing to do here - just iterate to the correct position. */	\
	}																				\
																					\
	/* Update the list to include the block being inserted in the correct */		\
	/* position. */																	\
	pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock;					\
	pxIterator->pxNextFreeBlock = pxBlockToInsert;									\
}
/*-----------------------------------------------------------*/

#define prvLocalMemInit()															\
{																					\
xBlockLink *pxFirstFreeBlock;														\
																					\
	xLM = (void*)0x2000;															\
	xStart = (void*)0x1900;															\
	xEnd = (void*)0x1920;															\
	xFreeBytesRemaining = (void*)0x1940;											\
	*xFreeBytesRemaining = configTOTAL_LM_SIZE;										\
	/* xStart is used to hold a pointer to the first item in the list of free */	\
	/* blocks.  The void cast is used to prevent compiler warnings. */				\
	xStart->pxNextFreeBlock = ( void * ) xLM->ucLocalMem;							\
	xStart->xBlockSize = ( size_t ) 0;												\
																					\
	/* xEnd is used to mark the end of the list of free blocks. */					\
	xEnd->xBlockSize = configTOTAL_LM_SIZE;											\
	xEnd->pxNextFreeBlock = NULL;													\
																					\
	/* To start with there is a single free block that is sized to take up the		\
	entire local memory space. */													\
	pxFirstFreeBlock = ( void * ) xLM->ucLocalMem;									\
	pxFirstFreeBlock->xBlockSize = configTOTAL_LM_SIZE;								\
	pxFirstFreeBlock->pxNextFreeBlock = xEnd;										\
}
/*-----------------------------------------------------------*/

//void *pvPortMalloc( size_t xWantedSize )
void *lm_alloc( size_t xWantedSize)
{
xBlockLink *pxBlock, *pxPreviousBlock, *pxNewBlockLink;
//static int xLMHasBeenInitialised = 0;
int *xLMHasBeenInitialised = (void*)0x1940;
void *pvReturn = NULL;

	{
		/* If this is the first call to malloc then the local memory will require
		initialisation to setup the list of free blocks. */
		if( *xLMHasBeenInitialised == 0 )
		{
			prvLocalMemInit();
			*xLMHasBeenInitialised = 1;
		}

		/* The wanted size is increased so it can contain a xBlockLink
		structure in addition to the requested amount of bytes. */
		if( xWantedSize > 0 )
		{
			xWantedSize += localMemSTRUCT_SIZE;

			/* Ensure that blocks are always aligned to the required number of bytes. */
			if( xWantedSize & portBYTE_ALIGNMENT_MASK )
			{
				/* Byte alignment required. */
				xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) );
			}
		}

		if( ( xWantedSize > 0 ) && ( xWantedSize < configTOTAL_LM_SIZE ) )
		{
			/* Blocks are stored in byte order - traverse the list from the start
			(smallest) block until one of adequate size is found. */
			pxPreviousBlock = xStart;
			pxBlock = xStart->pxNextFreeBlock;
			while( ( pxBlock->xBlockSize < xWantedSize ) && ( pxBlock->pxNextFreeBlock ) )
			{
				pxPreviousBlock = pxBlock;
				pxBlock = pxBlock->pxNextFreeBlock;
			}

			/* If we found the end marker then a block of adequate size was not found. */
			if( pxBlock != xEnd )
			{
				/* Return the memory space - jumping over the xBlockLink structure
				at its start. */
				pvReturn = ( void * ) ( ( ( unsigned char * ) pxPreviousBlock->pxNextFreeBlock ) + localMemSTRUCT_SIZE );

				/* This block is being returned for use so must be taken our of the
				list of free blocks. */
				pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock;

				/* If the block is larger than required it can be split into two. */
				if( ( pxBlock->xBlockSize - xWantedSize ) > localMemMINIMUM_BLOCK_SIZE )
				{
					/* This block is to be split into two.  Create a new block
					following the number of bytes requested. The void cast is
					used to prevent byte alignment warnings from the compiler. */
					pxNewBlockLink = ( void * ) ( ( ( unsigned char * ) pxBlock ) + xWantedSize );

					/* Calculate the sizes of two blocks split from the single
					block. */
					pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize;
					pxBlock->xBlockSize = xWantedSize;

					/* Insert the new block into the list of free blocks. */
					prvInsertBlockIntoFreeList( ( pxNewBlockLink ) );
				}

				(*xFreeBytesRemaining) -= pxBlock->xBlockSize;
			}
		}
	}

	#if( configUSE_MALLOC_FAILED_HOOK == 1 )
	{
		if( pvReturn == NULL )
		{
			extern void vApplicationMallocFailedHook( void );
			vApplicationMallocFailedHook();
		}
	}
	#endif

	return pvReturn;
}
/*-----------------------------------------------------------*/

void vPortFree( void *pv )
{
unsigned char *puc = ( unsigned char * ) pv;
xBlockLink *pxLink;

	if( pv )
	{
		/* The memory being freed will have an xBlockLink structure immediately
		before it. */
		puc -= localMemSTRUCT_SIZE;

		/* This casting is to keep the compiler from issuing warnings. */
		pxLink = ( void * ) puc;

		{
			/* Add this block to the list of free blocks. */
			prvInsertBlockIntoFreeList( ( ( xBlockLink * ) pxLink ) );
			(*xFreeBytesRemaining) += pxLink->xBlockSize;
		}
	}
}
/*-----------------------------------------------------------*/

size_t xPortGetFreeLocalMemSize( void )
{
	return *xFreeBytesRemaining;
}
/*-----------------------------------------------------------*/

void vPortInitialiseBlocks( void )
{
	/* This just exists to keep the linker quiet. */
}



volatile int* reg_src_addr = (int*) (0xFFF0);
volatile int* reg_dst_addr = (int*) (0xFFF4);
volatile int* reg_length = (int*) (0xFFF8);
volatile int* reg_cmd_flag = (int*) (0xFFFC);

/*
 * len is the number of byte to transfer.
 * Need to confirm the previous transfer has completed before the next call
 * or the current transfer may be interfered.
 */
void lm_transfer(void* dst_addr, void* src_addr, int len)
{
	(*reg_src_addr) =  (int)src_addr;
	(*reg_dst_addr) =  (int)dst_addr;
	(*reg_length) = len;//for byte address
	(*reg_cmd_flag) = 1;
}

int transfer_status(void)
{
	return (*reg_cmd_flag);
}


