/// <summary>
/// processes incoming image
/// </summary>
/// <returns>error code, refer to AL_XXX codes</returns>
/// <remarks>
/// working parallel code with single loop, using active waits to protect data dependencies
/// [Filter processing of full resolution image] in [1.131 seconds]
/// </remarks>
int CParallelActiveWaitAltaLuxFilter::Run()
{
    if (ClipLimit == 1.0)
        return AL_OK;	  //< is OK, immediately returns original image

    PixelType *pImage = (PixelType *)ImageBuffer;

    /// pulMapArray is pointer to mappings
    unsigned int *pulMapArray = new unsigned int[NumHorRegions * NumVertRegions * NUM_GRAY_LEVELS];
    if (pulMapArray == 0)
        return AL_OUT_OF_MEMORY;	  //< not enough memory

    /// region pixel count
    unsigned int NumPixels = (unsigned int)RegionWidth * (unsigned int)RegionHeight;	//< region pixel count

    unsigned int ulClipLimit;		//< clip limit
    if (ClipLimit > 0.0)
    {
        /// calculate actual cliplimit
        ulClipLimit = (unsigned int) (ClipLimit * (RegionWidth * RegionHeight) / NUM_GRAY_LEVELS);
        ulClipLimit = (ulClipLimit < 1UL) ? 1UL : ulClipLimit;
    }
    else
        ulClipLimit = 1UL<<14;		  //< large value, do not clip (AHE)

    /// Interpolate greylevel mappings to get CLAHE image
    // create events for signaling that the first phase is completed
    __declspec(align(32)) volatile LONG FirstPhaseCompleted[MAX_VERT_REGIONS+1];
    for (int i = 0; i <= NumVertRegions; i++)
        InterlockedExchange((volatile LONG*)&FirstPhaseCompleted[i], -1);

    concurrency::parallel_for((LONG)0, (LONG)(NumVertRegions + 1), [&](LONG uiY)
    {
        // first half
        PixelType* pImPointer = pImage;
        if (uiY > 0)
            pImPointer += ((RegionHeight >> 1) + ((uiY - 1) * RegionHeight)) * OriginalImageWidth;

        if (uiY < NumVertRegions)
        {
            /// calculate greylevel mappings for each contextual region
            for (LONG uiX = 0; uiX < NumHorRegions; uiX++, pImPointer += RegionWidth)
            {
                unsigned int *pHistogram = &pulMapArray[NUM_GRAY_LEVELS * (uiY * NumHorRegions + uiX)];
                MakeHistogram(pImPointer, pHistogram);
                ClipHistogram(pHistogram, ulClipLimit);
                MapHistogram(pHistogram, NumPixels);
                InterlockedExchange((volatile LONG*) &FirstPhaseCompleted[uiY], uiX);
            }
        }

        // second half
        unsigned int uiSubX, uiSubY;	//< size of subimages
        unsigned int uiXL, uiXR, uiYU, uiYB;	//< auxiliary variables interpolation routine

        pImPointer = pImage;
        if (uiY > 0)
            pImPointer += ((RegionHeight >> 1) + ((uiY - 1) * RegionHeight)) * OriginalImageWidth;

        if (uiY == 0)
        {
            /// special case: top row
            uiSubY = RegionHeight >> 1;
            uiYU = 0;
            uiYB = 0;
        } else {
Пример #2
0
VOID
DCamSurpriseRemoval(
    IN PHW_STREAM_REQUEST_BLOCK pSrb
    )

/*++

Routine Description:

    Response to SRB_SURPRISE_REMOVAL.

Arguments:

    pSrb - Pointer to the stream request block


Return Value:

    None.

--*/

{

    PIRP pIrp;
    PIRB pIrb;
    PDCAM_EXTENSION pDevExt;
    PSTREAMEX pStrmEx;
    NTSTATUS Status;

    PAGED_CODE();

    pIrb = (PIRB) pSrb->SRBExtension;
    ASSERT(pIrb);
    pDevExt = (PDCAM_EXTENSION) pSrb->HwDeviceExtension;
    ASSERT(pDevExt);


    //
    // Set this to stop accepting incoming read.
    //

    pDevExt->bDevRemoved = TRUE;


    //
    // Wait until all pending work items are completed!
    //

    KeWaitForSingleObject( &pDevExt->PendingWorkItemEvent, Executive, KernelMode, FALSE, NULL );


    //
    // Wait for currect read to be attached so we cancel them all.
    //

    pStrmEx = pDevExt->pStrmEx;
    if(pStrmEx) {
        // Make sure that this structure is still valid.
        if(pStrmEx->pVideoInfoHeader) {
            KeWaitForSingleObject( &pStrmEx->hMutex, Executive, KernelMode, FALSE, 0 );
            KeReleaseMutex(&pStrmEx->hMutex, FALSE);
        }
    }

    pIrp = IoAllocateIrp(pDevExt->BusDeviceObject->StackSize, FALSE);
    if(!pIrp) {
        ERROR_LOG(("DCamSurpriseRemovalPacket: faile to get resource; pIrb=%p, pDevExt=%p, pIrp\n", pIrb, pDevExt));
        pSrb->Status = STATUS_INSUFFICIENT_RESOURCES;
        StreamClassDeviceNotification(DeviceRequestComplete, pSrb->HwDeviceExtension, pSrb);
        return;
    }


    //
    // un-register a bus reset callback notification
    //

    pIrb->FunctionNumber = REQUEST_BUS_RESET_NOTIFICATION;
    pIrb->Flags = 0;
    pIrb->u.BusResetNotification.fulFlags = DEREGISTER_NOTIFICATION_ROUTINE;
    pIrb->u.BusResetNotification.ResetRoutine = (PBUS_BUS_RESET_NOTIFICATION) DCamBusResetNotification;
    pIrb->u.BusResetNotification.ResetContext = 0;
    Status = DCamSubmitIrpSynch(pDevExt, pIrp, pIrb);
    if(Status) {
        ERROR_LOG(("DCamSurpriseRemoval: Status %x while trying to deregister bus reset notification.\n", Status));
    }


    if(pStrmEx && pStrmEx->pVideoInfoHeader) {
        //
        // Stop isoch transmission so we can detach buffers and cancel pending SRBs
        //
        pIrb->FunctionNumber        = REQUEST_ISOCH_STOP;
        pIrb->Flags                 = 0;
        pIrb->u.IsochStop.hResource = pDevExt->hResource;
        pIrb->u.IsochStop.fulFlags  = 0;
        Status = DCamSubmitIrpSynch(pDevExt, pIrp, pIrb);
        if(Status) {
            ERROR_LOG(("DCamSurpriseRemoval: Status %x while trying to ISOCH_STOP.\n", Status));
        }
        IoFreeIrp(pIrp);

        if( InterlockedExchange((PLONG)&pStrmEx->CancelToken, 1 ) == 0 ) {
            DCamCancelAllPackets(
                pDevExt,
                &pDevExt->PendingReadCount );
        }
        COMPLETE_SRB( pSrb );

    } else {
        IoFreeIrp(pIrp);
        StreamClassDeviceNotification(DeviceRequestComplete, pSrb->HwDeviceExtension, pSrb);
    }

}
Пример #3
0
AtomicCounter& AtomicCounter::operator = (AtomicCounter::ValueType value)
{
	InterlockedExchange(&_counter, value);
	return *this;
}
Пример #4
0
int CMraProto::SetStatus(int iNewStatus)
{
	// remap global statuses to local supported
	switch (iNewStatus) {
	case ID_STATUS_OCCUPIED:
		iNewStatus = ID_STATUS_DND;
		break;
	case ID_STATUS_NA:
	case ID_STATUS_ONTHEPHONE:
	case ID_STATUS_OUTTOLUNCH:
		iNewStatus = ID_STATUS_AWAY;
		break;
	}

	// nothing to change
	if (m_iStatus == iNewStatus)
		return 0;

	DWORD dwOldStatusMode;

	//set all contacts to offline
	if ((m_iDesiredStatus = iNewStatus) == ID_STATUS_OFFLINE) {
		m_bLoggedIn = FALSE;
		dwOldStatusMode = InterlockedExchange((volatile LONG*)&m_iStatus, m_iDesiredStatus);

		// всех в offline, только если мы бывали подключены
		if (dwOldStatusMode > ID_STATUS_OFFLINE)
			for (HANDLE hContact = db_find_first(m_szModuleName); hContact; hContact = db_find_next(hContact, m_szModuleName))
				SetContactBasicInfoW(hContact, SCBIFSI_LOCK_CHANGES_EVENTS, (SCBIF_ID|SCBIF_GROUP_ID|SCBIF_SERVER_FLAG|SCBIF_STATUS), -1, -1, 0, 0, ID_STATUS_OFFLINE, 0, 0, 0);

		Netlib_CloseHandle(m_hConnection);
	}
	else {
		// если offline то сразу ставим connecting, но обработка как offline
		dwOldStatusMode = InterlockedCompareExchange((volatile LONG*)&m_iStatus, ID_STATUS_CONNECTING, ID_STATUS_OFFLINE);

		switch (dwOldStatusMode) {
		case ID_STATUS_OFFLINE: // offline, connecting
			if (StartConnect() != NO_ERROR) {
				m_bLoggedIn = FALSE;
				m_iDesiredStatus = ID_STATUS_OFFLINE;
				dwOldStatusMode = InterlockedExchange((volatile LONG*)&m_iStatus, m_iDesiredStatus);
			}
			break;
		case ID_STATUS_ONLINE:// connected, change status
		case ID_STATUS_AWAY:
		case ID_STATUS_DND:
		case ID_STATUS_FREECHAT:
		case ID_STATUS_INVISIBLE:
			MraSendNewStatus(m_iDesiredStatus, m_iXStatus, _T(""), _T(""));
		case ID_STATUS_CONNECTING:
			// предотвращаем переход в любой статус (кроме offline) из статуса connecting, если он не вызван самим плагином
			if (dwOldStatusMode == ID_STATUS_CONNECTING && iNewStatus != m_iDesiredStatus)
				break;

		default:
			dwOldStatusMode = InterlockedExchange((volatile LONG*)&m_iStatus, m_iDesiredStatus);
			break;
		}
	}
	MraSetContactStatus(NULL, m_iStatus);
	ProtoBroadcastAck(NULL, ACKTYPE_STATUS, ACKRESULT_SUCCESS, (HANDLE)dwOldStatusMode, m_iStatus);
	return 0;
}
Пример #5
0
/* Release spin lock */
static int slrelease (LOCKLONG *sl)
{
    InterlockedExchange ((volatile LONG*)sl, 0);
    return 0;
}
Пример #6
0
//! Удаляет DeletedFrame изо всех очередей!
//! Назначает следующий активный, (исходя из своих представлений)
//! Но только в том случае, если активный фрейм еще не назначен заранее.
void Manager::DeleteCommit()
{
	_MANAGER(CleverSysLog clv(L"Manager::DeleteCommit()"));
	_MANAGER(SysLog(L"DeletedFrame=%p",DeletedFrame));

	if (!DeletedFrame)
	{
		return;
	}

	// <ifDoubleInstance>
	//BOOL ifDoubI=ifDoubleInstance(DeletedFrame);
	// </ifDoubleInstance>
	int ModalIndex=IndexOfStack(DeletedFrame);

	if (ModalIndex!=-1)
	{
		/* $ 14.05.2002 SKV
		  Надёжнее найти и удалить именно то, что
		  нужно, а не просто верхний.
		*/
		for (int i=0; i<ModalStackCount; i++)
		{
			if (ModalStack[i]==DeletedFrame)
			{
				for (int j=i+1; j<ModalStackCount; j++)
				{
					ModalStack[j-1]=ModalStack[j];
				}

				ModalStackCount--;
				break;
			}
		}

		if (ModalStackCount)
		{
			ActivateFrame(ModalStack[ModalStackCount-1]);
		}
	}

	for (int i=0; i<FrameCount; i++)
	{
		if (FrameList[i]->FrameToBack==DeletedFrame)
		{
			FrameList[i]->FrameToBack=CtrlObject->Cp();
		}
	}

	int FrameIndex=IndexOf(DeletedFrame);

	if (-1!=FrameIndex)
	{
		DeletedFrame->DestroyAllModal();

		for (int j=FrameIndex; j<FrameCount-1; j++)
		{
			FrameList[j]=FrameList[j+1];
		}

		FrameCount--;

		if (FramePos >= FrameCount)
		{
			FramePos=0;
		}

		if (DeletedFrame->FrameToBack==CtrlObject->Cp())
		{
			ActivateFrame(FrameList[FramePos]);
		}
		else
		{
			ActivateFrame(DeletedFrame->FrameToBack);
		}
	}

	/* $ 14.05.2002 SKV
	  Долго не мог понять, нужен всё же этот код или нет.
	  Но вроде как нужен.
	  SVS> Когда понадобится - в некоторых местах расскомментить куски кода
	       помеченные скобками <ifDoubleInstance>

	if (ifDoubI && IsSemiModalBackFrame(ActivatedFrame)){
	  for(int i=0;i<ModalStackCount;i++)
	  {
	    if(ModalStack[i]==ActivatedFrame)
	    {
	      break;
	    }
	  }

	  if(i==ModalStackCount)
	  {
	    if (ModalStackCount == ModalStackSize){
	      ModalStack = (Frame **) xf_realloc (ModalStack, ++ModalStackSize * sizeof (Frame *));
	    }
	    ModalStack[ModalStackCount++]=ActivatedFrame;
	  }
	}
	*/
	DeletedFrame->OnDestroy();

	if (CurrentFrame==DeletedFrame)
	{
		CurrentFrame=0;
		InterlockedExchange(&CurrentWindowType,-1);
	}

	if (DeletedFrame->GetDynamicallyBorn())
	{
		_MANAGER(SysLog(L"delete DeletedFrame %p", DeletedFrame));

		/* $ 14.05.2002 SKV
		  Так как в деструкторе фрэйма неявно может быть
		  вызван commit, то надо подстраховаться.
		*/
		Frame *tmp=DeletedFrame;
		DeletedFrame=nullptr;
		delete tmp;
	}

	// Полагаемся на то, что в ActevateFrame не будет переписан уже
	// присвоенный  ActivatedFrame
	if (ModalStackCount)
	{
		ActivateFrame(ModalStack[ModalStackCount-1]);
	}
	else
	{
		ActivateFrame(FramePos);
	}
}
Пример #7
0
// 
// Add fault to Lurn fault list for future analysys
// 
// ErrorCode is dependent on fault type. It can be custom error code.
//
// Param is Type dependent parameter.
// Param is CCB if / Ccb is valid only for fault type LURN_ERR_IO, LURN_ERR_LOCK
//
NTSTATUS
LurnRecordFault(PLURELATION_NODE Lurn, LURN_FAULT_TYPE Type, UINT32 ErrorCode, PVOID Param)
{
	PLURN_FAULT_INFO fInfo = &Lurn->FaultInfo;
	LONG count;
	LURN_FAULT_TYPE	LastFaultType;
	LONG			LastErrorCode;
	PLURN_FAULT_IO pLfi= (PLURN_FAULT_IO) Param;

	LastFaultType = fInfo->LastFaultType;
	LastErrorCode = fInfo->LastErrorCode[LastFaultType];

	//
	// To do: Recognize some indirect error patterns.
	//

#if 0
	//
	// Check accesing same range failed.
	//
	if ((Type == LURN_ERR_READ || Type == LURN_ERR_WRITE || Type == LURN_ERR_VERIFY) && pLfi &&
		(ErrorCode == LURN_FAULT_COMMUNICATION))	{
		if (fInfo->LastIoOperation) {
			//
			// Check accesing same range failed and error occured multiple times.
			//
			if (fInfo->LastIoAddr + fInfo->LastIoLength > pLfi->Address 
				&& pLfi->Address+pLfi->Length > fInfo->LastIoAddr &&
						fInfo->ErrorCount[Type] > 5) {
				KDPrintM(NDASSCSI_DBG_LUR_ERROR, ("IO failed on same location. Marking error\n"));
				ErrorCode = LURN_FAULT_BAD_SECTOR;
			}
		} else {
			// no previous IO error recorded.
		}
	}
#endif
	//
	// to do: handle disk hang after bad sector..
	//
	
	// 
	// Update internal fault record.
	//		
	switch(Type) {
	case LURN_ERR_SUCCESS:
		count = InterlockedIncrement(&fInfo->ErrorCount[Type]);
		if (count == 128) {
			KDPrintM(NDASSCSI_DBG_LUR_TRACE, ("Resetting error count\n"));

			//
			// If some IO operation completed without any error, clear all other errors.
			//
			LurnResetFaultInfo(Lurn);
			InterlockedExchange(&fInfo->ErrorCount[Type], count);
		}
		break;
	case LURN_ERR_CONNECT:
	case LURN_ERR_LOGIN:
	case LURN_ERR_NDAS_OP:
	case LURN_ERR_DISK_OP:
	case LURN_ERR_READ:
	case LURN_ERR_WRITE: 
	case LURN_ERR_VERIFY: 		
	case LURN_ERR_UNKNOWN:
	case LURN_ERR_FLUSH:
	default:		
		// Error occured. Reset success count
		InterlockedExchange(&fInfo->ErrorCount[LURN_ERR_SUCCESS], 0);
		InterlockedIncrement(&fInfo->ErrorCount[Type]);
		InterlockedExchange(&fInfo->LastErrorCode[Type], ErrorCode);
		fInfo->LastFaultType = Type;
		KeQuerySystemTime(&fInfo->LastFaultTime);
		break;
	}

	if (Type == LURN_ERR_READ || Type == LURN_ERR_WRITE) {
		if (pLfi) {
			fInfo->LastIoOperation = Type;
			fInfo->LastIoAddr = pLfi->Address;
			fInfo->LastIoLength = pLfi->Length;
		}
	}

	//
	// Update error causes.
	//

	//
	// Guess error cause.  Be cautious when setting error because this can mark a disk as defective permanently.
	//
	if (Type == LURN_ERR_CONNECT) {
		fInfo->FaultCause |=  LURN_FCAUSE_TARGET_DOWN;
	} else {
		// At least target is not down
		fInfo->FaultCause &= ~LURN_FCAUSE_TARGET_DOWN;
	}

	if ((Type == LURN_ERR_READ || Type == LURN_ERR_WRITE || Type == LURN_ERR_VERIFY) &&
		ErrorCode == LURN_FAULT_BAD_SECTOR) {
		fInfo->FaultCause |=  LURN_FCAUSE_BAD_SECTOR;
	}

	if (Type == LURN_ERR_DISK_OP) {
		if (fInfo->ErrorCount[LURN_ERR_DISK_OP] > 5 && ErrorCode == LURN_FAULT_IDENTIFY) {

			NDAS_ASSERT(FALSE);

			//
			// If HDD's board is broken, identify may not work. 
			//
			// To do: mark LURN_FAULT_IDENTIFY fault only when this is just communication problem. (Need support from lpx)
			//
			fInfo->FaultCause |=  LURN_FCAUSE_BAD_DISK; 
		} else if (ErrorCode == LURN_FAULT_NOT_EXIST){
			//
			// NDAS chip cannot detect HDD. HDD may be removed or dead
			//
			fInfo->FaultCause |=  LURN_FAULT_NO_TARGET;
		}
	}

	//
	// to do: handle more error cases: LURN_ERR_FLUSH, LURN_ERR_LOGIN, LURN_ERR_NDAS_OP
	//
	return STATUS_SUCCESS;
}
Пример #8
0
/*
 * Monotonic and real time functions
 */
unsigned __stdcall wince_clock_gettime_threaded(void* param)
{
    LARGE_INTEGER hires_counter, li_frequency;
    LONG nb_responses;
    int timer_index;

    // Init - find out if we have access to a monotonic (hires) timer
    if (!QueryPerformanceFrequency(&li_frequency)) {
        usbi_dbg("no hires timer available on this platform");
        hires_frequency = 0;
        hires_ticks_to_ps = UINT64_C(0);
    } else {
        hires_frequency = li_frequency.QuadPart;
        // The hires frequency can go as high as 4 GHz, so we'll use a conversion
        // to picoseconds to compute the tv_nsecs part in clock_gettime
        hires_ticks_to_ps = UINT64_C(1000000000000) / hires_frequency;
        usbi_dbg("hires timer available (Frequency: %"PRIu64" Hz)", hires_frequency);
    }

    // Signal wince_init() that we're ready to service requests
    if (ReleaseSemaphore(timer_response, 1, NULL) == 0) {
        usbi_dbg("unable to release timer semaphore: %s", windows_error_str(0));
    }

    // Main loop - wait for requests
    while (1) {
        timer_index = WaitForMultipleObjects(2, timer_request, FALSE, INFINITE) - WAIT_OBJECT_0;
        if ( (timer_index != 0) && (timer_index != 1) ) {
            usbi_dbg("failure to wait on requests: %s", windows_error_str(0));
            continue;
        }
        if (request_count[timer_index] == 0) {
            // Request already handled
            ResetEvent(timer_request[timer_index]);
            // There's still a possiblity that a thread sends a request between the
            // time we test request_count[] == 0 and we reset the event, in which case
            // the request would be ignored. The simple solution to that is to test
            // request_count again and process requests if non zero.
            if (request_count[timer_index] == 0)
                continue;
        }
        switch (timer_index) {
        case 0:
            WaitForSingleObject(timer_mutex, INFINITE);
            // Requests to this thread are for hires always
            if (QueryPerformanceCounter(&hires_counter) != 0) {
                timer_tp.tv_sec = (long)(hires_counter.QuadPart / hires_frequency);
                timer_tp.tv_nsec = (long)(((hires_counter.QuadPart % hires_frequency)/1000) * hires_ticks_to_ps);
            } else {
                // Fallback to real-time if we can't get monotonic value
                // Note that real-time clock does not wait on the mutex or this thread.
                wince_clock_gettime(USBI_CLOCK_REALTIME, &timer_tp);
            }
            ReleaseMutex(timer_mutex);

            nb_responses = InterlockedExchange((LONG*)&request_count[0], 0);
            if ( (nb_responses)
                    && (ReleaseSemaphore(timer_response, nb_responses, NULL) == 0) ) {
                usbi_dbg("unable to release timer semaphore: %s", windows_error_str(0));
            }
            continue;
        case 1: // time to quit
            usbi_dbg("timer thread quitting");
            return 0;
        }
    }
    usbi_dbg("ERROR: broken timer thread");
    return 1;
}
Пример #9
0
DWORD WINAPI CIOCPServer::_ListenThreadProc(LPVOID lpParam)
{
	CIOCPServer *pThis = (CIOCPServer*)lpParam;

	// 先在监听套节字上投递几个Accept I/O
	CIOCPBuffer *pBuffer;
	for(int i=0; i<pThis->m_nInitialAccepts; i++)
	{
		pBuffer = pThis->AllocateBuffer(BUFFER_SIZE);
		if(pBuffer == NULL)
			return -1;
		pThis->InsertPendingAccept(pBuffer);
		pThis->PostAccept(pBuffer);
	}

	// 构建事件对象数组,以便在上面调用WSAWaitForMultipleEvents函数
	HANDLE hWaitEvents[2 + MAX_THREAD];
	int nEventCount = 0;
	hWaitEvents[nEventCount ++] = pThis->m_hAcceptEvent;
	hWaitEvents[nEventCount ++] = pThis->m_hRepostEvent;

	// 创建指定数量的工作线程在完成端口上处理I/O
	int i = 0;
	for(i=0; i<MAX_THREAD; i++)
	{
		hWaitEvents[nEventCount ++] = ::CreateThread(NULL, 0, _WorkerThreadProc, pThis, 0, NULL);
	}

	// 下面进入无限循环,处理事件对象数组中的事件
	while(TRUE)
	{
		int nIndex = ::WSAWaitForMultipleEvents(nEventCount, hWaitEvents, FALSE, 1000, FALSE);
	
		// 首先检查是否要停止服务
		if(pThis->m_bShutDown || nIndex == WSA_WAIT_FAILED)
		{
			// 关闭所有连接
			pThis->CloseAllConnections();
			::Sleep(0);		// 给I/O工作线程一个执行的机会
			// 关闭监听套节字
			::closesocket(pThis->m_sListen);
			pThis->m_sListen = INVALID_SOCKET;
			::Sleep(0);		// 给I/O工作线程一个执行的机会

			// 通知所有I/O处理线程退出
			for(int i=2; i<MAX_THREAD + 2; i++)
			{	
				::PostQueuedCompletionStatus(pThis->m_hCompletion, -1, 0, NULL);
			}

			// 等待I/O处理线程退出
			::WaitForMultipleObjects(MAX_THREAD, &hWaitEvents[2], TRUE, 5*1000);

			for(i=2; i<MAX_THREAD + 2; i++)
			{	
				::CloseHandle(hWaitEvents[i]);
			}
		
			::CloseHandle(pThis->m_hCompletion);

			pThis->FreeBuffers();
			pThis->FreeContexts();
			::ExitThread(0);
		}	

		// 1)定时检查所有未返回的AcceptEx I/O的连接建立了多长时间
		if(nIndex == WSA_WAIT_TIMEOUT)
		{
			pBuffer = pThis->m_pPendingAccepts;
			while(pBuffer != NULL)
			{
				int nSeconds;
				int nLen = sizeof(nSeconds);
				// 取得连接建立的时间
				::getsockopt(pBuffer->sClient, 
					SOL_SOCKET, SO_CONNECT_TIME, (char *)&nSeconds, &nLen);	
				// 如果超过10秒钟客户还不发送初始数据,就让这个客户go away
				if(nSeconds != -1 && nSeconds >= 10)
				{   
					closesocket(pBuffer->sClient);
                    pBuffer->sClient = INVALID_SOCKET;
				}

				pBuffer = pBuffer->pNext;
			}
		}
		else
		{
			nIndex = nIndex - WAIT_OBJECT_0;
			WSANETWORKEVENTS ne;
            int nLimit=0;
			if(nIndex == 0)			// 2)m_hAcceptEvent事件对象受信,说明投递的Accept请求不够,需要增加
			{
				::WSAEnumNetworkEvents(pThis->m_sListen, hWaitEvents[nIndex], &ne);
				if(ne.lNetworkEvents & FD_ACCEPT)
				{
					nLimit = 50;  // 增加的个数,这里设为50个
				}
			}
			else if(nIndex == 1)	// 3)m_hRepostEvent事件对象受信,说明处理I/O的线程接受到新的客户
			{
				nLimit = InterlockedExchange(&pThis->m_nRepostCount, 0);
			}
			else if(nIndex > 1)		// I/O服务线程退出,说明有错误发生,关闭服务器
			{
				pThis->m_bShutDown = TRUE;
				continue;
			}

			// 投递nLimit个AcceptEx I/O请求
			int i = 0;
			while(i++ < nLimit && pThis->m_nPendingAcceptCount < pThis->m_nMaxAccepts)
			{
				pBuffer = pThis->AllocateBuffer(BUFFER_SIZE);
				if(pBuffer != NULL)
				{
					pThis->InsertPendingAccept(pBuffer);
					pThis->PostAccept(pBuffer);
				}
			}
		}
	}
	return 0;
}
Пример #10
0
NTSTATUS
NTAPI
CmBattGetBatteryStatus(IN PCMBATT_DEVICE_EXTENSION DeviceExtension,
                       IN ULONG Tag)
{
    ULONG PsrData = 0;
    NTSTATUS Status;
    ULONG BstState;
    ULONG DesignVoltage, PresentRate, RemainingCapacity;
    PAGED_CODE();
    if (CmBattDebug & CMBATT_GENERIC_INFO)
        DbgPrint("CmBattGetBatteryStatus - CmBatt (%08x) Tag (%d)\n", DeviceExtension, Tag);
    
    /* Validate ACPI data */    
    Status = CmBattVerifyStaticInfo(DeviceExtension, Tag);
    if (!NT_SUCCESS(Status)) return Status;

    /* Check for delayed status notifications */
    if (DeviceExtension->DelayNotification)
    {
        /* Process them now and don't do any other work */
        CmBattNotifyHandler(DeviceExtension, ACPI_BATT_NOTIFY_STATUS);
        return Status;
    }

    /* Get _BST from ACPI */
    Status = CmBattGetBstData(DeviceExtension, &DeviceExtension->BstData);
    if (!NT_SUCCESS(Status))
    {
        /* Fail */
        InterlockedExchange(&DeviceExtension->ArLockValue, 0);
        return Status;
    }
    
    /* Clear current BST information */ 
    DeviceExtension->State = 0;
    DeviceExtension->RemainingCapacity = 0;
    DeviceExtension->PresentVoltage = 0;
    DeviceExtension->Rate = 0;

    /* Get battery state */
    BstState = DeviceExtension->BstData.State;
    
    /* Is the battery both charging and discharging? */
    if ((BstState & ACPI_BATT_STAT_DISCHARG) && (BstState & ACPI_BATT_STAT_CHARGING) &&
        (CmBattDebug & (CMBATT_ACPI_WARNING | CMBATT_GENERIC_WARNING)))
            DbgPrint("************************ ACPI BIOS BUG ********************\n* "
                     "CmBattGetBatteryStatus: Invalid state: _BST method returned 0x%08x for Battery State.\n"
                     "* One battery cannot be charging and discharging at the same time.\n",
                     BstState);
    
    /* Is the battery discharging? */   
    if (BstState & ACPI_BATT_STAT_DISCHARG)
    {
        /* Set power state and check if it just started discharging now */
        DeviceExtension->State |= BATTERY_DISCHARGING;
        if (!(DeviceExtension->State & ACPI_BATT_STAT_DISCHARG))
        {
            /* Remember the time when the state changed */
            DeviceExtension->InterruptTime = KeQueryInterruptTime();
        }
    }
    else if (BstState & ACPI_BATT_STAT_CHARGING)
    {
        /* Battery is charging, update power state */
        DeviceExtension->State |= (BATTERY_CHARGING | BATTERY_POWER_ON_LINE);
    }
    
    /* Is the battery in a critical state? */
    if (BstState & ACPI_BATT_STAT_CRITICAL) DeviceExtension->State |= BATTERY_CRITICAL;
    
    /* Read the voltage data */  
    DeviceExtension->PresentVoltage = DeviceExtension->BstData.PresentVoltage;
    
    /* Check if we have an A/C adapter */
    if (AcAdapterPdo)
    {
        /* Query information on it */
        CmBattGetPsrData(AcAdapterPdo, &PsrData);
    }
    else
    {
        /* Otherwise, check if the battery is charging */
        if (BstState & ACPI_BATT_STAT_CHARGING)
        {
            /* Then we'll assume there's a charger */
            PsrData = 1;
        }
        else
        {
            /* Assume no charger */
            PsrData = 0;        
        }
    }
    
    /* Is there a charger? */
    if (PsrData)
    {
        /* Set the power state flag to reflect this */
        DeviceExtension->State |= BATTERY_POWER_ON_LINE;
        if (CmBattDebug & (CMBATT_GENERIC_INFO | CMBATT_GENERIC_STATUS))
            DbgPrint("CmBattGetBatteryStatus: AC adapter is connected\n");
    }
    else if (CmBattDebug & (CMBATT_GENERIC_INFO | CMBATT_GENERIC_STATUS))
    {
        DbgPrint("CmBattGetBatteryStatus: AC adapter is NOT connected\n");        
    }
    
    /* Get some data we'll need */
    DesignVoltage = DeviceExtension->BifData.DesignVoltage;
    PresentRate = DeviceExtension->BstData.PresentRate;
    RemainingCapacity = DeviceExtension->BstData.RemainingCapacity;
    
    /* Check if we have battery data in Watts instead of Amps */
    if (DeviceExtension->BifData.PowerUnit == ACPI_BATT_POWER_UNIT_WATTS)
    {
        /* Get the data from the BST */
        DeviceExtension->RemainingCapacity = RemainingCapacity;
        DeviceExtension->Rate = PresentRate;
        
        /* Check if the rate is invalid */
        if (PresentRate > CM_MAX_VALUE)
        {
            /* Set an unknown rate and don't touch the old value */
            DeviceExtension->Rate = BATTERY_UNKNOWN_RATE;
            if ((PresentRate != CM_UNKNOWN_VALUE) && (CmBattDebug & CMBATT_ACPI_WARNING))
            {
                DbgPrint("CmBattGetBatteryStatus - Rate is greater than CM_MAX_VALUE\n");
                DbgPrint("----------------------   PresentRate = 0x%08x\n", PresentRate);
            }
        }
    }
    else if ((DesignVoltage != CM_UNKNOWN_VALUE) && (DesignVoltage))
    {
        /* We have voltage data, what about capacity? */
        if (RemainingCapacity == CM_UNKNOWN_VALUE)
        {
            /* Unable to calculate it */
            DeviceExtension->RemainingCapacity = BATTERY_UNKNOWN_CAPACITY;
            if (CmBattDebug & CMBATT_ACPI_WARNING)
            {
                DbgPrint("CmBattGetBatteryStatus - Can't calculate RemainingCapacity \n");
                DbgPrint("----------------------   RemainingCapacity = CM_UNKNOWN_VALUE\n");
            }
        }
        else
        {
            /* Compute the capacity with the information we have */
            DeviceExtension->RemainingCapacity = (DesignVoltage * RemainingCapacity + 500) / 1000;
        }
        
        /* Check if we have a rate */
        if (PresentRate != CM_UNKNOWN_VALUE)
        {
            /* Make sure the rate isn't too large */
            if (PresentRate > (-500 / DesignVoltage))
            {
                /* It is, so set unknown state */
                DeviceExtension->Rate = BATTERY_UNKNOWN_RATE;
                if (CmBattDebug & CMBATT_ACPI_WARNING)
                {
                    DbgPrint("CmBattGetBatteryStatus - Can't calculate Rate \n");
                    DbgPrint("----------------------   Overflow: PresentRate = 0x%08x\n", PresentRate);
                }
            }
            
            /* Compute the rate */
            DeviceExtension->Rate = (PresentRate * DesignVoltage + 500) / 1000;
        }
        else
        {
            /* We don't have a rate, so set unknown value */
            DeviceExtension->Rate = BATTERY_UNKNOWN_RATE;        
            if (CmBattDebug & CMBATT_ACPI_WARNING)
            {
                DbgPrint("CmBattGetBatteryStatus - Can't calculate Rate \n");
                DbgPrint("----------------------   Present Rate = CM_UNKNOWN_VALUE\n");
            }
        }
    }
    else
    {
        /* We have no rate, and no capacity, set unknown values */
        DeviceExtension->Rate = BATTERY_UNKNOWN_RATE;
        DeviceExtension->RemainingCapacity = BATTERY_UNKNOWN_CAPACITY;
        if (CmBattDebug & CMBATT_ACPI_WARNING)
        {
            DbgPrint("CmBattGetBatteryStatus - Can't calculate RemainingCapacity and Rate \n");
            DbgPrint("----------------------   DesignVoltage = 0x%08x\n", DesignVoltage);
        }
    }
    
    /* Check if we have an unknown rate */
    if (DeviceExtension->Rate == BATTERY_UNKNOWN_RATE)
    {
        /* The battery is discharging but we don't know by how much... this is bad! */
        if ((BstState & ACPI_BATT_STAT_DISCHARG) &&
            (CmBattDebug & (CMBATT_ACPI_WARNING | CMBATT_GENERIC_WARNING)))
            DbgPrint("CmBattGetBatteryStatus: battery rate is unkown when battery is not charging!\n");
    }
    else if (DeviceExtension->State & BATTERY_DISCHARGING)
    {
        /* The battery is discharging, so treat the rate as a negative rate */
        DeviceExtension->Rate = -DeviceExtension->Rate;
    }
    else if (!(DeviceExtension->State & BATTERY_CHARGING) && (DeviceExtension->Rate))
    {
        /* We are not charging, not discharging, but have a rate? Ignore it! */
        if (CmBattDebug & CMBATT_GENERIC_WARNING)
            DbgPrint("CmBattGetBatteryStatus: battery is not charging or discharging, but rate = %x\n",
                     DeviceExtension->Rate);
        DeviceExtension->Rate = 0;
    }
     
    /* Done */
    return STATUS_SUCCESS;
}
Пример #11
0
ALCboolean xaudio2_do_reset_playback(ALCdevice * device)
{
	XAudio2Data* data = (XAudio2Data*)device->ExtraData;

	HRESULT hr;
	DWORD outputchannelMasks;
	XAUDIO2_VOICE_DETAILS outputDetails;
	WAVEFORMATEXTENSIBLE SourceType;

	data->masterVoice->GetChannelMask(&outputchannelMasks);
	data->masterVoice->GetVoiceDetails(&outputDetails);

	if (!(device->Flags&DEVICE_FREQUENCY_REQUEST))
		device->Frequency = outputDetails.InputSampleRate;
	if (!(device->Flags&DEVICE_CHANNELS_REQUEST))
	{
		if (outputDetails.InputChannels == 1 && outputchannelMasks == MONO)
			device->FmtChans = DevFmtMono;
		else if (outputDetails.InputChannels == 2 && outputchannelMasks == STEREO)
			device->FmtChans = DevFmtStereo;
		else if (outputDetails.InputChannels == 4 && outputchannelMasks == QUAD)
			device->FmtChans = DevFmtQuad;
		else if (outputDetails.InputChannels == 6 && outputchannelMasks == X5DOT1)
			device->FmtChans = DevFmtX51;
		else if (outputDetails.InputChannels == 6 && outputchannelMasks == X5DOT1SIDE)
			device->FmtChans = DevFmtX51Side;
		else if (outputDetails.InputChannels == 7 && outputchannelMasks == X6DOT1)
			device->FmtChans = DevFmtX61;
		else if (outputDetails.InputChannels == 8 && outputchannelMasks == X7DOT1)
			device->FmtChans = DevFmtX71;
		else
			ERR("Unhandled channel config: %d -- 0x%08lx\n", outputDetails.InputChannels, outputchannelMasks);
	}

	SetDefaultWFXChannelOrder(device);

	switch (device->FmtChans)
	{
	case DevFmtMono:
		SourceType.Format.nChannels = 1;
		SourceType.dwChannelMask = MONO;
		break;
	case DevFmtStereo:
		SourceType.Format.nChannels = 2;
		SourceType.dwChannelMask = STEREO;
		break;
	case DevFmtQuad:
		SourceType.Format.nChannels = 4;
		SourceType.dwChannelMask = QUAD;
		break;
	case DevFmtX51:
		SourceType.Format.nChannels = 6;
		SourceType.dwChannelMask = X5DOT1;
		break;
	case DevFmtX51Side:
		SourceType.Format.nChannels = 6;
		SourceType.dwChannelMask = X5DOT1SIDE;
		break;
	case DevFmtX61:
		SourceType.Format.nChannels = 7;
		SourceType.dwChannelMask = X6DOT1;
		break;
	case DevFmtX71:
		SourceType.Format.nChannels = 8;
		SourceType.dwChannelMask = X7DOT1;
		break;
	}
	switch (device->FmtType)
	{
	case DevFmtByte:
		device->FmtType = DevFmtUByte;
		/* fall-through */
	case DevFmtUByte:
		SourceType.Format.wBitsPerSample = 8;
		SourceType.Samples.wValidBitsPerSample = 8;
		SourceType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
		break;
	case DevFmtUShort:
		device->FmtType = DevFmtShort;
		/* fall-through */
	case DevFmtShort:
		SourceType.Format.wBitsPerSample = 16;
		SourceType.Samples.wValidBitsPerSample = 16;
		SourceType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
		break;
	case DevFmtFloat:
		SourceType.Format.wBitsPerSample = 32;
		SourceType.Samples.wValidBitsPerSample = 32;
		SourceType.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
		break;
	}
	SourceType.Format.cbSize = (sizeof(SourceType) - sizeof(WAVEFORMATEX));
	SourceType.Format.nSamplesPerSec = device->Frequency;

	SourceType.Format.nBlockAlign = SourceType.Format.nChannels *
		SourceType.Format.wBitsPerSample / 8;
	SourceType.Format.nAvgBytesPerSec = SourceType.Format.nSamplesPerSec *
		SourceType.Format.nBlockAlign;

	SourceType.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;

	/*-----------create source voice-------------*/
	data->sourceVoiceCallback = new (std::nothrow) XAudio2SourceVoiceCallback(device);
	if (data->sourceVoiceCallback == NULL)
	{
		ERR("create XAudio2SourceVoiceCallback() failed\n");
		return ALC_FALSE;
	}

	data->sourceVoiceCallback->callbackEvent = CreateEventEx(NULL, NULL, 0, EVENT_ACCESS_MASK);
	if (data->sourceVoiceCallback->callbackEvent == NULL)
	{
		ERR("create callback event failed\n");
		return ALC_FALSE;
	}

	hr = data->xAudioObj->CreateSourceVoice(&data->sourceVoice, &SourceType.Format, 0,
		XAUDIO2_DEFAULT_FREQ_RATIO, data->sourceVoiceCallback);
	if (FAILED(hr))
	{
		ERR("CreateSourceVoice() failed: 0x%08lx\n", hr);
		return ALC_FALSE;
	}

	/*---------create buffer--------------*/
	//calculate frame size
	data->frameSize = FrameSizeFromDevFmt(device->FmtChans, device->FmtType);

	//start playing the audio engine
	data->sourceVoice->Start();

	//wait for the buffer to be created
	WaitForSingleObjectEx(data->sourceVoiceCallback->callbackEvent, INFINITE, FALSE);

	device->UpdateSize = data->bufferSize / data->frameSize;
	device->NumUpdates = 1;


	//set the running flag
	InterlockedExchange(&data->running, TRUE);

	return ALC_TRUE;
}
Пример #12
0
VOID
NTAPI
CmBattWakeDpc(IN PKDPC Dpc,
              IN PCMBATT_DEVICE_EXTENSION FdoExtension,
              IN PVOID SystemArgument1,
              IN PVOID SystemArgument2)
{
    PDEVICE_OBJECT CurrentObject;
    BOOLEAN AcNotify = FALSE;
    PCMBATT_DEVICE_EXTENSION DeviceExtension;
    ULONG ArFlag;
    if (CmBattDebug & 2) DbgPrint("CmBattWakeDpc: Entered.\n");
    
    /* Loop all device objects */
    for (CurrentObject = FdoExtension->DeviceObject;
         CurrentObject;
         CurrentObject = CurrentObject->NextDevice)
    {
        /* Turn delay flag off, we're back in S0 */
        DeviceExtension = CurrentObject->DeviceExtension;
        DeviceExtension->DelayNotification = 0;
        
        /* Check if this is an AC adapter */
        if (DeviceExtension->FdoType == CmBattAcAdapter)
        {
            /* Was there a pending notify? */
            if (DeviceExtension->ArFlag & CMBATT_AR_NOTIFY)
            {
                /* We'll send a notify on the next pass */
                AcNotify = TRUE;
                DeviceExtension->ArFlag = 0;
                if (CmBattDebug & 0x20)
                    DbgPrint("CmBattWakeDpc: AC adapter notified\n");
            }
        }
    }

    /* Loop the device objects again */
    for (CurrentObject = FdoExtension->DeviceObject;
         CurrentObject;
         CurrentObject = CurrentObject->NextDevice)
    {
        /* Check if this is a battery */
        DeviceExtension = CurrentObject->DeviceExtension;
        if (DeviceExtension->FdoType == CmBattBattery)
        {
            /* Check what ARs are pending */
            ArFlag = DeviceExtension->ArFlag;
            if (CmBattDebug & 0x20)
                DbgPrint("CmBattWakeDpc: Performing delayed ARs: %01x\n", ArFlag);

            /* Insert notification, clear the lock value */
            if (ArFlag & CMBATT_AR_INSERT) InterlockedExchange(&DeviceExtension->ArLockValue, 0);

            /* Removal, clear the battery tag */
            if (ArFlag & CMBATT_AR_REMOVE) DeviceExtension->Tag = 0;

            /* Notification (or AC/DC adapter change from first pass above) */
            if ((ArFlag & CMBATT_AR_NOTIFY) || (AcNotify))
            {
                /* Notify the class driver */
                BatteryClassStatusNotify(DeviceExtension->ClassData);
            }
        }
    }
}
Пример #13
0
VOID
NTAPI
CmBattNotifyHandler(IN PCMBATT_DEVICE_EXTENSION DeviceExtension,
                    IN ULONG NotifyValue)
{
    ULONG ArFlag;
    PCMBATT_DEVICE_EXTENSION FdoExtension;
    PDEVICE_OBJECT DeviceObject;
    
    if (CmBattDebug & (CMBATT_ACPI_ASSERT | CMBATT_PNP_INFO))
        DbgPrint("CmBattNotifyHandler: CmBatt 0x%08x Type %d Number %d Notify Value: %x\n",
                 DeviceExtension,
                 DeviceExtension->FdoType,
                 DeviceExtension->DeviceId,
                 NotifyValue);
    
    /* Check what kind of notification was received */
    switch (NotifyValue)
    {
        /* ACPI Specification says is sends a "Bus Check" when power source changes */
        case ACPI_BUS_CHECK:
        
            /* We treat it as possible physical change */
            DeviceExtension->ArFlag |= (CMBATT_AR_NOTIFY | CMBATT_AR_INSERT);
            if ((DeviceExtension->Tag) &&
                (CmBattDebug & (CMBATT_ACPI_WARNING | CMBATT_GENERIC_WARNING)))
                DbgPrint("CmBattNotifyHandler: Received battery #%x insertion, but tag was not invalid.\n",
                         DeviceExtension->DeviceId);
            break;
        
        /* Status of the battery has changed */
        case ACPI_BATT_NOTIFY_STATUS:
        
            /* All we'll do is notify the class driver */
            DeviceExtension->ArFlag |= CMBATT_AR_NOTIFY;
            break;
        
        /* Information on the battery has changed, such as physical presence */
        case ACPI_DEVICE_CHECK:
        case ACPI_BATT_NOTIFY_INFO:
        
            /* Reset all state and let the class driver re-evaluate it all */
            DeviceExtension->ArFlag |= (CMBATT_AR_NOTIFY |
                                        CMBATT_AR_INSERT |
                                        CMBATT_AR_REMOVE);
            break;
            
        default:
        
            if (CmBattDebug & CMBATT_PNP_INFO)
                DbgPrint("CmBattNotifyHandler: Unknown Notify Value: %x\n", NotifyValue);
    }

    /* Check if we're supposed to delay the notification till later */
    if (DeviceExtension->DelayNotification)
    {
        /* We'll handle this when we get a status query later on */
        if (CmBattDebug & CMBATT_PNP_INFO)
            DbgPrint("CmBattNotifyHandler: Notification delayed: ARs = %01x\n",
                      DeviceExtension->ArFlag);
        return;
    }

    /* We're going to handle this now */
    if (CmBattDebug & CMBATT_PNP_INFO) 
        DbgPrint("CmBattNotifyHandler: Performing ARs: %01x\n", DeviceExtension->ArFlag);

    /* Check if this is a battery or AC adapter notification */
    if (DeviceExtension->FdoType == CmBattBattery)
    {
        /* Reset the current trip point */
        DeviceExtension->TripPointValue = BATTERY_UNKNOWN_CAPACITY;
        
        /* Check what ARs have to be done */
        ArFlag = DeviceExtension->ArFlag;
        
        /* New battery inserted, reset lock value */
        if (ArFlag & CMBATT_AR_INSERT) InterlockedExchange(&DeviceExtension->ArLockValue, 0);

        /* Check if the battery may have been removed */
        if (ArFlag & CMBATT_AR_REMOVE) DeviceExtension->Tag = 0;
        
        /* Check if there's been any sort of change to the battery */
        if (ArFlag & CMBATT_AR_NOTIFY)
        {
            /* We'll probably end up re-evaluating _BIF and _BST */
            DeviceExtension->NotifySent = TRUE;
            BatteryClassStatusNotify(DeviceExtension->ClassData);
        }
    }
    else if (DeviceExtension->ArFlag & CMBATT_AR_NOTIFY)
    {
        /* The only known notification is AC/DC change. Loop device objects. */
        for (DeviceObject = DeviceExtension->FdoDeviceObject->DriverObject->DeviceObject;
             DeviceObject;
             DeviceObject = DeviceObject->NextDevice)
        {
            /* Is this a battery? */
            FdoExtension = DeviceObject->DeviceExtension;
            if (FdoExtension->FdoType == CmBattBattery)
            {
                /* Send a notification to the class driver */
                FdoExtension->NotifySent = TRUE;
                BatteryClassStatusNotify(FdoExtension->ClassData);
            }
        }
    }
    
    /* ARs have been processed */
    DeviceExtension->ArFlag = 0;
}
Пример #14
0
/*++

ConnectionOpen

    Opens a server connection.

Arguments:
    context - Opaque context passed to <PoolCreate>.

    data    - Pointer to a pointer that receives the DB_CONTEXT structure.

Return Values:
    If the function succeeds, the return value is nonzero (true).

    If the function fails, the return value is zero (false).

--*/
static BOOL FCALL ConnectionOpen(VOID *context, VOID **data)
{
    DB_CONTEXT          *db;
    DB_CONFIG_SERVER    *server;
    DWORD               error;
    DWORD               i;
    INT                 attempt;
    INT                 attemptMax;
    LONG                serverIndex;
    LONG                serverNextIndex;
    MYSQL               *connection;
    my_bool             optReconnect;
    UINT                optTimeout;

    UNREFERENCED_PARAMETER(context);
    ASSERT(data != NULL);
    TRACE("context=%p data=%p", context, data);

    db = MemAllocate(sizeof(DB_CONTEXT));
    if (db == NULL) {
        LOG_ERROR("Unable to allocate memory for database context.");

        error = ERROR_NOT_ENOUGH_MEMORY;
        goto failed;
    }
    ZeroMemory(db, sizeof(DB_CONTEXT));

    //
    // Have the MySQL client library allocate the handle structure for us. This is
    // in case the MYSQL structure changes in a future version of the client library.
    //
    db->handle = mysql_init(NULL);
    if (db->handle == NULL) {
        LOG_ERROR("Unable to allocate memory for MySQL handle.");

        error = ERROR_NOT_ENOUGH_MEMORY;
        goto failed;
    }

    // If the maximum number of attempts were not specified, try all servers
    if (dbConfigGlobal.connAttempts > 0) {
        attemptMax = dbConfigGlobal.connAttempts;
    } else {
        attemptMax = dbConfigServerCount;
    }

    for (attempt = 0; attempt < attemptMax; attempt++) {
        // Use the most recent server for the connection attempt
        serverIndex = dbIndex;
        server      = &dbConfigServers[serverIndex];

        TRACE("Connecting to server #%d [%s] on attempt %lu/%lu.",
            serverIndex, server->name, attempt+1, attemptMax);

        // Set connection options
        optTimeout = (UINT)dbConfigGlobal.connTimeout;
        if (mysql_options(db->handle, MYSQL_OPT_CONNECT_TIMEOUT, &optTimeout) != 0) {
            TRACE("Failed to set connection timeout option.");
        }

        optReconnect = FALSE;
        if (mysql_options(db->handle, MYSQL_OPT_RECONNECT, &optReconnect) != 0) {
            TRACE("Failed to set reconnection option.");
        }

        if (server->compression) {
            if (mysql_options(db->handle, MYSQL_OPT_COMPRESS, 0) != 0) {
                TRACE("Failed to set compression option.");
            }
        }

        if (server->sslEnable) {
            //
            // This function always returns 0. If the SSL setup is incorrect,
            // the call to mysql_real_connect() will return an error.
            //
            mysql_ssl_set(db->handle, server->sslKeyFile, server->sslCertFile,
                server->sslCAFile, server->sslCAPath, server->sslCiphers);
        }

        // Attempt connection with server
        connection = mysql_real_connect(db->handle,
            server->host, server->user, server->password,
            server->database, server->port, NULL, CLIENT_INTERACTIVE);

        if (connection == NULL) {
            LOG_ERROR("Unable to connect to server [%s]: %s",
                server->name, mysql_error(db->handle));

        } else if (mysql_get_server_version(db->handle) < 50019) {
            LOG_ERROR("Unsupported version of MySQL Server [%s]: running v%s, must be v5.0.19 or newer.",
                server->name, mysql_get_server_info(db->handle));

        } else {
            // Pointer values should be the same as from mysql_init()
            ASSERT(connection == db->handle);

            // Allocate pre-compiled statement structures
            for (i = 0; i < ELEMENT_COUNT(db->stmt); i++) {
                db->stmt[i] = mysql_stmt_init(db->handle);
                if (db->stmt[i] == NULL) {
                    LOG_ERROR("Unable to allocate memory for statement structure.");

                    error = ERROR_NOT_ENOUGH_MEMORY;
                    goto failed;
                }
            }

            // Successfully connected, set the global server index
            InterlockedExchange(&dbIndex, serverIndex);

            // Update context's server index and time stamps
            db->index = serverIndex;
            GetSystemTimeAsFileTime(&db->created.fileTime);
            db->used.value = db->created.value;

            LOG_INFO("Connected to %s [%s], running MySQL Server v%s.",
                mysql_get_host_info(db->handle), server->name,
                mysql_get_server_info(db->handle));

            *data = db;
            return TRUE;
        }

        // Unsuccessful connection, continue to the next server
        serverNextIndex = serverIndex + 1;
        if (serverNextIndex >= (LONG)dbConfigServerCount) {
            serverNextIndex = 0;
        }

        //
        // Compare the current server index before swapping values in the
        // event that another thread has already changed the index.
        //
        InterlockedCompareExchange(&dbIndex, serverNextIndex, serverIndex);
    }

    // Unable to connect to any servers
    error = ERROR_CONNECTION_REFUSED;

failed:
    if (db != NULL) {
        ConnectionClose(NULL, db);
    }
    SetLastError(error);
    return FALSE;
}
Пример #15
0
int GitRev::SafeFetchFullInfo(CGit *git)
{
	if(InterlockedExchange(&m_IsUpdateing,TRUE) == FALSE)
	{
		this->m_Files.Clear();
		git->CheckAndInitDll();
		GIT_COMMIT commit;
		GIT_COMMIT_LIST list;
		GIT_HASH   parent;
		memset(&commit,0,sizeof(GIT_COMMIT));

		CAutoLocker lock(g_Git.m_critGitDllSec);

		try
		{
			if (git_get_commit_from_hash(&commit, this->m_CommitHash.m_hash))
				return -1;
		}
		catch (char *)
		{
			return -1;
		}

		int i=0;

		git_get_commit_first_parent(&commit,&list);
		bool isRoot = (list==NULL);

		while(git_get_commit_next_parent(&list,parent) == 0 || isRoot)
		{
			GIT_FILE file=0;
			int count=0;

			try
			{
				if (isRoot)
					git_root_diff(git->GetGitDiff(), this->m_CommitHash.m_hash, &file, &count, 1);
				else
					git_diff(git->GetGitDiff(), parent, commit.m_hash, &file, &count, 1);
			}
			catch (char *)
			{
				git_free_commit(&commit);
				return -1;
			}
			isRoot = false;

			CTGitPath path;
			CString strnewname;
			CString stroldname;

			for (int j = 0; j < count; ++j)
			{
				path.Reset();
				char *newname;
				char *oldname;

				strnewname.Empty();
				stroldname.Empty();

				int mode,IsBin,inc,dec;
				git_get_diff_file(git->GetGitDiff(),file,j,&newname,&oldname,
						&mode,&IsBin,&inc,&dec);

				git->StringAppend(&strnewname, (BYTE*)newname, CP_UTF8);
				git->StringAppend(&stroldname, (BYTE*)oldname, CP_UTF8);

				path.SetFromGit(strnewname,&stroldname);
				path.ParserAction((BYTE)mode);
				path.m_ParentNo = i;

				this->m_Action|=path.m_Action;

				if(IsBin)
				{
					path.m_StatAdd=_T("-");
					path.m_StatDel=_T("-");
				}
				else
				{
					path.m_StatAdd.Format(_T("%d"),inc);
					path.m_StatDel.Format(_T("%d"),dec);
				}
				m_Files.AddPath(path);
			}
			git_diff_flush(git->GetGitDiff());
			++i;
		}


		InterlockedExchange(&m_IsUpdateing,FALSE);
		InterlockedExchange(&m_IsFull,TRUE);
		git_free_commit(&commit);
	}

	return 0;
}
// In newer compilers, the inline versions of these are used (in juce_Atomic.h), but in
// older ones we have to actually call the ops as win32 functions..
long juce_InterlockedExchange (volatile long* a, long b) noexcept                { return InterlockedExchange (a, b); }
Пример #17
0
NTSTATUS FWDispatch(
								   IN PDEVICE_OBJECT		DeviceObject,
								   IN PIRP					Irp
								   )
{
	NTSTATUS			Status = STATUS_SUCCESS;
	PIO_STACK_LOCATION	irpStack;
	PDEVICE_EXTENSION	deviceExtension;
	PVOID				ioBuf;
	ULONG				inBufLength, outBufLength;
	ULONG				ioControlCode;
	ULONG_PTR			 num=0;

	irpStack = IoGetCurrentIrpStackLocation(Irp);
	deviceExtension = (PDEVICE_EXTENSION)DeviceObject->DeviceExtension;

	Irp->IoStatus.Information = 0;

	//
	// Get the pointer to the input/output buffer and it's length
	//

	ioBuf = Irp->AssociatedIrp.SystemBuffer;
	inBufLength = irpStack->Parameters.DeviceIoControl.InputBufferLength;
	outBufLength = irpStack->Parameters.DeviceIoControl.OutputBufferLength;
	ioControlCode = irpStack->Parameters.DeviceIoControl.IoControlCode;
	// Irp->UserBuffer;		// If METHOD_NEITHER, This is Output Buffer

	switch (ioControlCode)
	{
	case IOCTL_SETUPFW:
		{
			//

			if (g_AlreadyHookTCPIP)
			{
				InterlockedExchange(&g_InterceptTCPIPRcv, 1);
			}
			else
			{
				Status=	FWHookTcpipRecvHandler();
				if (NT_SUCCESS(Status))
				{
					InterlockedExchange(&g_InterceptTCPIPRcv, 1);
					g_AlreadyHookTCPIP	=	1;
				}
			}
			break;
		}
	case IOCTL_UNSETFW:
		{
			//
			InterlockedExchange(&g_InterceptTCPIPRcv, 0);
			//UNHOOK的行为就放到驱动卸载时候了
			break;
		}
	case IOCTL_PENDDINGCHECKPORT:
		{
			//pendding进去
			IoMarkIrpPending(Irp);
			ExInterlockedInsertHeadList(&g_AskUserConnectListHeader, &Irp->Tail.Overlay.ListEntry, &g_AskUserConnectListLock);
			Status= STATUS_PENDING;
			Irp->IoStatus.Status = Status;
			return Status;
			break;
		}
	case IOCTL_SETONEPORTSTATUS:
		{
			Status = SetupPortStatus(ioBuf, 1);
			break;
		}
	case IOCTL_RESPONSEPORTASK:
		{
			Status = ResponsePortAsk((PFIREWALL_ASKUSER)ioBuf);
			break;
		}
	case IOCTL_ReleasePENDDINGCHECKPORT:
		{
			Status = ReleasePenddingCheckPortIrp();
			break;
		}
	case IOCTL_GETPORTSTATUS:
		{
			Status = GetPortRules(ioBuf, &outBufLength);
			if (Status==STATUS_INFO_LENGTH_MISMATCH)
			{
				Status	=	STATUS_SUCCESS;
			}
			Irp->IoStatus.Information	=	outBufLength;
			break;
		}

	default:
		{
			//Status = STATUS_INVALID_PARAMETER;
			kprintf("[SuperCI]  Unknown IOCTL: 0x%X (%04X,%04X)\n",
				ioControlCode, DEVICE_TYPE_FROM_CTL_CODE(ioControlCode),
				IoGetFunctionCodeFromCtlCode(ioControlCode));


			break;
		}
	}


	Irp->IoStatus.Status = Status;
	IoCompleteRequest(Irp, IO_NO_INCREMENT);


	return Status;

}
Пример #18
0
HRESULT __stdcall EnlistmentNotifyShim::PrepareRequest(
    BOOL fRetaining, 
    DWORD grfRM, 
    BOOL fWantMoniker,
    BOOL fSinglePhase
    )
{
    HRESULT hr = S_OK;
    IPrepareInfo* pPrepareInfo = NULL;
    BYTE* prepareInfoBuffer = NULL;
    ULONG prepareInfoLength = 0;
    ITransactionEnlistmentAsync* pEnlistmentAsync = NULL;

#if defined(_X86_)
    pEnlistmentAsync = (ITransactionEnlistmentAsync*)InterlockedExchange((LONG volatile*)&this->pEnlistmentAsync, NULL);
#elif defined(_WIN64)
    pEnlistmentAsync = (ITransactionEnlistmentAsync*)InterlockedExchange64((LONGLONG volatile*)&this->pEnlistmentAsync, NULL);
#endif

    if( pEnlistmentAsync == NULL )
    {
        return E_UNEXPECTED;
    }

    hr = pEnlistmentAsync->QueryInterface(
        IID_IPrepareInfo,
        (void**) &pPrepareInfo
        );
    if ( FAILED( hr ) )
    {
        goto ErrorExit;
    }

    hr = pPrepareInfo->GetPrepareInfoSize( &prepareInfoLength );
    if ( FAILED( hr ) )
    {
        goto ErrorExit;
    }

    // This buffer will be freed by Managed code through the CoTaskMemHandle object that is
    // created when the pointer to this buffer is returned from GetNotification.
    prepareInfoBuffer = (BYTE*) CoTaskMemAlloc( prepareInfoLength );

    hr = pPrepareInfo->GetPrepareInfo( prepareInfoBuffer );
    if ( FAILED( hr ) )
    {
        goto ErrorExit;
    }

    this->prepareInfoSize = prepareInfoLength;
    this->pPrepareInfo = prepareInfoBuffer;
    this->isSinglePhase = fSinglePhase;
    this->notificationType = PrepareRequestNotify;
    this->shimFactory->NewNotification( this );

ErrorExit:

    SafeReleaseInterface( (IUnknown**) &pPrepareInfo );
    // We can now release our pEnlistmentAsync reference.  We don't need it any longer
    // and it causes problems if the app responds to SPC with InDoubt.
    SafeReleaseInterface( (IUnknown**) &pEnlistmentAsync );

    // We only delete the prepareinInfoBuffer if we had an error.
    if ( FAILED( hr ) )
    {
        if ( NULL != prepareInfoBuffer )
        {
            CoTaskMemFree( prepareInfoBuffer );
        }
    }

    return hr;
}
Пример #19
0
 static inline Type exchange(volatile Type& storage, Type value) {
   return static_cast<Type>(InterlockedExchange((long*)&storage, (long)value));
 }
Пример #20
0
void CCastleSiegeSync::ResetTributeMoney()
{
	InterlockedExchange((LPLONG)&this->m_lCastleTributeMoney, 0);
}
Пример #21
0
/*
 * NOTE: this function should be called by the pcap functions that can theoretically
 *       deal with the Tc library for the first time, namely listing the adapters and
 *       opening one. All the other ones (close, read, write, set parameters) work
 *       on an open instance of TC, so we do not care to call this function
 */
TC_API_LOAD_STATUS LoadTcFunctions()
{
	TC_API_LOAD_STATUS currentStatus;

	do
	{
		currentStatus = InterlockedCompareExchange((LONG*)&g_TcFunctions.LoadStatus, TC_API_LOADING, TC_API_UNLOADED);

		while(currentStatus == TC_API_LOADING)
		{
			currentStatus = InterlockedCompareExchange((LONG*)&g_TcFunctions.LoadStatus, TC_API_LOADING, TC_API_LOADING);
			Sleep(10);
		}
		
		/*
		 * at this point we are either in the LOADED state, unloaded state (i.e. we are the ones loading everything)
		 * or in cannot load
		 */
		if(currentStatus  == TC_API_LOADED)
		{
			return TC_API_LOADED;
		}
		
		if (currentStatus == TC_API_CANNOT_LOAD)
		{
			return TC_API_CANNOT_LOAD;
		}

		currentStatus = TC_API_CANNOT_LOAD;

		g_TcFunctions.hTcApiDllHandle = LoadLibrarySafe("TcApi.dll");
		if (g_TcFunctions.hTcApiDllHandle == NULL)	break;

		g_TcFunctions.QueryPortList					= (TcFcnQueryPortList)			GetProcAddress(g_TcFunctions.hTcApiDllHandle, "TcQueryPortList");
		g_TcFunctions.FreePortList					= (TcFcnFreePortList)			GetProcAddress(g_TcFunctions.hTcApiDllHandle, "TcFreePortList");

		g_TcFunctions.StatusGetString				= (TcFcnStatusGetString)		GetProcAddress(g_TcFunctions.hTcApiDllHandle, "TcStatusGetString");

		g_TcFunctions.PortGetName					= (TcFcnPortGetName)			GetProcAddress(g_TcFunctions.hTcApiDllHandle, "TcPortGetName");
		g_TcFunctions.PortGetDescription			= (TcFcnPortGetDescription)		GetProcAddress(g_TcFunctions.hTcApiDllHandle, "TcPortGetDescription");

		g_TcFunctions.InstanceOpenByName			= (TcFcnInstanceOpenByName)		GetProcAddress(g_TcFunctions.hTcApiDllHandle, "TcInstanceOpenByName");
		g_TcFunctions.InstanceClose					= (TcFcnInstanceClose)			GetProcAddress(g_TcFunctions.hTcApiDllHandle, "TcInstanceClose");
		g_TcFunctions.InstanceSetFeature			= (TcFcnInstanceSetFeature)		GetProcAddress(g_TcFunctions.hTcApiDllHandle, "TcInstanceSetFeature");
		g_TcFunctions.InstanceQueryFeature			= (TcFcnInstanceQueryFeature)	GetProcAddress(g_TcFunctions.hTcApiDllHandle, "TcInstanceQueryFeature");
		g_TcFunctions.InstanceReceivePackets		= (TcFcnInstanceReceivePackets)	GetProcAddress(g_TcFunctions.hTcApiDllHandle, "TcInstanceReceivePackets");
		g_TcFunctions.InstanceGetReceiveWaitHandle	= (TcFcnInstanceGetReceiveWaitHandle)GetProcAddress(g_TcFunctions.hTcApiDllHandle, "TcInstanceGetReceiveWaitHandle");
		g_TcFunctions.InstanceTransmitPackets		= (TcFcnInstanceTransmitPackets)GetProcAddress(g_TcFunctions.hTcApiDllHandle, "TcInstanceTransmitPackets");
		g_TcFunctions.InstanceQueryStatistics		= (TcFcnInstanceQueryStatistics)GetProcAddress(g_TcFunctions.hTcApiDllHandle, "TcInstanceQueryStatistics");

		g_TcFunctions.PacketsBufferCreate			= (TcFcnPacketsBufferCreate)	GetProcAddress(g_TcFunctions.hTcApiDllHandle, "TcPacketsBufferCreate");
		g_TcFunctions.PacketsBufferDestroy			= (TcFcnPacketsBufferDestroy)	GetProcAddress(g_TcFunctions.hTcApiDllHandle, "TcPacketsBufferDestroy");
		g_TcFunctions.PacketsBufferQueryNextPacket	= (TcFcnPacketsBufferQueryNextPacket)GetProcAddress(g_TcFunctions.hTcApiDllHandle, "TcPacketsBufferQueryNextPacket");
		g_TcFunctions.PacketsBufferCommitNextPacket	= (TcFcnPacketsBufferCommitNextPacket)GetProcAddress(g_TcFunctions.hTcApiDllHandle, "TcPacketsBufferCommitNextPacket");

		g_TcFunctions.StatisticsDestroy				= (TcFcnStatisticsDestroy)		GetProcAddress(g_TcFunctions.hTcApiDllHandle, "TcStatisticsDestroy");
		g_TcFunctions.StatisticsUpdate				= (TcFcnStatisticsUpdate)		GetProcAddress(g_TcFunctions.hTcApiDllHandle, "TcStatisticsUpdate");
		g_TcFunctions.StatisticsQueryValue			= (TcFcnStatisticsQueryValue)	GetProcAddress(g_TcFunctions.hTcApiDllHandle, "TcStatisticsQueryValue");

		if (   g_TcFunctions.QueryPortList == NULL
			|| g_TcFunctions.FreePortList == NULL
			|| g_TcFunctions.StatusGetString == NULL
			|| g_TcFunctions.PortGetName == NULL
			|| g_TcFunctions.PortGetDescription == NULL
			|| g_TcFunctions.InstanceOpenByName == NULL
			|| g_TcFunctions.InstanceClose == NULL
			|| g_TcFunctions.InstanceSetFeature	 == NULL
			|| g_TcFunctions.InstanceQueryFeature == NULL
			|| g_TcFunctions.InstanceReceivePackets == NULL
			|| g_TcFunctions.InstanceGetReceiveWaitHandle == NULL
			|| g_TcFunctions.InstanceTransmitPackets == NULL
			|| g_TcFunctions.InstanceQueryStatistics == NULL
			|| g_TcFunctions.PacketsBufferCreate == NULL
			|| g_TcFunctions.PacketsBufferDestroy == NULL
			|| g_TcFunctions.PacketsBufferQueryNextPacket == NULL
			|| g_TcFunctions.PacketsBufferCommitNextPacket == NULL
			|| g_TcFunctions.StatisticsDestroy == NULL
			|| g_TcFunctions.StatisticsUpdate == NULL
			|| g_TcFunctions.StatisticsQueryValue == NULL
		)
		{
			break;
		}

		/*
		 * everything got loaded, yay!!
		 */
		currentStatus = TC_API_LOADED;
	}while(FALSE);

	if (currentStatus != TC_API_LOADED)
	{
		if (g_TcFunctions.hTcApiDllHandle != NULL)
		{
			FreeLibrary(g_TcFunctions.hTcApiDllHandle);
			g_TcFunctions.hTcApiDllHandle = NULL;
		}
	}

	InterlockedExchange((LONG*)&g_TcFunctions.LoadStatus, currentStatus);

	return currentStatus;
}
Пример #22
0
DWORD
WINAPI
MixerThreadRoutine(
    LPVOID lpParameter)
{
    KSPROPERTY Request;
    KSAUDIO_POSITION Position;
    DWORD Result, MixPosition, BufferPosition, BytesWritten, BytesRead, MixLength, BufferLength;
    LPCDirectSoundCaptureBufferImpl This = (LPCDirectSoundCaptureBufferImpl)lpParameter;

    /* setup audio position property request */
    Request.Id = KSPROPERTY_AUDIO_POSITION;
    Request.Set = KSPROPSETID_Audio;
    Request.Flags = KSPROPERTY_TYPE_GET;

    MixPosition = 0;
    BufferPosition = 0;
    do
    {
        /* query current position */
        Result = SyncOverlappedDeviceIoControl(This->hPin, IOCTL_KS_PROPERTY, (PVOID)&Request, sizeof(KSPROPERTY), (PVOID)&Position, sizeof(KSAUDIO_POSITION), NULL);

        /* sanity check */
        ASSERT(Result == ERROR_SUCCESS);

        /* FIXME implement samplerate conversion */
        ASSERT(This->MixFormat.nSamplesPerSec == This->Format->nSamplesPerSec);

        /* FIXME implement bitrate conversion */
        ASSERT(This->MixFormat.wBitsPerSample == This->Format->wBitsPerSample);

        /* sanity check */
        ASSERT(BufferPosition <= This->BufferSize);
        ASSERT(MixPosition  <= This->MixBufferSize);

        if (BufferPosition == This->BufferSize)
        {
            /* restart from front */
            BufferPosition = 0;
        }

        if (MixPosition == This->MixBufferSize)
        {
            /* restart from front */
            MixPosition = 0;
        }

        if (This->MixFormat.nChannels != This->Format->nChannels)
        {
            if ((DWORD)Position.PlayOffset >= MixPosition)
            {
                /* calculate buffer position difference */
                MixLength = Position.PlayOffset - MixPosition;
            }
            else
            {
                /* buffer overlap */
                MixLength = This->MixBufferSize - MixPosition;
            }

            BufferLength = This->BufferSize - BufferPosition;

            /* convert the format */
            PerformChannelConversion(&This->MixBuffer[MixPosition], MixLength, &BytesRead, This->MixFormat.nChannels, This->Format->nChannels, This->Format->wBitsPerSample, &This->Buffer[BufferPosition], BufferLength, &BytesWritten);

            /* update buffer offsets */
            MixPosition += BytesRead;
            BufferPosition += BytesWritten;
            DPRINT("MixPosition %u BufferPosition %u BytesRead %u BytesWritten %u MixLength %u BufferLength %u\n", MixPosition, BufferPosition, BytesRead, BytesWritten, MixLength, BufferLength);
        }

        /* Notify Events */
        if (This->Notify)
        {
            DoNotifyPositionEvents(This->Notify, This->CurrentMixPosition, BufferPosition);
        }

        /* update offset */
        InterlockedExchange(&This->CurrentMixPosition, (LONG)BufferPosition);

        /* FIXME use timer */
        Sleep(10);

    }while(InterlockedCompareExchange(&This->StopMixerThread, 0, 0) == 0);


    /* signal stop event */
    SetEvent(This->hStopEvent);

    /* done */
    return 0;
}
Пример #23
0
int _spin_lite_trylock(spin_t *l)
{
    CHECK_SPINLOCK_LITE(l);
    return InterlockedExchange(&l->l, EBUSY);
}
Пример #24
0
/*
 * This may be called from DllMain, and hence operates under unusual
 * constraints.
 */
static GC_thread GC_new_thread(void) {
  int i;
  /* It appears to be unsafe to acquire a lock here, since this	*/
  /* code is apparently not preeemptible on some systems.	*/
  /* (This is based on complaints, not on Microsoft's official	*/
  /* documentation, which says this should perform "only simple	*/
  /* initialization tasks".)					*/
  /* Hence we make do with nonblocking synchronization.		*/

  /* The following should be a noop according to the win32	*/
  /* documentation.  There is empirical evidence that it	*/
  /* isn't.		- HB					*/
# if defined(MPROTECT_VDB)
   if (GC_incremental) SetUnhandledExceptionFilter(GC_write_fault_handler);
# endif
                /* cast away volatile qualifier */
  for (i = 0; InterlockedExchange((IE_t)&thread_table[i].in_use,1) != 0; i++) {
    /* Compare-and-swap would make this cleaner, but that's not 	*/
    /* supported before Windows 98 and NT 4.0.  In Windows 2000,	*/
    /* InterlockedExchange is supposed to be replaced by		*/
    /* InterlockedExchangePointer, but that's not really what I		*/
    /* want here.							*/
    if (i == MAX_THREADS - 1)
      ABORT("too many threads");
  }
  /* Update GC_max_thread_index if necessary.  The following is safe,	*/
  /* and unlike CompareExchange-based solutions seems to work on all	*/
  /* Windows95 and later platforms.					*/
  /* Unfortunately, GC_max_thread_index may be temporarily out of 	*/
  /* bounds, so readers have to compensate.				*/
  while (i > GC_max_thread_index) {
    InterlockedIncrement((IE_t)&GC_max_thread_index);
  }
  if (GC_max_thread_index >= MAX_THREADS) {
    /* We overshot due to simultaneous increments.	*/
    /* Setting it to MAX_THREADS-1 is always safe.	*/
    GC_max_thread_index = MAX_THREADS - 1;
  }
  
# ifdef CYGWIN32
    thread_table[i].pthread_id = pthread_self();
# endif
  if (!DuplicateHandle(GetCurrentProcess(),
	               GetCurrentThread(),
		       GetCurrentProcess(),
		       (HANDLE*)&thread_table[i].handle,
		       0,
		       0,
		       DUPLICATE_SAME_ACCESS)) {
	DWORD last_error = GetLastError();
	GC_printf1("Last error code: %lx\n", last_error);
	ABORT("DuplicateHandle failed");
  }
  thread_table[i].stack_base = GC_get_stack_base();
  /* Up until this point, GC_push_all_stacks considers this thread	*/
  /* invalid.								*/
  if (thread_table[i].stack_base == NULL) 
    ABORT("Failed to find stack base in GC_new_thread");
  /* Up until this point, this entry is viewed as reserved but invalid	*/
  /* by GC_delete_thread.						*/
  thread_table[i].id = GetCurrentThreadId();
  /* If this thread is being created while we are trying to stop	*/
  /* the world, wait here.  Hopefully this can't happen on any	*/
  /* systems that don't allow us to block here.			*/
  while (GC_please_stop) Sleep(20);
  return thread_table + i;
}
Пример #25
0
VOID
DCamCancelOnePacket(
    IN PHW_STREAM_REQUEST_BLOCK pSrbToCancel
    )
/*++

Routine Description:

    This routine is called to cancel a pending streaming SRB.  This is likely to
    happen when transitioning from PAUSE to STOP state.
    Note: This routine is called at DISPATCH_LEVEL !! so we queue a work item
    to cancel pending requests at the passive level.

Arguments:

    pSrbToCancel - Pointer to SRB to cancel

Return Value:

    None.

--*/
{
    PDCAM_EXTENSION pDevExt;
    PSTREAMEX       pStrmEx;
    PIO_WORKITEM pIOWorkItem;


    pDevExt = (PDCAM_EXTENSION) pSrbToCancel->HwDeviceExtension;
    ASSERT(pDevExt);
    pStrmEx = (PSTREAMEX) pDevExt->pStrmEx;
    ASSERT(pStrmEx);

    // Nothing to cancel
    if(pStrmEx == NULL) {
        return;
    }


    //
    // Can cancel stream SRB as a result of aborting a stream.
    //
    if ( (pSrbToCancel->Flags & SRB_HW_FLAGS_STREAM_REQUEST) != SRB_HW_FLAGS_STREAM_REQUEST) {
        ERROR_LOG(("DCamCancelOnePacket: Cannot cancel Device SRB %p\n", pSrbToCancel));
        ASSERT( (pSrbToCancel->Flags & SRB_HW_FLAGS_STREAM_REQUEST) == SRB_HW_FLAGS_STREAM_REQUEST );
        return;
    }

    //
    // Abort only once so we must obtain the token first.
    //
    if( InterlockedExchange((PLONG)&pStrmEx->CancelToken, 1 ) == 1 ) {
        // Already in cancelling state!
        ERROR_LOG( ( "Already cancelling...\n" ) );
        return;
    }

    //
    // Start a work item to cancel all pending request
    //
    pIOWorkItem = IoAllocateWorkItem( pDevExt ->PhysicalDeviceObject );

    if( !pIOWorkItem ) {
        // Could not do it, release the token.
        InterlockedExchange((PLONG)&pStrmEx->CancelToken, 0 );
        return;
    }
    else {
        IoQueueWorkItem( pIOWorkItem, AbortWorkItem, DelayedWorkQueue, pDevExt );
    }
}
Пример #26
0
PRECORD_LIST
SpyNewRecord (
    VOID
    )
/*++

Routine Description:

    Allocates a new RECORD_LIST structure if there is enough memory to do so. A
    sequence number is updated for each request for a new record.

    NOTE:  This code must be NON-PAGED because it can be called on the
           paging path or at DPC level.

Arguments:

    None

Return Value:

    Pointer to the RECORD_LIST allocated, or NULL if no memory is available.

--*/
{
    PRECORD_LIST newRecord;
    ULONG initialRecordType;

    //
    //  Allocate the buffer
    //

    newRecord = SpyAllocateBuffer( &initialRecordType );

    if (newRecord == NULL) {

        //
        //  We could not allocate a record, see if the static buffer is
        //  in use.  If not, we will use it
        //

        if (!InterlockedExchange( &MiniSpyData.StaticBufferInUse, TRUE )) {

            newRecord = (PRECORD_LIST)MiniSpyData.OutOfMemoryBuffer;
            initialRecordType |= RECORD_TYPE_FLAG_STATIC;
        }
    }

    //
    //  If we got a record (doesn't matter if it is static or not), init it
    //

    if (newRecord != NULL) {

        //
        // Init the new record
        //

        newRecord->LogRecord.RecordType = initialRecordType;
        newRecord->LogRecord.Length = sizeof(LOG_RECORD);
        newRecord->LogRecord.SequenceNumber = InterlockedIncrement( &MiniSpyData.LogSequenceNumber );
        RtlZeroMemory( &newRecord->LogRecord.Data, sizeof( RECORD_DATA ) );
    }

    return( newRecord );
}
Пример #27
0
AtomicCounter& AtomicCounter::operator = (const AtomicCounter& counter)
{
	InterlockedExchange(&_counter, counter.value());
	return *this;
}
Пример #28
0
int GitRev::SafeGetSimpleList(CGit *git)
{
	if(InterlockedExchange(&m_IsUpdateing,TRUE) == FALSE)
	{
		m_SimpleFileList.clear();
		git->CheckAndInitDll();
		GIT_COMMIT commit;
		GIT_COMMIT_LIST list;
		GIT_HASH   parent;
		memset(&commit,0,sizeof(GIT_COMMIT));

		CAutoLocker lock(g_Git.m_critGitDllSec);

		try
		{
			if(git_get_commit_from_hash(&commit, this->m_CommitHash.m_hash))
				return -1;
		}
		catch (char *)
		{
			return -1;
		}

		int i=0;
		bool isRoot = this->m_ParentHash.empty();
		git_get_commit_first_parent(&commit,&list);
		while(git_get_commit_next_parent(&list,parent) == 0 || isRoot)
		{
			GIT_FILE file=0;
			int count=0;
			try
			{
				if(isRoot)
					git_root_diff(git->GetGitSimpleListDiff(), commit.m_hash, &file, &count, 0);
				else
					git_diff(git->GetGitSimpleListDiff(), parent, commit.m_hash, &file, &count, 0);
			}
			catch (char *)
			{
				return -1;
			}

			isRoot = false;

			CTGitPath path;
			CString strnewname;
			CString stroldname;

			for (int j = 0; j < count; ++j)
			{
				path.Reset();
				char *newname;
				char *oldname;

				strnewname.Empty();
				stroldname.Empty();

				int mode,IsBin,inc,dec;
				try
				{
					git_get_diff_file(git->GetGitSimpleListDiff(), file, j, &newname, &oldname, &mode, &IsBin, &inc, &dec);
				}
				catch (char *)
				{
					return -1;
				}

				git->StringAppend(&strnewname, (BYTE*)newname, CP_UTF8);

				m_SimpleFileList.push_back(strnewname);

			}
			git_diff_flush(git->GetGitSimpleListDiff());
			++i;
		}

		InterlockedExchange(&m_IsUpdateing,FALSE);
		InterlockedExchange(&m_IsSimpleListReady, TRUE);
		git_free_commit(&commit);
	}

	return 0;
}
Пример #29
0
UINT CImportPatchDlg::PatchThread()
{
	CTGitPath path;
	path.SetFromWin(g_Git.m_CurrentDir);

	int i=0;
	UpdateOkCancelText();
	for (i = m_CurrentItem; i < m_cList.GetItemCount(); ++i)
	{
		if (m_pTaskbarList)
		{
			m_pTaskbarList->SetProgressState(m_hWnd, TBPF_NORMAL);
			m_pTaskbarList->SetProgressValue(m_hWnd, i, m_cList.GetItemCount());
		}

		m_cList.SetItemData(i, CPatchListCtrl::STATUS_APPLYING|m_cList.GetItemData(i));

		CRect rect;
		this->m_cList.GetItemRect(i,&rect,LVIR_BOUNDS);
		this->m_cList.InvalidateRect(rect);

		if(m_bExitThread)
			break;

		if(m_cList.GetCheck(i))
		{
			CString cmd;

			while(path.HasRebaseApply())
			{
				if (m_pTaskbarList)
					m_pTaskbarList->SetProgressState(m_hWnd, TBPF_ERROR);

				int ret = CMessageBox::Show(NULL, IDS_PROC_APPLYPATCH_REBASEDIRFOUND,
												  IDS_APPNAME,
												   1, IDI_ERROR, IDS_ABORTBUTTON, IDS_SKIPBUTTON, IDS_RESOLVEDBUTTON);

				switch(ret)
				{
				case 1:
					cmd = _T("git.exe am --abort");
					break;
				case 2:
					cmd = _T("git.exe am --skip");
					++i;
					break;
				case 3:
					cmd = _T("git.exe am --resolved");
					break;
				default:
					cmd.Empty();
				}
				if(cmd.IsEmpty())
				{
					m_bExitThread = TRUE;
					break;
				}

				this->AddLogString(cmd);
				CString output;
				if (g_Git.Run(cmd, &output, CP_UTF8))
				{
					this->AddLogString(output);
					this->AddLogString(CString(MAKEINTRESOURCE(IDS_FAIL)));
				}
				else
				{
					this->AddLogString(CString(MAKEINTRESOURCE(IDS_DONE)));
				}
			}

			if(m_bExitThread)
				break;

			cmd = _T("git.exe am ");

			if(this->m_bAddSignedOffBy)
				cmd += _T("--signoff ");

			if(this->m_b3Way)
				cmd += _T("--3way ");

			if(this->m_bIgnoreSpace)
				cmd += _T("--ignore-space-change ");

			if(this->m_bKeepCR)
				cmd += _T("--keep-cr ");

			cmd += _T("\"");
			cmd += m_cList.GetItemText(i,0);
			cmd += _T("\"");

			this->AddLogString(cmd);
			CString output;
			if (g_Git.Run(cmd, &output, CP_UTF8))
			{
				//keep STATUS_APPLYING to let user retry failed patch
				m_cList.SetItemData(i, CPatchListCtrl::STATUS_APPLY_FAIL|CPatchListCtrl::STATUS_APPLYING);
				this->AddLogString(output);
				this->AddLogString(CString(MAKEINTRESOURCE(IDS_FAIL)));
				if (m_pTaskbarList)
					m_pTaskbarList->SetProgressState(m_hWnd, TBPF_ERROR);
				break;

			}
			else
			{
				m_cList.SetItemData(i,  CPatchListCtrl::STATUS_APPLY_SUCCESS);
				this->AddLogString(CString(MAKEINTRESOURCE(IDS_SUCCESS)));
			}

		}
		else
		{
			CString sMessage;
			sMessage.Format(IDS_PROC_SKIPPATCH, m_cList.GetItemText(i,0));
			AddLogString(sMessage);
			m_cList.SetItemData(i, CPatchListCtrl::STATUS_APPLY_SKIP);
		}

		m_cList.SetItemData(m_CurrentItem, (~CPatchListCtrl::STATUS_APPLYING)&m_cList.GetItemData(i));
		++m_CurrentItem;

		this->m_cList.GetItemRect(i,&rect,LVIR_BOUNDS);
		this->m_cList.InvalidateRect(rect);

		UpdateOkCancelText();
	}

	//in case am fail, need refresh finial item status
	CRect rect;
	this->m_cList.GetItemRect(i,&rect,LVIR_BOUNDS);
	this->m_cList.InvalidateRect(rect);

	this->m_cList.GetItemRect(m_CurrentItem,&rect,LVIR_BOUNDS);
	this->m_cList.InvalidateRect(rect);

	if (m_pTaskbarList)
	{
		m_pTaskbarList->SetProgressValue(m_hWnd, m_CurrentItem, m_cList.GetItemCount());
		if (m_bExitThread && m_CurrentItem != m_cList.GetItemCount())
			m_pTaskbarList->SetProgressState(m_hWnd, TBPF_PAUSED);
		else if (!m_bExitThread && m_CurrentItem == m_cList.GetItemCount())
			m_pTaskbarList->SetProgressState(m_hWnd, TBPF_NORMAL);
	}

	EnableInputCtrl(true);
	InterlockedExchange(&m_bThreadRunning, FALSE);
	UpdateOkCancelText();
	return 0;
}
Пример #30
0
BOOL AudioStream::ServiceBuffer(void)
{
	long vol;
	int fRtn = TRUE;

	if (status != ASF_USED)
		return FALSE;

	ENTER_CRITICAL_SECTION(write_lock);

	// status may have changed, so lets check once again
	if (status != ASF_USED)
	{
		LEAVE_CRITICAL_SECTION(write_lock);
		return FALSE;
	}

	// Check for reentrance
	if (InterlockedExchange(&m_lInService, TRUE) == FALSE)
	{
		if (m_bFade == TRUE)
		{
			if (m_lCutoffVolume == -10000)
			{
				vol = Get_Volume();
				//				nprintf(("Alan","Volume is: %d\n",vol));
				m_lCutoffVolume = MAX(vol - VOLUME_ATTENUATION_BEFORE_CUTOFF, -10000);
			}

			vol = Get_Volume();
			vol = vol - FADE_VOLUME_INTERVAL;	// decrease by 1db
			//			nprintf(("Alan","Volume is now: %d\n",vol));
			Set_Volume(vol);

			//			nprintf(("Sound","SOUND => Volume for stream sound is %d\n",vol));
			//			nprintf(("Alan","Cuttoff Volume is: %d\n",m_lCutoffVolume));
			if (vol < m_lCutoffVolume)
			{
				m_bFade = 0;
				m_lCutoffVolume = -10000;
				if (m_bDestroy_when_faded == TRUE)
				{
					LEAVE_CRITICAL_SECTION(write_lock);
					Destroy();
					// Reset reentrancy semaphore
					InterlockedExchange(&m_lInService, FALSE);
					return FALSE;
				}
				else
				{
					Stop_and_Rewind();
					// Reset reentrancy semaphore
					LEAVE_CRITICAL_SECTION(write_lock);
					InterlockedExchange(&m_lInService, FALSE);
					return TRUE;
				}
			}
		}

		// All of sound not played yet, send more data to buffer
		DWORD dwFreeSpace = GetMaxWriteSize();

		// Determine free space in sound buffer
		if (dwFreeSpace)
		{

			// Some wave data remains, but not enough to fill free space
			// Send wave data to buffer, fill remainder of free space with silence
			uint num_bytes_written;

			if (WriteWaveData(dwFreeSpace, &num_bytes_written) == SUCCESS)
			{
				//				nprintf(("Alan","Num bytes written: %d\n", num_bytes_written));

				if (m_pwavefile->m_total_uncompressed_bytes_read >= m_pwavefile->m_max_uncompressed_bytes_to_read)
				{
					m_fade_timer_id = timer_get_milliseconds() + 1700;		// start fading 1.7 seconds from now
					m_finished_id = timer_get_milliseconds() + 2000;		// 2 seconds left to play out buffer
					m_pwavefile->m_max_uncompressed_bytes_to_read = AS_HIGHEST_MAX;
				}

				if ((m_fade_timer_id > 0) && ((uint)timer_get_milliseconds() > m_fade_timer_id))
				{
					m_fade_timer_id = 0;
					Fade_and_Stop();
				}

				if ((m_finished_id > 0) && ((uint)timer_get_milliseconds() > m_finished_id))
				{
					m_finished_id = 0;
					m_bPastLimit = TRUE;
				}

				if ((num_bytes_written < dwFreeSpace) && m_bReadingDone)
				{
					int num_bytes_silence;
					num_bytes_silence = dwFreeSpace - num_bytes_written;

					if (num_bytes_silence > 0)
					{

						m_silence_written += num_bytes_silence;
						if (WriteSilence(num_bytes_silence) == FAILURE)
						{
							fRtn = FALSE;
							Int3();
						}

						if (m_silence_written >= m_cbBufSize)
						{
							m_silence_written = 0;

							if (m_bDestroy_when_faded == TRUE)
							{
								LEAVE_CRITICAL_SECTION(write_lock);
								Destroy();
								// Reset reentrancy semaphore
								InterlockedExchange(&m_lInService, FALSE);
								return FALSE;
							}

							// All of sound has played, stop playback or loop again
							if (m_bLooping && !m_bFade)
							{
								Play(m_lVolume, m_bLooping);
							}
							else
							{
								Stop_and_Rewind();
							}
						}
					}
				}
			}
			else
			{
				// Error writing wave data
				fRtn = FALSE;
				Int3();
			}
		}

		// Reset reentrancy semaphore
		InterlockedExchange(&m_lInService, FALSE);
	}
	else
	{
		// Service routine reentered. Do nothing, just return
		fRtn = FALSE;
	}

	LEAVE_CRITICAL_SECTION(write_lock);
	return (fRtn);
}