Пример #1
0
VOID TaskMgrSS::CompleteTaskSet( TASKSETHANDLE hSet )
{
    TaskSet*             pSet = &mSets[ hSet ];

    UINT uCount = _InterlockedDecrement( (LONG*)&pSet->muCompletionCount );

    if( 0 == uCount )
    {
        pSet->mbCompleted = TRUE;
        pSet->mpFunc = 0;
        //
        //  The task set has completed.  We need to look at the successors
        //  and signal them that this dependency of theirs has completed.
        //
        pSet->mSuccessorsLock.aquire();

        for( UINT uSuccessor = 0; uSuccessor < MAX_SUCCESSORS; ++uSuccessor )
        {
            TaskSet* pSuccessor = pSet->Successors[ uSuccessor ];

            //
            //  A signaled successor must be removed from the Successors list 
            //  before the mSuccessorsLock can be released.
            //
            pSet->Successors[ uSuccessor ] = NULL;
            
            if( NULL != pSuccessor ) 
            {
                UINT uStart;

                uStart = _InterlockedDecrement( (LONG*)&pSuccessor->muStartCount );

                //
                //  If the start count is 0 the successor has had all its 
                //  dependencies satisified and can be scheduled.
                //
                if( 0 == uStart )
                {
                    mTaskScheduler.AddTaskSet( pSuccessor->mhTaskset, pSuccessor->muSize );
                }
            }
        }

        pSet->mSuccessorsLock.release();

        ReleaseHandle( hSet );
    }
}
Пример #2
0
static VOID EtpDereferenceWsWatchContext(
    _Inout_ PWS_WATCH_CONTEXT Context
    )
{
    if (_InterlockedDecrement(&Context->RefCount) == 0)
    {
        PSINGLE_LIST_ENTRY listEntry;

        if (Context->SymbolProvider)
            PhDereferenceObject(Context->SymbolProvider);

        // Free all unused results.

        PhAcquireQueuedLockExclusive(&Context->ResultListLock);

        listEntry = Context->ResultListHead.Next;

        while (listEntry)
        {
            PSYMBOL_LOOKUP_RESULT result;

            result = CONTAINING_RECORD(listEntry, SYMBOL_LOOKUP_RESULT, ListEntry);
            listEntry = listEntry->Next;
            PhDereferenceObject(result->Symbol);
            PhFree(result);
        }

        PhReleaseQueuedLockExclusive(&Context->ResultListLock);

        PhFree(Context);
    }
}
Пример #3
0
LONG
FASTCALL
VideoPortInterlockedDecrement(
    IN PLONG Addend)
{
    return _InterlockedDecrement(Addend);
}
Пример #4
0
int pcap_io_recv(void* packet, int max_len)
{
	if (PacketCount==0)
		return 0;

	u32 len=*(u32*)&PacketBuffer[ReadCursor];
	if ((u32)max_len<len)
		__debugbreak;
	
	memcpy(packet,(void*)&PacketBuffer[ReadCursor+4],len);

	//Make sure ReadCursor allways has a valid value :)
	//not even sure that much is needed tbh, bored to think :P

	u32 RCpos=ReadCursor;

	RCpos+=len+4;
	if (RCpos>=PacketBufferSize)
		RCpos=0;
	ReadCursor=RCpos;

	//This however, needs to be interlocked
	_InterlockedDecrement(&PacketCount);
	//EnterCriticalSection(&cs);
	//PacketCount--;
	//ExitCriticalSection(&cs);
	return len;
}
Пример #5
0
DWORD FileProcessor::Run(LPVOID /*arg*/)
{
	if( PP ){
	 FileEntry entry;
		nProcessed = 0;
		while( !PP->quitRequested() && (isBackwards ? PP->getBack(entry) : PP->getFront(entry)) ){
		 // create a scoped lock without closing it immediately
		 CRITSECTLOCK::Scope scp(PP->ioLock, 0);
			scope = &scp;
			currentEntry = &entry;
			_InterlockedIncrement(&PP->nProcessing);
			entry.compress( this, PP );
			_InterlockedDecrement(&PP->nProcessing);
			_InterlockedIncrement(&PP->nProcessed);
			currentEntry = NULL;
			nProcessed += 1;
			scope = NULL;

			runningTotalRaw += entry.fileInfo.st_size;
			runningTotalCompressed += (entry.compressedSize > 0)? entry.compressedSize : entry.fileInfo.st_size;
			/*if( PP->verbose() > 1 )*/{
#if defined(__MACH__)
                mach_port_t thread = mach_thread_self();
				mach_msg_type_number_t count = THREAD_BASIC_INFO_COUNT;
				thread_basic_info_data_t info;
				int kr = thread_info(thread, THREAD_BASIC_INFO, (thread_info_t) &info, &count);
				if( kr == KERN_SUCCESS ){
					 userTime = info.user_time.seconds + info.user_time.microseconds * 1e-6;
					 systemTime = info.system_time.seconds + info.system_time.microseconds * 1e-6;
					 avCPUUsage += info.cpu_usage * 100.0 / TH_USAGE_SCALE;
					 threadInfo = info;
					 hasInfo = true;
				}
				mach_port_deallocate(mach_task_self(), thread);
#elif defined(linux)
				struct rusage rtu;
				if (!getrusage(RUSAGE_THREAD, &rtu)) {
					const auto ut = rtu.ru_utime.tv_sec + rtu.ru_utime.tv_usec * 1e-6;
					const auto st = rtu.ru_stime.tv_sec + rtu.ru_stime.tv_usec * 1e-6;
					if (ut >= 0 && st >= 0) {
						userTime = ut, systemTime = st, hasInfo = true;
					}
				}
#	ifdef CLOCK_THREAD_CPUTIME_ID
				struct timespec ts;
				if (clock_gettime(CLOCK_THREAD_CPUTIME_ID, &ts) != -1) {
					cpuTime = ts.tv_sec + ts.tv_nsec * 1e-9;
					double t = userTime + systemTime;
					if (cpuTime > 0) {
						avCPUUsage += t * 100.0 / cpuTime;
					}
				}
#	endif
#endif
			}
		}
	}
	return DWORD(nProcessed);
}
Пример #6
0
NTKERNELAPI
LONG
FASTCALL
InterlockedDecrement(
    IN OUT LONG volatile *Addend)
{
    return _InterlockedDecrement(Addend);
}
Пример #7
0
long atomic_decrement(volatile long* value)
{
#ifdef __GNUC__
	return __sync_sub_and_fetch(value, 1);	
#else
	return _InterlockedDecrement(value);
#endif
}
ULONG 	CSignalGeneratorDlg::Release()
{
	ULONG newRefValue = _InterlockedDecrement((volatile long*)&m_refCount);

	if (newRefValue == 0)
		delete this;
	return newRefValue;
}
Пример #9
0
LONG
WINAPI
redirect_InterlockedDecrement(
    __inout __drv_interlocked LONG volatile *Addend
    )
{
    return _InterlockedDecrement(Addend);
}
Пример #10
0
/**
  Performs an atomic decrement of an 32-bit unsigned integer.

  Performs an atomic decrement of the 32-bit unsigned integer specified by
  Value and returns the decrement value. The decrement operation must be
  performed using MP safe mechanisms. The state of the return value is not
  guaranteed to be MP safe.

  @param  Value A pointer to the 32-bit value to decrement.

  @return The decrement value.

**/
UINT32
EFIAPI
InternalSyncDecrement (
  IN      volatile UINT32           *Value
  )
{
  return _InterlockedDecrement ((long *)(UINTN)(Value));
}
Пример #11
0
NTSTATUS PhpThreadQueryWorker(
    __in PVOID Parameter
    )
{
    PPH_THREAD_QUERY_DATA data = (PPH_THREAD_QUERY_DATA)Parameter;
    LONG newSymbolsLoading;

    newSymbolsLoading = _InterlockedIncrement(&data->ThreadProvider->SymbolsLoading);

    if (newSymbolsLoading == 1)
        PhInvokeCallback(&data->ThreadProvider->LoadingStateChangedEvent, (PVOID)TRUE);

    // We can't resolve the start address until symbols have
    // been loaded.
    PhWaitForEvent(&data->ThreadProvider->SymbolsLoadedEvent, NULL);

    data->StartAddressString = PhGetSymbolFromAddress(
        data->ThreadProvider->SymbolProvider,
        data->ThreadItem->StartAddress,
        &data->StartAddressResolveLevel,
        &data->ThreadItem->StartAddressFileName,
        NULL,
        NULL
        );

    newSymbolsLoading = _InterlockedDecrement(&data->ThreadProvider->SymbolsLoading);

    if (newSymbolsLoading == 0)
        PhInvokeCallback(&data->ThreadProvider->LoadingStateChangedEvent, (PVOID)FALSE);

    // Get the service tag, and the service name.
    if (
        WINDOWS_HAS_SERVICE_TAGS &&
        data->ThreadProvider->SymbolProvider->IsRealHandle &&
        data->ThreadItem->ThreadHandle
        )
    {
        PVOID serviceTag;

        if (NT_SUCCESS(PhGetThreadServiceTag(
            data->ThreadItem->ThreadHandle,
            data->ThreadProvider->ProcessHandle,
            &serviceTag
            )))
        {
            data->ServiceName = PhGetServiceNameFromTag(
                data->ThreadProvider->ProcessId,
                serviceTag
                );
        }
    }

    RtlInterlockedPushEntrySList(&data->ThreadProvider->QueryListHead, &data->ListEntry);

    PhDereferenceObject(data->ThreadProvider);

    return STATUS_SUCCESS;
}
Пример #12
0
ULONG VMR9CustomPresenter::Release()
{
    ULONG ret = _InterlockedDecrement(&m_RefCount);
    if (ret == 0)
    {
        delete this;
    }
    return ret;
}
ULONG CMPEG1Stream::Release()
{
    LONG cRef = _InterlockedDecrement(&m_cRef);
    if (cRef == 0)
    {
        delete this;
    }
    return cRef;
}
Пример #14
0
void CallSetImmediate::call() {
	csIsolate->protectedScope([this](){
		v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HandleScope scope(isolate);
		auto cb = v8::Local<v8::Function>::New(isolate, pcb);
		pcb.Dispose();
		delete this;
		cb->Call(v8::Context::GetCurrent()->Global(), 0, nullptr);
		_InterlockedDecrement(&outStandingCallbacks);
	});
}
Пример #15
0
VOID EtProcIconDereferenceProcessIcon(
    __inout PET_PROCESS_ICON ProcessIcon
    )
{
    if (_InterlockedDecrement(&ProcessIcon->RefCount) == 0)
    {
        DestroyIcon(ProcessIcon->Icon);
        PhFree(ProcessIcon);
    }
}
Пример #16
0
int atomic_decrement(volatile int *value)
{
    assert(value);
    assert((int)value % 4 == 0); // Only 32 bit aligned values work.
#if LOOM_COMPILER == LOOM_COMPILER_MSVC
    return _InterlockedDecrement(value);

#else
    return __sync_sub_and_fetch(value, 1);
#endif
}
Пример #17
0
INTERLOCKED_RESULT
FASTCALL
Exfi386InterlockedDecrementLong(
    IN OUT PLONG Addend)
{
    LONG Result;

    Result = _InterlockedDecrement(Addend);
    return (Result < 0) ? ResultNegative :
           (Result > 0) ? ResultPositive :
           ResultZero;
}
Пример #18
0
    ~Thread() {
#ifndef TARGET_WINNT
        __sync_sub_and_fetch(m_addr_coipipe_counter, 1);
#else // TARGET_WINNT
        _InterlockedDecrement(m_addr_coipipe_counter);
#endif // TARGET_WINNT
        for (int i = 0; i < mic_engines_total; i++) {
            if (m_pipelines[i] != 0) {
                COI::PipelineDestroy(m_pipelines[i]);
            }
        }
    }
Пример #19
0
INTERLOCKED_RESULT
NTAPI
ExInterlockedDecrementLong(
  IN PLONG Addend,
  IN PKSPIN_LOCK Lock)
{
    LONG Result;

    Result = _InterlockedDecrement(Addend);
    return (Result < 0) ? ResultNegative :
           (Result > 0) ? ResultPositive :
           ResultZero;
}
Пример #20
0
    void
    shared_count::release_shared()
    {
#ifdef _MSC_VER
        if (_InterlockedDecrement(&shared_owners_) == -1)
#else
        if (--shared_owners_ == -1)
#endif
        {
            on_zero_shared();
            delete this;
        }
    }
Пример #21
0
void WorkQueue::SetWorkStatusComplete()
{
    _InterlockedDecrement(&m_incompleteWork);

    // FIXME: No need to acquire the lock while wake up the condition variable ?
    // If the workqueue is waiting on the condition variable.. wake him up
    if (0 != _InterlockedExchangeAdd(&m_waitingForCompletion, 0) && 0 == _InterlockedExchangeAdd(&m_incompleteWork, 0))
    {
        SetEvent(m_condCrit);
    }

    return;
}
Пример #22
0
VOID CALLBACK Interpreter::SamplerProc(PVOID , BOOLEAN TimerOrWaitFired)
{
	if (!TimerOrWaitFired)
		return;
	if (_InterlockedDecrement(&m_nInputPollCounter) == 0)
	{
		NotifyAsyncPending();
#if 0//def _DEBUG
		DWORD dwTicksNow = timeGetTime();
		Semaphore* sem = Pointers.InputSemaphore->m_location;
		TRACE("Fired after %d, last reset at %d, signals %d\n\r", dwTicksNow-dwTicksReset, dwTicksReset, ObjectMemoryIntegerValueOf(sem->m_excessSignals));
#endif
	}
}
Пример #23
0
void TaskMgrSS::TaskSet::Execute(INT iContextId)
{
    int uIdx = _InterlockedDecrement(&muTaskId);
    if(uIdx >= 0)
    {
        //gTaskMgrSS.mTaskScheduler.DecrementTaskCount();

        ProfileBeginTask( mszSetName );

        mpFunc( mpvArg, iContextId, uIdx, muSize );

        ProfileEndTask();

        //gTaskMgr.CompleteTaskSet( mhTaskset );
        UINT uCount = _InterlockedDecrement( (LONG*)&muCompletionCount );

        if( 0 == uCount )
        {
            mbCompleted = TRUE;
            mpFunc = 0;
            CompleteTaskSet();
        }
    }
}
Пример #24
0
DWORD WINAPI ttapiThreadProc( LPVOID lpParameter )
{
	LPTTAPI_WORKER_PARAMS pParams = ( LPTTAPI_WORKER_PARAMS ) lpParameter;
	DWORD i , dwFastIter = ttapi_dwFastIter , dwSlowIter = ttapi_dwSlowIter;

	while( TRUE ) {		
		// Wait

		// Fast
		for ( i = 0 ; i < dwFastIter ; ++i ) {
			if ( pParams->vlFlag == 0 ) {
				// Msg( "0x%8.8X Fast %u" , dwId , i );
				goto process;
			}
			__asm pause;
		}

		// Moderate
		for ( i = 0 ; i < dwSlowIter ; ++i ) {
			if ( pParams->vlFlag == 0 ) {
				// Msg( "0x%8.8X Moderate %u" , dwId , i );
				goto process;
			}
			SwitchToThread();
		}

		// Slow
		while ( pParams->vlFlag ) {
			Sleep( 100 );
			//Msg( "Shit" );
		}

		process:

		pParams->vlFlag = 1;

		if ( pParams->lpWorkerFunc )
			pParams->lpWorkerFunc( pParams->lpvWorkerFuncParams );
		else
			break;

		_InterlockedDecrement( &ttapi_queue_size.size );

	} // while

	return 0;
}
Пример #25
0
/**
 * Dereferences the specified object.
 * The object will be freed if its reference count reaches 0.
 *
 * \param Object A pointer to the object to dereference.
 *
 * \return TRUE if the object was freed, otherwise FALSE.
 */
VOID PhDereferenceObject(
    __in PVOID Object
    )
{
    PPH_OBJECT_HEADER objectHeader;
    LONG newRefCount;

    objectHeader = PhObjectToObjectHeader(Object);
    /* Decrement the reference count. */
    newRefCount = _InterlockedDecrement(&objectHeader->RefCount);
    ASSUME_ASSERT(newRefCount >= 0);

    /* Free the object if it has 0 references. */
    if (newRefCount == 0)
    {
        PhpFreeObject(objectHeader);
    }
}
// Cleans up all resources used by a single PTD; does not free the PTD structure
// itself.
static void __cdecl destroy_ptd(__acrt_ptd* const ptd) throw()
{
    if (ptd->_pxcptacttab != __acrt_exception_action_table)
    {
        _free_crt(ptd->_pxcptacttab);
    }

    _free_crt(ptd->_cvtbuf);
    _free_crt(ptd->_asctime_buffer);
    _free_crt(ptd->_wasctime_buffer);
    _free_crt(ptd->_gmtime_buffer);
    _free_crt(ptd->_tmpnam_narrow_buffer);
    _free_crt(ptd->_tmpnam_wide_buffer);
    _free_crt(ptd->_strerror_buffer);
    _free_crt(ptd->_wcserror_buffer);
    _free_crt(ptd->_beginthread_context);

    __acrt_lock_and_call(__acrt_multibyte_cp_lock, [&]
    {
        __crt_multibyte_data* const multibyte_data = ptd->_multibyte_info;
        if (!multibyte_data)
        {
            return;
        }

        if (_InterlockedDecrement(&multibyte_data->refcount) != 0)
        {
            return;
        }

        if (multibyte_data == &__acrt_initial_multibyte_data)
        {
            return;
        }

        _free_crt(multibyte_data);
    });

    __acrt_lock_and_call(__acrt_locale_lock, [&]
    {
        replace_current_thread_locale_nolock(ptd, nullptr);
    });
}
Пример #27
0
/*
 * @implemented
 */
VOID
NTAPI
HalCalibratePerformanceCounter(IN volatile PLONG Count,
                               IN ULONGLONG NewCount)
{
    ULONG Flags = 0;

    /* Disable interrupts */
    Flags = __readmsr();
    _disable();

    /* Do a decrement for this CPU */
    _InterlockedDecrement(Count);

    /* Wait for other CPUs */
    while (*Count);

    /* Restore interrupts if they were previously enabled */
    __writemsr(Flags);
}
Пример #28
0
/**
 * Calls the delete procedure for an object and frees its
 * allocated storage.
 *
 * \param ObjectHeader A pointer to the object header of an allocated object.
 */
VOID PhpFreeObject(
    __in PPH_OBJECT_HEADER ObjectHeader
    )
{
    /* Object type statistics. */
    _InterlockedDecrement(&ObjectHeader->Type->NumberOfObjects);

#ifdef DEBUG
    PhAcquireQueuedLockExclusive(&PhDbgObjectListLock);
    RemoveEntryList(&ObjectHeader->ObjectListEntry);
    PhReleaseQueuedLockExclusive(&PhDbgObjectListLock);
#endif

    REF_STAT_UP(RefObjectsDestroyed);

    /* Call the delete procedure if we have one. */
    if (ObjectHeader->Type->DeleteProcedure)
    {
        ObjectHeader->Type->DeleteProcedure(
            PhObjectHeaderToObject(ObjectHeader),
            0
            );
    }

    if (ObjectHeader->Flags & PHOBJ_FROM_TYPE_FREE_LIST)
    {
        PhFreeToFreeList(&ObjectHeader->Type->FreeList, ObjectHeader);
        REF_STAT_UP(RefObjectsFreedToTypeFreeList);
    }
    else if (ObjectHeader->Flags & PHOBJ_FROM_SMALL_FREE_LIST)
    {
        PhFreeToFreeList(&PhObjectSmallFreeList, ObjectHeader);
        REF_STAT_UP(RefObjectsFreedToSmallFreeList);
    }
    else
    {
        PhFree(ObjectHeader);
        REF_STAT_UP(RefObjectsFreed);
    }
}
Пример #29
0
void TaskMgrSS::TaskSet::CompleteTaskSet()
{
    //
    //  The task set has completed.  We need to look at the successors
    //  and signal them that this dependency of theirs has completed.
    //

    mSuccessorsLock.aquire();

    for( UINT uSuccessor = 0; uSuccessor < MAX_SUCCESSORS; ++uSuccessor )
    {
        TaskSet* pSuccessor = Successors[ uSuccessor ];

        //
        //  A signaled successor must be removed from the Successors list 
        //  before the mSuccessorsLock can be released.
        //
        Successors[ uSuccessor ] = NULL;
            
        if( NULL != pSuccessor ) 
        {
            UINT uStart;

            uStart = _InterlockedDecrement( (LONG*)&pSuccessor->muStartCount );

            //
            //  If the start count is 0 the successor has had all its 
            //  dependencies satisified and can be scheduled.
            //
            if( 0 == uStart )
            {
                gTaskMgrSS.mTaskScheduler.AddTaskSet( pSuccessor->mhTaskset, pSuccessor->muSize );
            }
        }
    }

    mSuccessorsLock.release();

    gTaskMgrSS.ReleaseHandle( mhTaskset );
}
Пример #30
0
// This will basically wait for the work to be completed
HRESULT WorkQueue::WaitForWorkCompletion(int milliSec)
{
    HRESULT ret = S_OK;

    m_mutexCri.enter();
    _InterlockedIncrement(&m_waitingForCompletion);

    if (IsWorkPending())
    {
        // Release the lock acquired the caller..
        m_mutexCri.leave();

        DWORD dwMilliseconds = (0 != milliSec) ? static_cast<DWORD>(milliSec) : INFINITE;
        // Now wait for either event to become signaled
        DWORD result = WaitForSingleObject(m_condCrit, dwMilliseconds);

        // now acquire the mutex
        m_mutexCri.enter();

        if (WAIT_OBJECT_0 == result)
        {
            ret = S_OK;
        }
        else if (WAIT_TIMEOUT == result)
        {
            ret = E_TIMEOUT;
        }
        else
        {
            ret = E_FAIL;
        }
    }

    // TODO: Thread Cancellation to be handled here
    _InterlockedDecrement(&m_waitingForCompletion);
    m_mutexCri.leave();

    return ret;
}