Beispiel #1
0
static bool fifoInternalSend(u32 firstword, int extrawordcount, u32 * wordlist) {
	if(extrawordcount>0 && !wordlist) return false;
	if(fifo_freewords<extrawordcount+1) return false;
	if(extrawordcount<0 || extrawordcount>(FIFO_MAX_DATA_BYTES/4)) return false;

	int count = 0;
	int oldIME = enterCriticalSection();

	u32 head = fifo_waitBlock();
	if(fifo_send_queue.head == FIFO_BUFFER_TERMINATE) {
		fifo_send_queue.head = head;
	} else {
		FIFO_BUFFER_SETNEXT(fifo_send_queue.tail,head);		
	}
	FIFO_BUFFER_DATA(head)=firstword;
	fifo_send_queue.tail = head;

	while (count<extrawordcount) {
		u32 next = fifo_waitBlock();
		if(fifo_send_queue.head == FIFO_BUFFER_TERMINATE) {
			fifo_send_queue.head = next;
		} else {
			FIFO_BUFFER_SETNEXT(fifo_send_queue.tail,next);		
		}
		FIFO_BUFFER_DATA(next)=wordlist[count];
		count++;
		fifo_send_queue.tail = next;
	}

	REG_IPC_FIFO_CR |= IPC_FIFO_SEND_IRQ;

	leaveCriticalSection(oldIME);
	
	return true;
}
Beispiel #2
0
//---------------------------------------------------------------------------------
void irqClearAUX(u32 mask) {
//---------------------------------------------------------------------------------
    int oldIME = enterCriticalSection();
    __irqClear(mask,irqTableAUX);
    irqDisable( mask);
    leaveCriticalSection(oldIME);
}
Beispiel #3
0
int fifoGetDatamsg(int channel, int buffersize, u8 * destbuffer) {
	if(channel<0 || channel>=FIFO_NUM_CHANNELS) return -1;
	int block = fifo_data_queue[channel].head;
	if (block == FIFO_BUFFER_TERMINATE) return -1;
	int oldIME = enterCriticalSection();

	int num_bytes = FIFO_BUFFER_GETEXTRA(block);
	int	num_words = (num_bytes+3)>>2;
	u32 buffer_array[num_words];

	int i,next;
	for(i=0; i<num_words;i++) {
		buffer_array[i] = FIFO_BUFFER_DATA(block);
		next=FIFO_BUFFER_GETNEXT(block);
		fifo_freeBlock(block);
		block=next;
		if(block==FIFO_BUFFER_TERMINATE) break;
	}
	fifo_data_queue[channel].head = block;

	if(buffersize<num_bytes) num_bytes=buffersize;
	memcpy(destbuffer,buffer_array,num_bytes);

	leaveCriticalSection(oldIME);
	return num_bytes;
	
}
Beispiel #4
0
//---------------------------------------------------------------------------------
void sdmmc_controller_init() {
//---------------------------------------------------------------------------------
	int oldIME = enterCriticalSection();
	// Reset
	sdmmc_write16(0x100, 0x0402);
	sdmmc_write16(0x100, 0x0000);
	sdmmc_write16(0x104, 0x0000);
	sdmmc_write16(0x108, 0x0001);

	// InitIP
	sdmmc_mask16(REG_SDRESET, 0x0001, 0x0000);
	sdmmc_mask16(REG_SDRESET, 0x0000, 0x0001);
	sdmmc_mask16(REG_SDSTOP, 0x0001, 0x0000);

	// Reset
	sdmmc_mask16(REG_SDOPT, 0x0005, 0x0000);

	// EnableInfo
	sdmmc_mask16(REG_SDSTATUS0, 0x0018, 0x0000);
	sdmmc_mask16(0x20, 0x0018, 0x0000); // ??
	sdmmc_mask16(0x20, 0x0000, 0x0018);

	sdmmc_init_irq();
	leaveCriticalSection(oldIME);
}
//------------------------------------------------------------------------------
tOplkError timeru_deleteTimer(tTimerHdl* pTimerHdl_p)
{
    tTimerEntry*    pTimerEntry;
    tTimerEntry**   ppEntry;

    // check pointer to handle
    if (pTimerHdl_p == NULL)
        return kErrorTimerInvalidHandle;

    // check handle itself, i.e. was the handle initialized before
    if (*pTimerHdl_p == 0)
        return kErrorOk;

    pTimerEntry = (tTimerEntry*)*pTimerHdl_p;

    // remove timer entry from timer list
    enterCriticalSection(TIMERU_TIMER_LIST);
    ppEntry = &timeruInstance_l.pTimerListFirst;
    while (*ppEntry != NULL)
    {
        if (*ppEntry == pTimerEntry)
        {
            *ppEntry = pTimerEntry->pNext;
            if (*ppEntry != NULL)
            {
                (*ppEntry)->timeoutInMs += pTimerEntry->timeoutInMs;
            }
            break;
        }

        ppEntry = &(*ppEntry)->pNext;
    }
    leaveCriticalSection(TIMERU_TIMER_LIST);

    // insert in free list
    enterCriticalSection(TIMERU_FREE_LIST);
    pTimerEntry->pNext = timeruInstance_l.pFreeListFirst;
    timeruInstance_l.pFreeListFirst = pTimerEntry;
    timeruInstance_l.freeEntries++;
    leaveCriticalSection(TIMERU_FREE_LIST);

    // set handle invalid
    *pTimerHdl_p = 0;
    return kErrorOk;

}
//------------------------------------------------------------------------------
static DWORD WINAPI processThread(LPVOID parameter_p)
{
    tTimerEntry*    pTimerEntry;
    UINT32          timeoutInMs;
    UINT32          waitResult;
    tOplkError      ret;

    UNUSED_PARAMETER(parameter_p);

    for (;;)
    {
        ret = timeru_process();
        if (ret != kErrorOk)
        {
            // Error
        }

        // calculate time until the next timer event
        enterCriticalSection(TIMERU_TIMER_LIST);
        pTimerEntry = timeruInstance_l.pTimerListFirst;
        if (pTimerEntry == NULL)
        {   // timer list is empty
            timeoutInMs = INFINITE;
        }
        else
        {
            timeoutInMs = getTickCount() - timeruInstance_l.startTimeInMs;
            if (timeoutInMs > pTimerEntry->timeoutInMs)
            {   // timeout elapsed
                timeoutInMs = 0;
            }
            else
            {   // adjust timeout with elapsed time since start time
                timeoutInMs = pTimerEntry->timeoutInMs - timeoutInMs;
            }
        }
        leaveCriticalSection(TIMERU_TIMER_LIST);

        waitResult = WaitForMultipleObjects(2, timeruInstance_l.ahEvents, FALSE, timeoutInMs);
        switch (waitResult)
        {
            case (WAIT_OBJECT_0 + TIMERU_EVENT_SHUTDOWN):
                goto Exit;
                break;

            case (WAIT_OBJECT_0 + TIMERU_EVENT_WAKEUP):
            case WAIT_TIMEOUT:
                break;

            default:
                // Error
                break;
        }
    }

Exit:
    return 0;
}
Beispiel #7
0
void * fifoGetAddress(int channel) {
	if(channel<0 || channel>=FIFO_NUM_CHANNELS) return NULL;
	int block = fifo_address_queue[channel].head;
	if (block == FIFO_BUFFER_TERMINATE) return NULL;
	int oldIME = enterCriticalSection();
	void *address = (void*)FIFO_BUFFER_DATA(block);
	fifo_address_queue[channel].head = FIFO_BUFFER_GETNEXT(block);
	fifo_freeBlock(block);
	leaveCriticalSection(oldIME);
	return address;
}
Beispiel #8
0
//---------------------------------------------------------------------------------
void irqSet(u32 mask, IntFn handler) {
//---------------------------------------------------------------------------------
    int oldIME = enterCriticalSection();
    __irqSet(mask,handler,irqTable);
    if(mask & IRQ_VBLANK)
        REG_DISPSTAT |= DISP_VBLANK_IRQ ;
    if(mask & IRQ_HBLANK)
        REG_DISPSTAT |= DISP_HBLANK_IRQ ;
    if(mask & IRQ_IPC_SYNC)
        REG_IPC_SYNC |= IPC_SYNC_IRQ_ENABLE;
    leaveCriticalSection(oldIME);
}
Beispiel #9
0
u32 fifoGetValue32(int channel) {
	if(channel<0 || channel>=FIFO_NUM_CHANNELS) return 0;
	int block = fifo_value32_queue[channel].head;
	if ( block == FIFO_BUFFER_TERMINATE) return 0;

	int oldIME = enterCriticalSection();
	u32 value32 = FIFO_BUFFER_DATA(block);
	fifo_value32_queue[channel].head = FIFO_BUFFER_GETNEXT(block);
	fifo_freeBlock(block);
	leaveCriticalSection(oldIME);
	return value32;
}
Beispiel #10
0
/* Lookup or create a new TraceInfo */
static TraceInfo *
lookupOrEnter(jvmtiEnv *jvmti, Trace *trace, TraceFlavor flavor)
{
    TraceInfo *tinfo;
    jlong      hashCode;

    /* Calculate hash code (outside critical section to lessen contention) */
    hashCode = hashTrace(trace);

    /* Do a lookup in the hash table */
    enterCriticalSection(jvmti);
    {
        TraceInfo *prev;
        int        hashIndex;

        /* Start with first item in hash buck chain */
        prev = NULL;
        hashIndex = (int)(hashCode & HASH_INDEX_MASK);
        tinfo = gdata->hashBuckets[hashIndex];
        while ( tinfo != NULL ) {
            if ( tinfo->hashCode == hashCode &&
                    memcmp(trace, &(tinfo->trace), sizeof(Trace))==0 ) {
                /* We found one that matches, move to head of bucket chain */
                if ( prev != NULL ) {
                    /* Remove from list and add to head of list */
                    prev->next = tinfo->next;
                    tinfo->next = gdata->hashBuckets[hashIndex];
                    gdata->hashBuckets[hashIndex] = tinfo;
                }
                /* Break out */
                break;
            }
            prev = tinfo;
            tinfo = tinfo->next;
        }

        /* If we didn't find anything we need to enter a new entry */
        if ( tinfo == NULL ) {
            /* Create new hash table element */
            tinfo = newTraceInfo(trace, hashCode, flavor);
        }

        /* Update stats */
        (void)updateStats(tinfo);

    }
    exitCriticalSection(jvmti);

    return tinfo;
}
Beispiel #11
0
void CPythonEngine::threadGILAcquire(int ms)
{
    init();
    enterCriticalSection();

    PyGILState_STATE gstate;
    gstate = PyGILState_Ensure();
    char buf[128];
    sprintf(buf, "time.sleep(%d.%03d)", ms / 1000, ms % 1000);
    PyRun_SimpleString(buf);

    PyGILState_Release(gstate);
    leaveCriticalSection();
}
Beispiel #12
0
//---------------------------------------------------------------------------------
void irqDisable(uint32 irq) {
//---------------------------------------------------------------------------------
    int oldIME = enterCriticalSection();
    if (irq & IRQ_VBLANK)
        REG_DISPSTAT &= ~DISP_VBLANK_IRQ ;
    if (irq & IRQ_HBLANK)
        REG_DISPSTAT &= ~DISP_HBLANK_IRQ ;
    if (irq & IRQ_VCOUNT)
        REG_DISPSTAT &= ~DISP_YTRIGGER_IRQ;
    if(irq & IRQ_IPC_SYNC)
        REG_IPC_SYNC &= ~IPC_SYNC_IRQ_ENABLE;

    REG_IE &= ~irq;
    leaveCriticalSection(oldIME);
}
Beispiel #13
0
void CPythonEngine::backpipeTamsgTick()
{
    init();
    enterCriticalSection();
    long int tm = GetTickCount();
    CMemReader& reader = CMemReader::getMemReader();
    CIpcMessage mess;

    if (CIPCBackPipe::readFromPipe(&mess, 1007))
    {
        int msgLen;
        char msgBuf[16384];

        memset(msgBuf, 0, 16384);
        memcpy(&msgLen, mess.payload, sizeof(int));
        memcpy(msgBuf, mess.payload + 4, msgLen);

        int scriptNr;
        for (scriptNr = 0;; scriptNr++)
        {
            CPythonScript *pythonScript = CPythonScript::getScriptByNr(scriptNr);
            if (!pythonScript)
                break;
            if (!pythonScript->isEnabled())
                continue;
            int funNr;
            for (funNr = 0;; funNr++)
            {
                struct funType *fun = pythonScript->getFunDef(funNr);
                if (!fun)
                    break;

                if (fun->type == FUNTYPE_TAMSG)
                {
                    PyGILState_STATE gstate;
                    gstate = PyGILState_Ensure();
                    PyObject *params = pythonScript->getParamsDic();
                    PyObject *result = PyObject_CallMethod(pythonScript->getPluginObject(), fun->name, "(Os)", params, msgBuf);
                    Py_XDECREF(params);
                    Py_XDECREF(result);
                    fun->call();
                    PyGILState_Release(gstate);
                }
            }
        }
    }
    leaveCriticalSection();
}
Beispiel #14
0
int writeFirmwarePage(u32 address,u8 *buffer) {
	int i;
	u8 pagebuffer[256];
	readFirmware(address, pagebuffer, 256);
	
	if(memcmp(pagebuffer, buffer, 256) == 0) return 0;
	
	int oldIME = enterCriticalSection();
	
	//write enable
	REG_SPICNT = SPI_ENABLE | SPI_CONTINUOUS | SPI_DEVICE_NVRAM;
	readwriteSPI(FIRMWARE_WREN);
	REG_SPICNT = 0;
	
	//Wait for Write Enable Latch to be set
	REG_SPICNT = SPI_ENABLE | SPI_CONTINUOUS | SPI_DEVICE_NVRAM;
	readwriteSPI(FIRMWARE_RDSR);
	while((readwriteSPI(0) & 0x02) == 0); //Write Enable Latch
	REG_SPICNT = 0;
	
	//page write
	REG_SPICNT = SPI_ENABLE | SPI_CONTINUOUS | SPI_DEVICE_NVRAM;
	readwriteSPI(FIRMWARE_PW);
	// Set the address
	readwriteSPI((address>>16) & 0xff);
	readwriteSPI((address>> 8) & 0xff);
	readwriteSPI((address) & 0xff);
	
	for(i = 0; i < 256; i++) {
		readwriteSPI(buffer[i]);
	}
	
	REG_SPICNT = 0;
	
	// wait for programming to finish
	REG_SPICNT = SPI_ENABLE|SPI_CONTINUOUS|SPI_DEVICE_NVRAM;
	readwriteSPI(FIRMWARE_RDSR);
	while(readwriteSPI(0) & 0x01); //Write In Progress
	REG_SPICNT = 0;
	
	leaveCriticalSection(oldIME);
	
	// read it back & verify
	readFirmware(address, pagebuffer, 256);
	if(memcmp(pagebuffer, buffer, 256) == 0) return 0;
	return -1;
}
//------------------------------------------------------------------------------
tOplkError timeru_process(void)
{
    tTimerEntry*        pTimerEntry;
    UINT32              timeoutInMs;
    tEvent              event;
    tTimerEventArg      timerEventArg;
    tOplkError          ret = kErrorOk;

    enterCriticalSection(TIMERU_TIMER_LIST);
    // calculate elapsed time since start time
    timeoutInMs = getTickCount() - timeruInstance_l.startTimeInMs;

    // observe first timer entry in timer list
    pTimerEntry = timeruInstance_l.pTimerListFirst;
    if (pTimerEntry != NULL)
    {
        if (timeoutInMs >= pTimerEntry->timeoutInMs)
        {   // timeout elapsed - remove entry from timer list
            timeruInstance_l.pTimerListFirst = pTimerEntry->pNext;
            // adjust start time
            timeruInstance_l.startTimeInMs += pTimerEntry->timeoutInMs;
        }
        else
        {
            pTimerEntry = NULL;
        }
    }
    leaveCriticalSection(TIMERU_TIMER_LIST);

    if (pTimerEntry != NULL)
    {
        // call event function
        timerEventArg.timerHdl = (tTimerHdl)pTimerEntry;
        OPLK_MEMCPY(&timerEventArg.argument, &pTimerEntry->timerArg.argument, sizeof(timerEventArg.argument));

        event.eventSink = pTimerEntry->timerArg.eventSink;
        event.eventType = kEventTypeTimer;
        OPLK_MEMSET(&event.netTime, 0x00, sizeof(tNetTime));
        event.pEventArg = &timerEventArg;
        event.eventArgSize = sizeof(timerEventArg);

        ret = eventu_postEvent(&event);
    }

    return ret;
}
Beispiel #16
0
void CVmc::setMotorRPM(int motor, int rpm)
{
	if((rpm < -1*_maxRpm) || (rpm > _maxRpm)) return;
	if((motor < 1) || (motor > 3)) return;

	enterCriticalSection();

	switch(motor)
	{
		case 1: _pwmOut1= rpm; break;
		case 2: _pwmOut2= rpm; break;
		case 3: _pwmOut3= rpm; break;
		default: break;
	}

	leaveCriticalSection();
}
Beispiel #17
0
/* Callback for JVMTI_EVENT_VM_START */
static void JNICALL
cbVMStart(jvmtiEnv *jvmti, JNIEnv *env)
{
    enterCriticalSection(jvmti);
    {
        jclass klass;
        jfieldID field;
        jint rc;

        /* Java Native Methods for class */
        static JNINativeMethod registry[2] = {
            {   STRING(HEAP_TRACKER_native_newobj), "(Ljava/lang/Object;Ljava/lang/Object;)V",
                (void*)&HEAP_TRACKER_native_newobj
            },
            {   STRING(HEAP_TRACKER_native_newarr), "(Ljava/lang/Object;Ljava/lang/Object;)V",
                (void*)&HEAP_TRACKER_native_newarr
            }
        };

        /* Register Natives for class whose methods we use */
        klass = (*env)->FindClass(env, STRING(HEAP_TRACKER_class));
        if ( klass == NULL ) {
            fatal_error("ERROR: JNI: Cannot find %s with FindClass\n",
                        STRING(HEAP_TRACKER_class));
        }
        rc = (*env)->RegisterNatives(env, klass, registry, 2);
        if ( rc != 0 ) {
            fatal_error("ERROR: JNI: Cannot register natives for class %s\n",
                        STRING(HEAP_TRACKER_class));
        }

        /* Engage calls. */
        field = (*env)->GetStaticFieldID(env, klass, STRING(HEAP_TRACKER_engaged), "I");
        if ( field == NULL ) {
            fatal_error("ERROR: JNI: Cannot get field from %s\n",
                        STRING(HEAP_TRACKER_class));
        }
        (*env)->SetStaticIntField(env, klass, field, 1);

        /* Indicate VM has started */
        gdata->vmStarted = JNI_TRUE;

    }
    exitCriticalSection(jvmti);
}
Beispiel #18
0
// fifoSetAddressHandler - Set a callback to receive incoming address messages on a specific channel.
bool fifoSetAddressHandler(int channel, FifoAddressHandlerFunc newhandler, void * userdata) {
	if(channel<0 || channel>=FIFO_NUM_CHANNELS) return false;

	int oldIME = enterCriticalSection();

	fifo_address_func[channel] = newhandler;
	fifo_address_data[channel] = userdata;
	
	if(newhandler) {
		while(fifoCheckAddress(channel)) {
			newhandler( fifoGetAddress(channel), userdata );
		}
	}

	leaveCriticalSection(oldIME);

	return true;
}
/* Callback for JVMTI_EVENT_VM_INIT */
static void JNICALL
cbVMInit(jvmtiEnv *jvmti, JNIEnv *env, jthread thread)
{
    jvmtiHeapCallbacks heapCallbacks;
    jvmtiError         error;
    
    /* Iterate through heap, find all untagged objects allocated before this */
    (void)memset(&heapCallbacks, 0, sizeof(heapCallbacks));
    heapCallbacks.heap_iteration_callback = &cbObjectTagger;
    error = (*jvmti)->IterateThroughHeap(jvmti, JVMTI_HEAP_FILTER_TAGGED, 
                                         NULL, &heapCallbacks, NULL);
    check_jvmti_error(jvmti, error, "Cannot iterate through heap");

    enterCriticalSection(jvmti); {
        
        /* Indicate VM is initialized */
        gdata->vmInitialized = JNI_TRUE;
    
    } exitCriticalSection(jvmti);
}
Beispiel #20
0
bool MaekawaAlgorithm::receiveLocked(Packet locked){
    
    printf("----Node %d has received LOCKED message from %d \n",processID,locked.ORIGIN);
//    //Compare and maximize the sequence number
//    if(sequenceNo < locked.SEQ)
//        sequenceNo = locked.SEQ;
    
    //Increase hasReceivedLockedMessage by 1. If this variable reaches K-1, then the node can enter the critical section.
    //hasReceivedLockedMessage++;
    
    //Update quorumVote table
    
    int temp = -1;
    for(int i = 0; i < quorumsize; i++){
        if(quorumVote[i][0] == locked.ORIGIN) temp = i;
    }
    quorumVote[temp][1] = 1;
    
    hasReceivedLockedMessage = 0;
    
    printf("--^^--quorumVote Table--^^-- \n");
    
    //Check if the current node has received all the locked messages
    for(int i = 0; i < quorumsize; i++){
        printf("%d , %d \n",quorumVote[i][0],quorumVote[i][1]);
        if(quorumVote[i][1] == 1){
            hasReceivedLockedMessage++;
        }
    }
    printf("----Node %d has received %d LOCKED messages \n",processID,hasReceivedLockedMessage);
    
    if(hasReceivedLockedMessage == quorumsize){
        
        printf("----Node %d has entered critical section \n",processID);
        enterCriticalSection();
        //printf("Node %d has exited critical section \n",processID);
        return true;
    }
    return true;
}
Beispiel #21
0
void CPythonEngine::periodicalTick()
{
    init();
    enterCriticalSection();
    long int tm = GetTickCount();
    int scriptNr;
    for (scriptNr = 0;; scriptNr++)
    {
        CPythonScript *pythonScript = CPythonScript::getScriptByNr(scriptNr);
        if (!pythonScript)
            break;
        if (!pythonScript->isEnabled())
            continue;
        int funNr;
        for (funNr = 0;; funNr++)
        {
            struct funType *fun = pythonScript->getFunDef(funNr);
            if (!fun)
                break;

            if (fun->type == FUNTYPE_PERIODICAL && tm >= fun->tmNextExec)
            {
                CPythonScript *pythonScript = CPythonScript::getScriptByNr(scriptNr);

                PyGILState_STATE gstate;
                gstate = PyGILState_Ensure();
                PyObject *params = pythonScript->getParamsDic();
                PyObject *result = PyObject_CallMethod(pythonScript->getPluginObject(), fun->name, "(O)", params);
                Py_XDECREF(params);
                Py_XDECREF(result);

                fun->call();

                PyGILState_Release(gstate);
            }
        }
    }
    leaveCriticalSection();
}
Beispiel #22
0
// fifoSetDatamsgHandler - Set a callback to receive incoming data sequences on a specific channel.
bool fifoSetDatamsgHandler(int channel, FifoDatamsgHandlerFunc newhandler, void * userdata) {
	if(channel<0 || channel>=FIFO_NUM_CHANNELS) return false;

	int oldIME = enterCriticalSection();

	fifo_datamsg_func[channel] = newhandler;
	fifo_datamsg_data[channel] = userdata;


	if(newhandler) {
		while(fifoCheckDatamsg(channel)) {
			int block = fifo_data_queue[channel].head;
			int n_bytes = FIFO_UNPACK_DATALENGTH(FIFO_BUFFER_DATA(block));
			newhandler(n_bytes, userdata);
			if (block == fifo_data_queue[channel].head) fifoGetDatamsg(channel,0,0);
		}
	}

	leaveCriticalSection(oldIME);

	return true;
}
Beispiel #23
0
void CPythonEngine::unloadScript(int scriptNr)
{


    init();
    enterCriticalSection();
    CPythonScript *pythonScript = CPythonScript::getScriptByNr(scriptNr);
    pythonScript->setEnabled(false);
    struct funType *fun = NULL;
    for (int funNr = 0; (fun = pythonScript->getFunDef(funNr)); funNr++)
    {
        if (fun->type == FUNTYPE_INPACKET)
            CPackSender::unregisterInpacketRegex(fun->matchExprHandle);
    }

    CPythonScript::pythonScriptTab[scriptNr] = CPythonScript::pythonScriptTab[CPythonScript::pythonScriptCount - 1];
    CPythonScript::pythonScriptCount--;
    registerPluginCount--;
    // this is commented out by purpose - there would be too much threads
    // playing to cleanup this memory here
    //delete pythonScript;//crashes TA on reloading script possibly fix later!
    leaveCriticalSection();
}
Beispiel #24
0
// Calls python functions of type 3 when we receive notice of an incoming packet
void CPythonEngine::backpipeInpacketTick()
{
    init();
    enterCriticalSection();
    CMemReader& reader = CMemReader::getMemReader();
    CIpcMessage mess;
    struct parcelRecvActionData* pd;

    //runs at most 'maxtimes' python functions each tick
    for (int maxtimes = 5; CIPCBackPipe::readFromPipe(&mess, 1010) && maxtimes > 0; maxtimes--)
    {
        char buf[1024];

        long int tm = GetTickCount();
        pd = (parcelRecvActionData*)&(mess.payload);

        int discardIncompletePacket = pd->countLeft + 1 != pd->totalCount; //the initial packets were too old and were discarded

        int countLeft = pd->countLeft;
        int msgLen    = pd->len;
        int handle    = pd->handle;
        char* msgBuf  = (char*)malloc(sizeof(pd->actionData) * (countLeft + 1));
        memcpy(msgBuf, pd->actionData, pd->len);
        while (countLeft && GetTickCount() - tm < 200)  // wait for remaining sections to come in for up to 200ms(they should always be on their way)
        {
            if (CIPCBackPipe::readFromPipe(&mess, 1010))
            {
                if (pd->handle != handle || pd->countLeft != countLeft - 1)
                    sprintf(buf, "ERROR in backpipeInpacketTick: handle %d should be %d and count %d should be %d", pd->handle, handle, pd->countLeft, countLeft - 1);
                //AfxMessageBox(buf);
                memcpy(msgBuf + msgLen, pd->actionData, pd->len);
                msgLen   += pd->len;
                countLeft = pd->countLeft;
            }
        }
        if (countLeft)
        {
            sprintf(buf, "ERROR in backpipeInpacketTick: did not finish reading data");
            //AfxMessageBox(buf);
        }
        else if (discardIncompletePacket)
        {
            int a = 0;// discard data and continue
        }
        else     //everything is OK
        {
            sprintf(buf, "One packet took %dms", GetTickCount() - tm);
            //if (GetTickCount() - tm>20) MessageBox(NULL, buf,"huaeotnre",0);
            CPythonScript *pythonScript = NULL;
            for (int scriptNr = 0; (pythonScript = CPythonScript::getScriptByNr(scriptNr)); scriptNr++)
            {
                if (!pythonScript->isEnabled())
                    continue;
                struct funType *fun = NULL;
                for (int funNr = 0; (fun = pythonScript->getFunDef(funNr)); funNr++)
                {
                    if (fun->type == FUNTYPE_INPACKET && fun->matchExprHandle == pd->handle)
                    {
                        PyGILState_STATE gstate;
                        gstate = PyGILState_Ensure();
                        PyObject *result = PyObject_CallMethod(pythonScript->getPluginObject(), fun->name, "(s#)", msgBuf, msgLen);
                        Py_XDECREF(result);
                        fun->call();
                        PyGILState_Release(gstate);
                        goto inpacketTickCleanup;
                    }
                }
            }
        }
inpacketTickCleanup:
        msgBuf[0] = 0;
        free(msgBuf);
    }
    leaveCriticalSection();
}
Beispiel #25
0
//---------------------------------------------------------------------------------
int sdmmc_sdcard_init() {
//---------------------------------------------------------------------------------
	u16 sdaddr;
	u32 resp0;
	u32 resp1;
	u32 resp2;
	u32 resp3;
	u32 resp4;
	u32 resp5;
	u32 resp6;
	u32 resp7;

	u32 ocr, ccs, hcs, response;

	sdmmc_cardready = 0;

	int oldIME = enterCriticalSection();

	sdmmc_write16(REG_SDCLKCTL, 0x20);
	sdmmc_write16(REG_SDOPT, 0x40EA); // XXX: document me!
	sdmmc_write16(0x02, 0x400);

	sdmmc_mask16(REG_SDCLKCTL, 0, 0x100);
	sdmmc_write16(REG_SDCLKCTL, sdmmc_read16(REG_SDCLKCTL));
	sdmmc_mask16(REG_SDCLKCTL, 0x100, 0);
	sdmmc_mask16(REG_SDCLKCTL, 0, 0x200);
	sdmmc_mask16(REG_SDCLKCTL, 0, 0x100);

	// CMD0
	sdmmc_send_command(0x0000, 0x0000, 0x0000);
	sdmmc_send_command(0x0408, 0x01aa, 0x0000);
	sdmmc_gotcmd8reply = 1;

	if(sdmmc_timeout)
		sdmmc_gotcmd8reply = 0;

	if(sdmmc_gotcmd8reply)
		hcs = (1<<30);
	else
		hcs = 0;

	ocr = 0x00ff8000;

	while (1) {
		sdmmc_send_acmd41(ocr | hcs, &response);

		if (response & 0x80000000)
			break;
	}

	ccs = response & (1<<30);

	if(ccs && hcs) 
		sdmmc_sdhc = 1;
	else
		sdmmc_sdhc = 0;

	// CMD2 - get CID
	sdmmc_send_command(2, 0, 0);
	
	resp0 = sdmmc_read16(REG_SDRESP0);
	resp1 = sdmmc_read16(REG_SDRESP1);
	resp2 = sdmmc_read16(REG_SDRESP2);
	resp3 = sdmmc_read16(REG_SDRESP3);
	resp4 = sdmmc_read16(REG_SDRESP4);
	resp5 = sdmmc_read16(REG_SDRESP5);
	resp6 = sdmmc_read16(REG_SDRESP6);
	resp7 = sdmmc_read16(REG_SDRESP7);

	sdmmc_cid[0] = resp0 | (u32)(resp1<<16);
	sdmmc_cid[1] = resp2 | (u32)(resp3<<16);
	sdmmc_cid[2] = resp4 | (u32)(resp5<<16);
	sdmmc_cid[3] = resp6 | (u32)(resp7<<16);

	// CMD3
	sdmmc_send_command(3, 0, 0);
	
	resp0 = sdmmc_read16(REG_SDRESP0);
	resp1 = sdmmc_read16(REG_SDRESP1);
	
	sdaddr = resp1;
	
	// CMD9 - get CSD
	sdmmc_send_command(9, 0, sdaddr);
	
	resp0 = sdmmc_read16(REG_SDRESP0);
	resp1 = sdmmc_read16(REG_SDRESP1);
	resp2 = sdmmc_read16(REG_SDRESP2);
	resp3 = sdmmc_read16(REG_SDRESP3);
	resp4 = sdmmc_read16(REG_SDRESP4);
	resp5 = sdmmc_read16(REG_SDRESP5);
	resp6 = sdmmc_read16(REG_SDRESP6);
	resp7 = sdmmc_read16(REG_SDRESP7);
	
	sdmmc_write16(REG_SDCLKCTL, 0x100);	
	
	// CMD7
	sdmmc_send_command(7, 0, sdaddr);
	
	resp0 = sdmmc_read16(REG_SDRESP0);
	resp1 = sdmmc_read16(REG_SDRESP1);
	
	// CMD55
	sdmmc_send_command(55, 0, sdaddr);
	
	// ACMD6
	sdmmc_send_command(6, 2, 0);
	
	resp0 = sdmmc_read16(REG_SDRESP0);
	resp1 = sdmmc_read16(REG_SDRESP1);

	sdmmc_send_command(13, 0, sdaddr);
	
	resp0 = sdmmc_read16(REG_SDRESP0);
	resp1 = sdmmc_read16(REG_SDRESP1);

	sdmmc_send_command(16, 0x200, 0x0);
	
	resp0 = sdmmc_read16(REG_SDRESP0);
	resp1 = sdmmc_read16(REG_SDRESP1);	
	
	sdmmc_write16(REG_SDCLKCTL, sdmmc_read16(REG_SDCLKCTL));
	sdmmc_write16(REG_SDBLKLEN, 0x200);

	sdmmc_mask16(REG_SDCLKCTL, 0x100, 0);

	sdmmc_cardready = 1;
	leaveCriticalSection(oldIME);

	return 0;
}
Beispiel #26
0
//---------------------------------------------------------------------------------
void irqEnableAUX(uint32 irq) {
//---------------------------------------------------------------------------------
    int oldIME = enterCriticalSection();
    REG_AUXIE |= irq;
    leaveCriticalSection(oldIME);
}
/* Callback for JVMTI_EVENT_VM_DEATH */
static void JNICALL
cbVMDeath(jvmtiEnv *jvmti, JNIEnv *env)
{
    jvmtiHeapCallbacks heapCallbacks;
    jvmtiError         error;

    /* These are purposely done outside the critical section */

    /* Force garbage collection now so we get our ObjectFree calls */
    error = (*jvmti)->ForceGarbageCollection(jvmti);
    check_jvmti_error(jvmti, error, "Cannot force garbage collection");
    
    /* Iterate through heap and find all objects */
    (void)memset(&heapCallbacks, 0, sizeof(heapCallbacks));
    heapCallbacks.heap_iteration_callback = &cbObjectSpaceCounter;
    error = (*jvmti)->IterateThroughHeap(jvmti, 0, NULL, &heapCallbacks, NULL);
    check_jvmti_error(jvmti, error, "Cannot iterate through heap");

    /* Process VM Death */
    enterCriticalSection(jvmti); {
        jclass              klass;
        jfieldID            field;
        jvmtiEventCallbacks callbacks;

        /* Disengage calls in HEAP_TRACKER_class. */
        klass = (*env)->FindClass(env, STRING(HEAP_TRACKER_class));
        if ( klass == NULL ) {
            fatal_error("ERROR: JNI: Cannot find %s with FindClass\n", 
                        STRING(HEAP_TRACKER_class));
        }
        field = (*env)->GetStaticFieldID(env, klass, STRING(HEAP_TRACKER_engaged), "I");
        if ( field == NULL ) {
            fatal_error("ERROR: JNI: Cannot get field from %s\n", 
                        STRING(HEAP_TRACKER_class));
        }
        (*env)->SetStaticIntField(env, klass, field, 0);

        /* The critical section here is important to hold back the VM death
         *    until all other callbacks have completed.
         */

        /* Clear out all callbacks. */
        (void)memset(&callbacks,0, sizeof(callbacks));
        error = (*jvmti)->SetEventCallbacks(jvmti, &callbacks, 
                                            (jint)sizeof(callbacks));
        check_jvmti_error(jvmti, error, "Cannot set jvmti callbacks");
        
        /* Since this critical section could be holding up other threads
         *   in other event callbacks, we need to indicate that the VM is
         *   dead so that the other callbacks can short circuit their work.
         *   We don't expect an further events after VmDeath but we do need
         *   to be careful that existing threads might be in our own agent
         *   callback code.
         */
        gdata->vmDead = JNI_TRUE;

        /* Dump all objects */
        if ( gdata->traceInfoCount > 0 ) {
            TraceInfo **list;
            int         count;
            int         i;
           
            stdout_message("Dumping heap trace information\n");

            /* Create single array of pointers to TraceInfo's, sort, and
             *   print top gdata->maxDump top space users.
             */
            list = (TraceInfo**)calloc(gdata->traceInfoCount, 
                                              sizeof(TraceInfo*));
            if ( list == NULL ) {
                fatal_error("ERROR: Ran out of malloc() space\n");
            }
            count = 0;
            for ( i = 0 ; i < HASH_BUCKET_COUNT ; i++ ) {
                TraceInfo *tinfo;

                tinfo = gdata->hashBuckets[i];
                while ( tinfo != NULL ) {
                    if ( count < gdata->traceInfoCount ) {
                        list[count++] = tinfo;
                    }
                    tinfo = tinfo->next;
                }
            }
            if ( count != gdata->traceInfoCount ) {
                fatal_error("ERROR: Count found by iterate doesn't match ours:"
                        " count=%d != traceInfoCount==%d\n",
                        count, gdata->traceInfoCount);
            }
            qsort(list, count, sizeof(TraceInfo*), &compareInfo);
            for ( i = 0 ; i < count ; i++ ) {
                if ( i >= gdata->maxDump ) {
                    break;
                }
                printTraceInfo(jvmti, i+1, list[i]);
            }
            (void)free(list);
        }

    } exitCriticalSection(jvmti);
        
}  
Beispiel #28
0
//---------------------------------------------------------------------------------
void irqSetAUX(u32 mask, IntFn handler) {
//---------------------------------------------------------------------------------
    int oldIME = enterCriticalSection();
    __irqSet(mask,handler,irqTableAUX);
    leaveCriticalSection(oldIME);
}
/* Callback for JVMTI_EVENT_CLASS_FILE_LOAD_HOOK */
static void JNICALL
cbClassFileLoadHook(jvmtiEnv *jvmti, JNIEnv* env,
                jclass class_being_redefined, jobject loader,
                const char* name, jobject protection_domain,
                jint class_data_len, const unsigned char* class_data,
                jint* new_class_data_len, unsigned char** new_class_data)
{
    enterCriticalSection(jvmti); {
        /* It's possible we get here right after VmDeath event, be careful */
        if ( !gdata->vmDead ) {

            const char * classname;

            /* Name can be NULL, make sure we avoid SEGV's */
            if ( name == NULL ) {
                classname = java_crw_demo_classname(class_data, class_data_len,
                                NULL);
                if ( classname == NULL ) {
                    fatal_error("ERROR: No classname in classfile\n");
                }
            } else {
                classname = strdup(name);
                if ( classname == NULL ) {
                    fatal_error("ERROR: Ran out of malloc() space\n");
                }
            }

            *new_class_data_len = 0;
            *new_class_data     = NULL;

            /* The tracker class itself? */
            if ( strcmp(classname, STRING(HEAP_TRACKER_class)) != 0 ) {
                jint           cnum;
                int            systemClass;
                unsigned char *newImage;
                long           newLength;

                /* Get number for every class file image loaded */
                cnum = gdata->ccount++;

                /* Is it a system class? If the class load is before VmStart
                 *   then we will consider it a system class that should
                 *   be treated carefully. (See java_crw_demo)
                 */
                systemClass = 0;
                if ( !gdata->vmStarted ) {
                    systemClass = 1;
                }

                newImage = NULL;
                newLength = 0;

                /* Call the class file reader/write demo code */
                java_crw_demo(cnum,
                    classname,
                    class_data,
                    class_data_len,
                    systemClass,
                    STRING(HEAP_TRACKER_class),
                    "L" STRING(HEAP_TRACKER_class) ";",
                    NULL, NULL,
                    NULL, NULL,
                    STRING(HEAP_TRACKER_newobj), "(Ljava/lang/Object;)V",
                    STRING(HEAP_TRACKER_newarr), "(Ljava/lang/Object;)V",
                    &newImage,
                    &newLength,
                    NULL,
                    NULL);

                /* If we got back a new class image, return it back as "the"
                 *   new class image. This must be JVMTI Allocate space.
                 */
                if ( newLength > 0 ) {
                    unsigned char *jvmti_space;

                    jvmti_space = (unsigned char *)allocate(jvmti, (jint)newLength);
                    (void)memcpy((void*)jvmti_space, (void*)newImage, (int)newLength);
                    *new_class_data_len = (jint)newLength;
                    *new_class_data     = jvmti_space; /* VM will deallocate */
                }

                /* Always free up the space we get from java_crw_demo() */
                if ( newImage != NULL ) {
                    (void)free((void*)newImage); /* Free malloc() space with free() */
                }
            }
        
            (void)free((void*)classname);
        }
    } exitCriticalSection(jvmti);
}
//------------------------------------------------------------------------------
tOplkError timeru_setTimer(tTimerHdl* pTimerHdl_p, ULONG timeInMs_p, tTimerArg argument_p)
{
    tTimerEntry*    pNewEntry;
    tTimerEntry**   ppEntry;

    // check pointer to handle
    if (pTimerHdl_p == NULL)
        return kErrorTimerInvalidHandle;

    // fetch entry from free timer list
    enterCriticalSection(TIMERU_FREE_LIST);
    pNewEntry = timeruInstance_l.pFreeListFirst;
    if (pNewEntry != NULL)
    {
        timeruInstance_l.pFreeListFirst = pNewEntry->pNext;
        timeruInstance_l.freeEntries--;
        if (timeruInstance_l.minFreeEntries > timeruInstance_l.freeEntries)
        {
            timeruInstance_l.minFreeEntries = timeruInstance_l.freeEntries;
        }
    }
    leaveCriticalSection(TIMERU_FREE_LIST);

    if (pNewEntry == NULL)
    {   // sorry, no free entry
        return kErrorTimerNoTimerCreated;
    }

    *pTimerHdl_p = (tTimerHdl)pNewEntry;
    OPLK_MEMCPY(&pNewEntry->timerArg, &argument_p, sizeof(tTimerArg));

    // insert timer entry in timer list
    enterCriticalSection(TIMERU_TIMER_LIST);
    // calculate timeout based on start time
    pNewEntry->timeoutInMs = (getTickCount() - timeruInstance_l.startTimeInMs) + timeInMs_p;

    ppEntry = &timeruInstance_l.pTimerListFirst;
    while (*ppEntry != NULL)
    {
        if ((*ppEntry)->timeoutInMs > pNewEntry->timeoutInMs)
        {
            (*ppEntry)->timeoutInMs -= pNewEntry->timeoutInMs;
            break;
        }
        pNewEntry->timeoutInMs -= (*ppEntry)->timeoutInMs;
        ppEntry = &(*ppEntry)->pNext;
    }
    // insert before **ppEntry
    pNewEntry->pNext = *ppEntry;
    *ppEntry = pNewEntry;
    leaveCriticalSection(TIMERU_TIMER_LIST);

#if (TARGET_SYSTEM == _WIN32_ || TARGET_SYSTEM == _WINCE_ )
    if (ppEntry == &timeruInstance_l.pTimerListFirst)
    {
        SetEvent(timeruInstance_l.ahEvents[TIMERU_EVENT_WAKEUP]);
    }
#endif

    return kErrorOk;
}