Exemplo n.º 1
0
VOID UsbDev::CancelSelectiveSuspend()
{
	PIRP Irp;
	LARGE_INTEGER timeout;
	KIRQL oldIrql;
	DBGU_TRACE("CancelSelectiveSuspend()\n");
	//test
	//Irp = (PIRP)InterlockedExchangePointer((PVOID *)&m_SuspendIrp, NULL);

	timeout.QuadPart = -600000000; //60 sec
	
	KeAcquireSpinLock(&IdleReqStateLock, &oldIrql);
	
	if (m_SuspendIrp)//(Irp)
	{
   		KeInitializeEvent(&m_SuspendIrpCancelEvent, SynchronizationEvent, FALSE);
		DBGU_TRACE("IoCancelIrp(Irp)\n");
		IoCancelIrp(m_SuspendIrp);
		KeReleaseSpinLock(&IdleReqStateLock, oldIrql);
		// waiting for IRP been cancelled.
		KeWaitForSingleObject(
			&m_SuspendIrpCancelEvent,
			Executive,
			KernelMode,
			FALSE,
			&timeout);//NULL);
		DBGU_TRACE("IoCancelIrp(Irp) Complete\n");	
	}
	else
		KeReleaseSpinLock(&IdleReqStateLock, oldIrql);
}
Exemplo n.º 2
0
VOID CancelSelectSuspend(IN PTDeviceExtension DeviceExtension)
{
    PIRP  irp;
    KIRQL oldIrql;

    irp = NULL;
    BulkUsb_DbgPrint(3, ("file bulkdev: CancelSelectSuspend - begins\n"));
    KeAcquireSpinLock(&DeviceExtension->IdleReqStateLock, &oldIrql);
    if(!CanDeviceSuspend(DeviceExtension))
    {
        BulkUsb_DbgPrint(3, ("file bulkdev: Device is not idle\n"));
        irp = (PIRP)InterlockedExchangePointer(&DeviceExtension->PendingIdleIrp, NULL);
    }

    KeReleaseSpinLock(&DeviceExtension->IdleReqStateLock, oldIrql);
    if(irp) 
	{
		IoCancelIrp(irp);
        if(0 == InterlockedDecrement(&DeviceExtension->FreeIdleIrpCount)) 
		{
            BulkUsb_DbgPrint(3, ("file bulkdev: CancelSelectSuspend frees the irp\n"));
            IoFreeIrp(irp);
            KeSetEvent(&DeviceExtension->NoIdleReqPendEvent, IO_NO_INCREMENT, FALSE);
        }
    }

    BulkUsb_DbgPrint(3, ("file bulkdev: CancelSelectSuspend - ends\n"));
    return;
}
Exemplo n.º 3
0
//-----------------------------------------------------------------------------
// Name: CancelPendingIrp
// Object: release pending IRP.
// Parameters :
//     in  : 
//     out :
//     return : 
//-----------------------------------------------------------------------------
VOID CancelPendingIrp()
{
    KeWaitForSingleObject(&hevt_g_PendingIrpUnlocked,Executive,KernelMode,FALSE,NULL);
    if (g_PendingIrp)
        IoCancelIrp(g_PendingIrp);

    KeSetEvent(&hevt_g_PendingIrpUnlocked,IO_NO_INCREMENT,FALSE);
}
Exemplo n.º 4
0
NTSTATUS EVhdCancelMetaOperation(MetaOperation *pOperation)
{
	if (pOperation->pIrp)
		IoCancelIrp(pOperation->pIrp);

	// TODO: Originally returns VOID?
	return STATUS_SUCCESS;
}
Exemplo n.º 5
0
FORCEINLINE
BOOLEAN
FxIrp::Cancel(
    VOID
    )
{
    return IoCancelIrp(m_Irp);
}
Exemplo n.º 6
0
NTSTATUS call_usbd(libusb_device_t *dev, void *urb, ULONG control_code,  
                   int timeout)
{
  KEVENT event;
  NTSTATUS status;
  IRP *irp;
  IO_STACK_LOCATION *next_irp_stack;
  LARGE_INTEGER _timeout;
  IO_STATUS_BLOCK io_status;

  if(timeout > LIBUSB_MAX_CONTROL_TRANSFER_TIMEOUT)
    {
      timeout = LIBUSB_MAX_CONTROL_TRANSFER_TIMEOUT;
    }

  KeInitializeEvent(&event, NotificationEvent, FALSE);

  irp = IoBuildDeviceIoControlRequest(control_code, dev->target_device,
                                      NULL, 0, NULL, 0, TRUE,
                                      NULL, &io_status);

  if(!irp)
    {
      return STATUS_NO_MEMORY;
    }

  next_irp_stack = IoGetNextIrpStackLocation(irp);
  next_irp_stack->Parameters.Others.Argument1 = urb;
  next_irp_stack->Parameters.Others.Argument2 = NULL;

  IoSetCompletionRoutine(irp, on_usbd_complete, &event, TRUE, TRUE, TRUE); 

  status = IoCallDriver(dev->target_device, irp);
    
  if(status == STATUS_PENDING)
    {
      _timeout.QuadPart = -(timeout * 10000);
      
      if(KeWaitForSingleObject(&event, Executive, KernelMode,
                               FALSE, &_timeout) == STATUS_TIMEOUT)
        {
          DEBUG_ERROR("call_usbd(): request timed out");
          IoCancelIrp(irp);
        }
    }

  /* wait until completion routine is called */
  KeWaitForSingleObject(&event, Executive, KernelMode, FALSE, NULL);

  status = irp->IoStatus.Status;
  
  /* complete the request */
  IoCompleteRequest(irp, IO_NO_INCREMENT);

  return status;
}
Exemplo n.º 7
0
/* !!!NOTE: the caller MUST be the IRP owner!!! *
 * !! one can not post threaded IRPs this way!! */
VBOXDRVTOOL_DECL(NTSTATUS) VBoxDrvToolIoPostSyncWithTimeout(PDEVICE_OBJECT pDevObj, PIRP pIrp, ULONG dwTimeoutMs)
{
    KEVENT Event;
    LOG(("post irp (0x%p) to DevObj(0x%p) with timeout (%u)", pIrp, pDevObj, dwTimeoutMs));

    KeInitializeEvent(&Event, NotificationEvent, FALSE);
    NTSTATUS Status = VBoxDrvToolIoPostAsync(pDevObj, pIrp, &Event);
    if (Status == STATUS_PENDING)
    {
        LARGE_INTEGER Interval;
        PLARGE_INTEGER pInterval = NULL;
        if (dwTimeoutMs != RT_INDEFINITE_WAIT)
        {
            Interval.QuadPart = -(int64_t) dwTimeoutMs /* ms */ * 10000;
            pInterval = &Interval;
        }

        Status = KeWaitForSingleObject(&Event, Executive, KernelMode, FALSE, pInterval);
        if (Status == STATUS_TIMEOUT)
        {
            WARN(("irp (0x%p) to DevObj(0x%p) was not completed within timeout (%u), cancelling", pIrp, pDevObj, dwTimeoutMs));
            if (!IoCancelIrp(pIrp))
            {
                /* this may happen, but this is something the caller with timeout is not expecting */
                WARN(("IoCancelIrp failed"));
            }

            /* wait for the IRP to complete */
            KeWaitForSingleObject(&Event, Executive, KernelMode, FALSE, NULL);
        }
        else
        {
            ASSERT_WARN(Status == STATUS_SUCCESS, ("uunexpected Status (0x%x)", Status));
        }

        /* by this time the IRP is completed */
        Status = pIrp->IoStatus.Status;
        LOG(("Pending IRP(0x%p) completed with status(0x%x)", pIrp, Status));
    }
    else
    {
        LOG(("IRP(0x%p) completed with status(0x%x)", pIrp, Status));
    }
    return Status;
}
Exemplo n.º 8
0
Arquivo: read.c Projeto: GYGit/reactos
static NTSTATUS STDCALL read_data_completion(PDEVICE_OBJECT DeviceObject, PIRP Irp, PVOID conptr) {
    read_data_stripe* stripe = conptr;
    read_data_context* context = (read_data_context*)stripe->context;
    UINT64 i;
    BOOL complete;
    
    if (stripe->status == ReadDataStatus_Cancelling) {
        stripe->status = ReadDataStatus_Cancelled;
        goto end;
    }
    
    stripe->iosb = Irp->IoStatus;
    
    if (NT_SUCCESS(Irp->IoStatus.Status)) {
        // FIXME - calculate and compare checksum
        
        stripe->status = ReadDataStatus_Success;
            
        for (i = 0; i < context->num_stripes; i++) {
            if (context->stripes[i].status == ReadDataStatus_Pending) {
                context->stripes[i].status = ReadDataStatus_Cancelling;
                IoCancelIrp(context->stripes[i].Irp);
            }
        }
            
        goto end;
    } else {
        stripe->status = ReadDataStatus_Error;
    }
    
end:
    complete = TRUE;
        
    for (i = 0; i < context->num_stripes; i++) {
        if (context->stripes[i].status == ReadDataStatus_Pending || context->stripes[i].status == ReadDataStatus_Cancelling) {
            complete = FALSE;
            break;
        }
    }
    
    if (complete)
        KeSetEvent(&context->Event, 0, FALSE);

    return STATUS_MORE_PROCESSING_REQUIRED;
}
Exemplo n.º 9
0
VOID
NTAPI
USBH_HubCancelWakeIrp(IN PUSBHUB_FDO_EXTENSION HubExtension,
                      IN PIRP Irp)
{
    DPRINT("USBH_HubCancelWakeIrp: HubExtension - %p, Irp - %p\n",
           HubExtension,
           Irp);

    IoCancelIrp(Irp);

    if (InterlockedExchange((PLONG)&HubExtension->FdoWaitWakeLock, 1))
    {
        PoStartNextPowerIrp(Irp);
        Irp->IoStatus.Status = STATUS_CANCELLED;
        IoCompleteRequest(Irp, IO_NO_INCREMENT);
    }
}
Exemplo n.º 10
0
VOID
CancelWaitWake(
    IN PDEVICE_EXTENSION DeviceExtension
    )
/*++
 
Routine Description:

    This routine cancels the Wait Wake request.

Arguments:

    DeviceExtension - pointer to the device extension

Return Value:

    None.

--*/
{
    PIRP Irp;

    MobiUsb_DbgPrint(3, ("file mobipwr: CancelWaitWake - begins\n"));

    Irp = (PIRP) InterlockedExchangePointer(&DeviceExtension->WaitWakeIrp, 
                                            NULL);

    if(Irp) {

        IoCancelIrp(Irp);

        if(InterlockedExchange(&DeviceExtension->FlagWWCancel, 1)) {

            PoStartNextPowerIrp(Irp);

            Irp->IoStatus.Status = STATUS_CANCELLED;
            Irp->IoStatus.Information = 0;

            IoCompleteRequest(Irp, IO_NO_INCREMENT);
        }    
    }

    MobiUsb_DbgPrint(3, ("file mobipwr: CancelWaitWake - ends\n"));
}
Exemplo n.º 11
0
Arquivo: wsk2.c Projeto: airhigh/wdrbd
NTSTATUS
NTAPI
Connect(
	__in PWSK_SOCKET	WskSocket,
	__in PSOCKADDR		RemoteAddress
)
{
	KEVENT		CompletionEvent = { 0 };
	PIRP		Irp = NULL;
	NTSTATUS	Status = STATUS_UNSUCCESSFUL;

	if (g_SocketsState != INITIALIZED || !WskSocket || !RemoteAddress)
		return STATUS_INVALID_PARAMETER;

	Status = InitWskData(&Irp, &CompletionEvent);
	if (!NT_SUCCESS(Status)) {
		return Status;
	}

	Status = ((PWSK_PROVIDER_CONNECTION_DISPATCH) WskSocket->Dispatch)->WskConnect(
		WskSocket,
		RemoteAddress,
		0,
		Irp);

	if (Status == STATUS_PENDING) {
		LARGE_INTEGER	nWaitTime;
		nWaitTime = RtlConvertLongToLargeInteger(-1 * 1000 * 1000 * 10);
		if ((Status = KeWaitForSingleObject(&CompletionEvent, Executive, KernelMode, FALSE, &nWaitTime)) == STATUS_TIMEOUT)
		{
			IoCancelIrp(Irp);
			KeWaitForSingleObject(&CompletionEvent, Executive, KernelMode, FALSE, NULL);
		}
	}

	if (Status == STATUS_SUCCESS)
	{
		Status = Irp->IoStatus.Status;
	}

	IoFreeIrp(Irp);
	return Status;
}
Exemplo n.º 12
0
BOOLEAN
CancelKeyboardIrp(
    IN PIRP Irp
    )
{
	// 这里有些判断应该不是必须的,不过还是小心点好
	if ( Irp->Cancel || Irp->CancelRoutine == NULL )
	{
		DbgPrint( "Can't Cancel the irp\n" );
		return FALSE;
	}
	if ( FALSE == IoCancelIrp( Irp ) )
	{
		DbgPrint( "IoCancelIrp() to failed\n" );
		return FALSE;
	}
	IoSetCancelRoutine(Irp, NULL);
	return TRUE; 
}
NTSTATUS StopPolling(PDEVICE_EXTENSION pdx)
{
    PIO_STACK_LOCATION stack;
    PLIST_ENTRY        ListEntry;
    KIRQL              OldIrql;
    BOOLEAN            Pending;
    PIRP               ReadIrp;
    
    KeAcquireSpinLock(&pdx->PollLock, &OldIrql);
    Pending = pdx->PollPending;
    KeReleaseSpinLock(&pdx->PollLock, OldIrql);

    if(Pending)
    {
        IoCancelIrp(pdx->PollingIrp);
    }
    
    // finish any outstanding reads 
    KeAcquireSpinLock(&pdx->ReadIrpLock, &OldIrql);

    while(!IsListEmpty(&pdx->ReadIrpList))
    {
        ListEntry = RemoveHeadList(&pdx->ReadIrpList);
        KeReleaseSpinLock(&pdx->ReadIrpLock, OldIrql);
        
        ReadIrp = CONTAINING_RECORD(ListEntry, IRP, Tail.Overlay.ListEntry);

        IoSetCancelRoutine(ReadIrp, NULL);
        IoReleaseRemoveLock(&pdx->RemoveLock, ReadIrp);
        CompleteRequest(ReadIrp, STATUS_NO_SUCH_DEVICE, 0);

        KeAcquireSpinLock(&pdx->ReadIrpLock, &OldIrql);
    }
    KeReleaseSpinLock(&pdx->ReadIrpLock, OldIrql);

    // clear the read fifo 
    KeAcquireSpinLock(&pdx->FifoLock, &OldIrql);
    pdx->FifoReadPointer = pdx->FifoWritePointer = 0;
    KeReleaseSpinLock(&pdx->FifoLock, OldIrql);

    return STATUS_SUCCESS;
}
Exemplo n.º 14
0
static VOID EvhdFinalize(ParserInstance *parser)
{
	if (parser->pRecoveryStatusIrp)
	{
		IoCancelIrp(parser->pRecoveryStatusIrp);
		ExWaitForRundownProtectionRelease(&parser->RecoveryRundownProtection);
		IoFreeIrp(parser->pRecoveryStatusIrp);
		parser->pRecoveryStatusIrp = NULL;
	}

	if (parser->pDirectIoIrp)
	{
		IoFreeIrp(parser->pDirectIoIrp);
		parser->pDirectIoIrp = NULL;
	}

	if (parser->pQoSStatusIrp)
	{
		IoFreeIrp(parser->pQoSStatusIrp);
		parser->pQoSStatusIrp = NULL;
	}

	if (parser->pQoSStatusBuffer)
	{
		ExFreePoolWithTag(parser->pQoSStatusBuffer, EvhdQoSPoolTag);
		parser->pQoSStatusBuffer = NULL;
	}

	if (parser->pVhdmpFileObject)
	{
		ObDereferenceObject(parser->pVhdmpFileObject);
		parser->pVhdmpFileObject = NULL;
	}

	if (parser->FileHandle)
	{
		ZwClose(parser->FileHandle);
		parser->FileHandle = NULL;
	}
}
Exemplo n.º 15
0
Arquivo: wsk2.c Projeto: airhigh/wdrbd
NTSTATUS NTAPI
Disconnect(
	__in PWSK_SOCKET	WskSocket
)
{
	KEVENT		CompletionEvent = { 0 };
	PIRP		Irp = NULL;
	NTSTATUS	Status = STATUS_UNSUCCESSFUL;
	LARGE_INTEGER	nWaitTime;
	nWaitTime.QuadPart = (-1 * 1000 * 10000);   // wait 1000ms relative 
	
	if (g_SocketsState != INITIALIZED || !WskSocket)
		return STATUS_INVALID_PARAMETER;

	Status = InitWskData(&Irp, &CompletionEvent);
	if (!NT_SUCCESS(Status)) {
		return Status;
	}

	Status = ((PWSK_PROVIDER_CONNECTION_DISPATCH) WskSocket->Dispatch)->WskDisconnect(
		WskSocket,
		NULL,
		0,//WSK_FLAG_ABORTIVE,=> when disconnecting, ABORTIVE was going to standalone, and then we removed ABORTIVE
		Irp);

	if (Status == STATUS_PENDING) {
		Status = KeWaitForSingleObject(&CompletionEvent, Executive, KernelMode, FALSE, &nWaitTime);
		if(STATUS_TIMEOUT == Status) { // DW-712 timeout process for fast closesocket in congestion mode, instead of WSK_FLAG_ABORTIVE
			WDRBD_INFO("Timeout... Cancel Disconnect socket:%p\n",WskSocket);
			IoCancelIrp(Irp);
			KeWaitForSingleObject(&CompletionEvent, Executive, KernelMode, FALSE, NULL);
		} 

		Status = Irp->IoStatus.Status;
	}

	IoFreeIrp(Irp);
	return Status;
}
Exemplo n.º 16
0
VOID DriverUnload(IN PDRIVER_OBJECT pDriverObject)
{
	PDEVICE_OBJECT pNextDevObj = pDriverObject->DeviceObject;
	while(0 != pNextDevObj)
	{
		PMYDEVICE_EXTENSION pDevExtend = (PMYDEVICE_EXTENSION)pNextDevObj->DeviceExtension;
		
		if(pNextDevObj == g_MasterDeviceObj)
		{
			PDEVICE_OBJECT pTempDevObj = pNextDevObj->NextDevice;
			UNICODE_STRING tMasterDevObjSymbol;
			RtlInitUnicodeString(&tMasterDevObjSymbol,__T(DEVICE_NAME_KBDFILTER_SYMBOL));
			IoDeleteSymbolicLink(&tMasterDevObjSymbol);
			IoDeleteDevice(pNextDevObj);
			pNextDevObj = pTempDevObj;
			continue;
		}
		
		PIRP tCurIrp		= pDevExtend->CurIrp;
		BOOLEAN tCancelRet	= FALSE;
		if(0 != tCurIrp)
		{
			 tCancelRet = IoCancelIrp(tCurIrp);
		}

		if(0 != pDevExtend->LowDeviceObj)
		{
			IoDetachDevice(pDevExtend->LowDeviceObj);
		}

		LARGE_INTEGER tDelay;
		tDelay.QuadPart = 1000*10000*(-1);
		KeDelayExecutionThread(KernelMode,FALSE,&tDelay);
	
		PDEVICE_OBJECT pTempDevObj = pNextDevObj->NextDevice;
		IoDeleteDevice(pNextDevObj);
		pNextDevObj = pTempDevObj;
	}
}
Exemplo n.º 17
0
static NTSTATUS callparport(struct eppflexfile *fs, unsigned long ioctlcode,
			    void *buffer, unsigned int inlen, unsigned int outlen,
			    LARGE_INTEGER *timeout)
{
        NTSTATUS status;
        PIRP irp;
        PIO_STACK_LOCATION irpsp;
        KEVENT event;

        irp = IoAllocateIrp((CCHAR)(fs->pdo->StackSize+1), FALSE);
        if (!irp)
                return STATUS_INSUFFICIENT_RESOURCES;
        irpsp = IoGetNextIrpStackLocation(irp);
        irpsp->MajorFunction = IRP_MJ_INTERNAL_DEVICE_CONTROL;
        irpsp->Parameters.DeviceIoControl.OutputBufferLength = outlen;
        irpsp->Parameters.DeviceIoControl.InputBufferLength = inlen;
        irpsp->Parameters.DeviceIoControl.IoControlCode = ioctlcode;
        irp->AssociatedIrp.SystemBuffer = buffer;
  
        KeInitializeEvent(&event, NotificationEvent, FALSE);
        IoSetCompletionRoutine(irp, parcompletion, &event, TRUE, TRUE, TRUE);
        status = IoCallDriver(fs->pdo, irp);
        if (!NT_SUCCESS(status)) {
                IoFreeIrp(irp);
                return status;
        }
  
        status = KeWaitForSingleObject(&event, Executive, KernelMode, FALSE, timeout);
        if (status == STATUS_TIMEOUT) {
                IoCancelIrp(irp);
                status = KeWaitForSingleObject(&event, Executive, KernelMode, FALSE, NULL);
        }
        status = irp->IoStatus.Status;
        IoFreeIrp(irp);
        return status;
}
Exemplo n.º 18
0
VOID NTAPI CancelWaitWake(IN PDEVICE_EXTENSION DeviceExtension)
{
    PIRP Irp;

    FreeBT_DbgPrint(3, ("FBTUSB: CancelWaitWake: Entered\n"));

    Irp = (PIRP) InterlockedExchangePointer(&DeviceExtension->WaitWakeIrp, NULL);
    if(Irp)
    {
        IoCancelIrp(Irp);
        if(InterlockedExchange(&DeviceExtension->FlagWWCancel, 1))
        {
            PoStartNextPowerIrp(Irp);
            Irp->IoStatus.Status = STATUS_CANCELLED;
            Irp->IoStatus.Information = 0;
            IoCompleteRequest(Irp, IO_NO_INCREMENT);

        }

    }

    FreeBT_DbgPrint(3, ("FBTUSB: CancelWaitWake: Leaving\n"));

}
Exemplo n.º 19
0
Arquivo: wsk2.c Projeto: airhigh/wdrbd
LONG NTAPI Receive(
	__in  PWSK_SOCKET	WskSocket,
	__out PVOID			Buffer,
	__in  ULONG			BufferSize,
	__in  ULONG			Flags,
	__in ULONG			Timeout
)
{
	KEVENT		CompletionEvent = { 0 };
	PIRP		Irp = NULL;
	WSK_BUF		WskBuffer = { 0 };
	LONG		BytesReceived = SOCKET_ERROR;
	NTSTATUS	Status = STATUS_UNSUCCESSFUL;

    struct      task_struct *thread = current;
    PVOID       waitObjects[2];
    int         wObjCount = 1;

	if (g_SocketsState != INITIALIZED || !WskSocket || !Buffer || !BufferSize)
		return SOCKET_ERROR;

	if ((int) BufferSize <= 0)
	{
		return SOCKET_ERROR;
	}

	Status = InitWskBuffer(Buffer, BufferSize, &WskBuffer);
	if (!NT_SUCCESS(Status)) {
		return SOCKET_ERROR;
	}

	Status = InitWskData(&Irp, &CompletionEvent);

	if (!NT_SUCCESS(Status)) {
		FreeWskBuffer(&WskBuffer);
		return SOCKET_ERROR;
	}

	Status = ((PWSK_PROVIDER_CONNECTION_DISPATCH) WskSocket->Dispatch)->WskReceive(
				WskSocket,
				&WskBuffer,
				Flags,
				Irp);

    if (Status == STATUS_PENDING)
    {
        LARGE_INTEGER	nWaitTime;
        LARGE_INTEGER	*pTime;

        if (Timeout <= 0 || Timeout == MAX_SCHEDULE_TIMEOUT)
        {
            pTime = 0;
        }
        else
        {
            nWaitTime = RtlConvertLongToLargeInteger(-1 * Timeout * 1000 * 10);
            pTime = &nWaitTime;
        }

        waitObjects[0] = (PVOID) &CompletionEvent;
        if (thread->has_sig_event)
        {
            waitObjects[1] = (PVOID) &thread->sig_event;
            wObjCount = 2;
        }
        Status = KeWaitForMultipleObjects(wObjCount, &waitObjects[0], WaitAny, Executive, KernelMode, FALSE, pTime, NULL);
        switch (Status)
        {
        case STATUS_WAIT_0: // waitObjects[0] CompletionEvent
            if (Irp->IoStatus.Status == STATUS_SUCCESS)
            {
                BytesReceived = (LONG) Irp->IoStatus.Information;
            }
            else
            {
#ifdef _WIN32_LOGLINK 
                DbgPrint("RECV(%s) wsk(0x%p) multiWait err(0x%x:%s)\n", thread->comm, WskSocket, Irp->IoStatus.Status, GetSockErrorString(Irp->IoStatus.Status));
#else
				WDRBD_INFO("RECV(%s) wsk(0x%p) multiWait err(0x%x:%s)\n", thread->comm, WskSocket, Irp->IoStatus.Status, GetSockErrorString(Irp->IoStatus.Status));
#endif
				if(Irp->IoStatus.Status)
                {
                    BytesReceived = -ECONNRESET;
                }
            }
            break;

        case STATUS_WAIT_1:
            BytesReceived = -EINTR;
            break;

        case STATUS_TIMEOUT:
            BytesReceived = -EAGAIN;
            break;

        default:
            BytesReceived = SOCKET_ERROR;
            break;
        }
    }
	else
	{
		if (Status == STATUS_SUCCESS)
		{
			BytesReceived = (LONG) Irp->IoStatus.Information;
#ifdef _WIN32_LOGLINK
			DbgPrint("(%s) Rx No pending and data(%d) is avail\n", current->comm, BytesReceived);
#else
			WDRBD_INFO("(%s) Rx No pending and data(%d) is avail\n", current->comm, BytesReceived);
#endif
		}
		else
		{
#ifdef _WIN32_LOGLINK
			DbgPrint("WskReceive Error Status=0x%x\n", Status); // EVENT_LOG!
#else
			WDRBD_TRACE("WskReceive Error Status=0x%x\n", Status); // EVENT_LOG!
#endif
		}
	}

	if (BytesReceived == -EINTR || BytesReceived == -EAGAIN)
	{
		// cancel irp in wsk subsystem
		IoCancelIrp(Irp);
		KeWaitForSingleObject(&CompletionEvent, Executive, KernelMode, FALSE, NULL);
		if (Irp->IoStatus.Information > 0)
		{
			//WDRBD_INFO("rx canceled but rx data(%d) avaliable.\n", Irp->IoStatus.Information);
			BytesReceived = Irp->IoStatus.Information;
		}
	}

	IoFreeIrp(Irp);
	FreeWskBuffer(&WskBuffer);

	return BytesReceived;
}
Exemplo n.º 20
0
Arquivo: wsk2.c Projeto: airhigh/wdrbd
LONG
NTAPI
SendLocal(
	__in PWSK_SOCKET	WskSocket,
	__in PVOID			Buffer,
	__in ULONG			BufferSize,
	__in ULONG			Flags,
	__in ULONG			Timeout
)
{
	KEVENT		CompletionEvent = { 0 };
	PIRP		Irp = NULL;
	WSK_BUF		WskBuffer = { 0 };
	LONG		BytesSent = SOCKET_ERROR;
	NTSTATUS	Status = STATUS_UNSUCCESSFUL;

	if (g_SocketsState != INITIALIZED || !WskSocket || !Buffer || ((int) BufferSize <= 0))
		return SOCKET_ERROR;

	Status = InitWskBuffer(Buffer, BufferSize, &WskBuffer);
	if (!NT_SUCCESS(Status)) {
		return SOCKET_ERROR;
	}

	Status = InitWskData(&Irp, &CompletionEvent);
	if (!NT_SUCCESS(Status)) {
		FreeWskBuffer(&WskBuffer);
		return SOCKET_ERROR;
	}

	Flags |= WSK_FLAG_NODELAY;

	Status = ((PWSK_PROVIDER_CONNECTION_DISPATCH) WskSocket->Dispatch)->WskSend(
		WskSocket,
		&WskBuffer,
		Flags,
		Irp);

	if (Status == STATUS_PENDING)
	{
		LARGE_INTEGER	nWaitTime;
		LARGE_INTEGER	*pTime;

		if (Timeout <= 0 || Timeout == MAX_SCHEDULE_TIMEOUT)
		{
			pTime = NULL;
		}
		else
		{
			nWaitTime = RtlConvertLongToLargeInteger(-1 * Timeout * 1000 * 10);
			pTime = &nWaitTime;
		}
		Status = KeWaitForSingleObject(&CompletionEvent, Executive, KernelMode, FALSE, pTime);

		switch (Status)
		{
		case STATUS_TIMEOUT:
			IoCancelIrp(Irp);
			KeWaitForSingleObject(&CompletionEvent, Executive, KernelMode, FALSE, NULL);
			BytesSent = -EAGAIN;
			break;

		case STATUS_WAIT_0:
			if (NT_SUCCESS(Irp->IoStatus.Status))
			{
				BytesSent = (LONG) Irp->IoStatus.Information;
			}
			else
			{
#ifdef _WIN32_LOGLINK
				DbgPrint("(%s) sent error(%s)\n", current->comm, GetSockErrorString(Irp->IoStatus.Status));
#else
				WDRBD_WARN("(%s) sent error(%s)\n", current->comm, GetSockErrorString(Irp->IoStatus.Status));
#endif
				switch (Irp->IoStatus.Status)
				{
				case STATUS_IO_TIMEOUT:
					BytesSent = -EAGAIN;
					break;
				case STATUS_INVALID_DEVICE_STATE:
					BytesSent = -EAGAIN;
					break;
				default:
					BytesSent = -ECONNRESET;
					break;
				}
			}
			break;

		default:
#ifdef _WIN32_LOGLINK
			DbgPrint("KeWaitForSingleObject failed. status 0x%x\n", Status);
#else
			WDRBD_ERROR("KeWaitForSingleObject failed. status 0x%x\n", Status);
#endif
			BytesSent = SOCKET_ERROR;
		}
	}
	else
	{
		if (Status == STATUS_SUCCESS)
		{
			BytesSent = (LONG) Irp->IoStatus.Information;
#ifdef _WIN32_LOGLINK
			DbgPrint("(%s) WskSend No pending: but sent(%d)!\n", current->comm, BytesSent);
#else
			WDRBD_WARN("(%s) WskSend No pending: but sent(%d)!\n", current->comm, BytesSent);
#endif
		}
		else
		{
#ifdef _WIN32_LOGLINK
			DbgPrint("(%s) WskSend error(0x%x)\n", current->comm, Status);
#else
			WDRBD_WARN("(%s) WskSend error(0x%x)\n", current->comm, Status);
#endif
			BytesSent = SOCKET_ERROR;
		}
	}

	IoFreeIrp(Irp);
	FreeWskBuffer(&WskBuffer);

	return BytesSent;
}
Exemplo n.º 21
0
Arquivo: wsk2.c Projeto: airhigh/wdrbd
LONG
NTAPI
Send(
	__in PWSK_SOCKET	WskSocket,
	__in PVOID			Buffer,
	__in ULONG			BufferSize,
	__in ULONG			Flags,
	__in ULONG			Timeout,
	__in KEVENT			*send_buf_kill_event,
	__in struct			drbd_transport *transport,
	__in enum			drbd_stream stream
)
{
	KEVENT		CompletionEvent = { 0 };
	PIRP		Irp = NULL;
	WSK_BUF		WskBuffer = { 0 };
	LONG		BytesSent = SOCKET_ERROR; // DRBC_CHECK_WSK: SOCKET_ERROR be mixed EINVAL?
	NTSTATUS	Status = STATUS_UNSUCCESSFUL;

	if (g_SocketsState != INITIALIZED || !WskSocket || !Buffer || ((int) BufferSize <= 0))
		return SOCKET_ERROR;

	Status = InitWskBuffer(Buffer, BufferSize, &WskBuffer);
	if (!NT_SUCCESS(Status)) {
		return SOCKET_ERROR;
	}

	Status = InitWskData(&Irp, &CompletionEvent);
	if (!NT_SUCCESS(Status)) {
		FreeWskBuffer(&WskBuffer);
		return SOCKET_ERROR;
	}

	Flags |= WSK_FLAG_NODELAY;

	Status = ((PWSK_PROVIDER_CONNECTION_DISPATCH) WskSocket->Dispatch)->WskSend(
		WskSocket,
		&WskBuffer,
		Flags,
		Irp);

	if (Status == STATUS_PENDING)
	{
		LARGE_INTEGER	nWaitTime;
		LARGE_INTEGER	*pTime;

		int retry_count = 0;
	retry:
		if (Timeout <= 0 || Timeout == MAX_SCHEDULE_TIMEOUT)
		{
			pTime = NULL;
		}
		else
		{
			nWaitTime = RtlConvertLongToLargeInteger(-1 * Timeout * 1000 * 10);
			pTime = &nWaitTime;
		}
		{
			struct      task_struct *thread = current;
			PVOID       waitObjects[2];
			int         wObjCount = 1;

			waitObjects[0] = (PVOID) &CompletionEvent;
#ifndef _WIN32_SEND_BUFFING 
			// in send-buffering, Netlink , call_usermodehelper are distinguished to SendLocal
			// KILL event is only used in send-buffering thread while send block. 
			// WIN32_V9_REFACTO_:required to refactoring that input param, log message are simplized.
#else

#endif
			Status = KeWaitForMultipleObjects(wObjCount, &waitObjects[0], WaitAny, Executive, KernelMode, FALSE, pTime, NULL);
			switch (Status)
			{
			case STATUS_TIMEOUT:
#ifdef _WIN32_SEND_BUFFING
				if (wObjCount == 1)
				{
					retry_count++;
					WDRBD_WARN("(%s) sent timeout=%d sz=%d retry_count=%d WskSocket=%p IRP=%p\n",
						current->comm, Timeout, BufferSize, retry_count,WskSocket, Irp);

					// required to refactroing about retrying method.

					goto retry;
				}
#endif
				if (transport != NULL)
				{
					if (!drbd_stream_send_timed_out(transport, stream))
					{
						goto retry;
					}
				}

				IoCancelIrp(Irp);
				KeWaitForSingleObject(&CompletionEvent, Executive, KernelMode, FALSE, NULL);
				BytesSent = -EAGAIN;
				break;

			case STATUS_WAIT_0:
				if (NT_SUCCESS(Irp->IoStatus.Status))
				{
					BytesSent = (LONG)Irp->IoStatus.Information;
				}
				else
				{
					WDRBD_WARN("tx error(%s) wsk(0x%p)\n", GetSockErrorString(Irp->IoStatus.Status), WskSocket);
					switch (Irp->IoStatus.Status)
					{
						case STATUS_IO_TIMEOUT:
							BytesSent = -EAGAIN;
							break;
						case STATUS_INVALID_DEVICE_STATE:
							BytesSent = -EAGAIN;
							break;
						default:
							BytesSent = -ECONNRESET;
							break;
					}
				}
				break;

			//case STATUS_WAIT_1: // common: sender or send_bufferinf thread's kill signal
			//	IoCancelIrp(Irp);
			//	KeWaitForSingleObject(&CompletionEvent, Executive, KernelMode, FALSE, NULL);
			//	BytesSent = -EINTR;
			//	break;

			default:
				WDRBD_ERROR("Wait failed. status 0x%x\n", Status);
				BytesSent = SOCKET_ERROR;
			}
		}
	}
	else
	{
		if (Status == STATUS_SUCCESS)
		{
			BytesSent = (LONG) Irp->IoStatus.Information;
			WDRBD_WARN("(%s) WskSend No pending: but sent(%d)!\n", current->comm, BytesSent);
		}
		else
		{
			WDRBD_WARN("(%s) WskSend error(0x%x)\n", current->comm, Status);
			BytesSent = SOCKET_ERROR;
		}
	}

	IoFreeIrp(Irp);
	FreeWskBuffer(&WskBuffer);

	return BytesSent;
}
Exemplo n.º 22
0
VOID
NICFreeBusyRecvPackets(
    PMP_ADAPTER Adapter
    )
/*++

Routine Description:

    This function tries to cancel all the outstanding read IRP if it is not 
    already completed and frees the RCB block. This routine is called
    only by the Halt handler.
    
Arguments:

    Adapter    - pointer to the MP_ADAPTER structure
    
Return value:

    VOID
--*/
{ 
    PLIST_ENTRY         pEntry = NULL;
    PRCB                pRCB = NULL;
    
    DEBUGP(MP_TRACE, ("--> NICFreeBusyRecvPackets\n"));

    if(!MP_TEST_FLAG(Adapter, fMP_RECV_SIDE_RESOURCE_ALLOCATED)){
        return;
    }
    
    NdisAcquireSpinLock(&Adapter->RecvLock);

    while(!IsListEmpty(&Adapter->RecvBusyList))
    {
        
        pEntry = (PLIST_ENTRY)RemoveHeadList(&Adapter->RecvBusyList);
        pRCB = CONTAINING_RECORD(pEntry, RCB, List);
        NdisInitializeListHead(&pRCB->List);
        
        NdisReleaseSpinLock(&Adapter->RecvLock); 
        
        
        if (InterlockedExchange((PVOID)&pRCB->IrpLock, IRPLOCK_CANCEL_STARTED) 
                                == IRPLOCK_CANCELABLE) {

            // 
            // We got it to the IRP before it was completed. We can cancel
            // the IRP without fear of losing it, as the completion routine
            // will not let go of the IRP until we say so.
            // 
            IoCancelIrp(pRCB->Irp);
            // 
            // Release the completion routine. If it already got there,
            // then we need to free it ourself. Otherwise, we got
            // through IoCancelIrp before the IRP completed entirely.
            // 
            if (InterlockedExchange((PVOID)&pRCB->IrpLock, IRPLOCK_CANCEL_COMPLETE) 
                                    == IRPLOCK_COMPLETED) {
                if(NdisInterlockedDecrement(&pRCB->Ref) == 0) {
                    NICFreeRCB(pRCB);
                } else {
                    ASSERTMSG("Only we have the right to free RCB\n", FALSE);                
                }
            }

        }

        NdisAcquireSpinLock(&Adapter->RecvLock);
        
    }

    NdisReleaseSpinLock(&Adapter->RecvLock); 

    DEBUGP(MP_TRACE, ("<-- NICFreeBusyRecvPackets\n"));
     
    return ;
}
Exemplo n.º 23
0
NTSTATUS DriverEntry(
	IN PDRIVER_OBJECT  DriverObject, 
	IN PUNICODE_STRING RegistryPath
)
{
	unsigned int i;
	NTSTATUS Status;
	
	DbgPrint("DriverEntry: start\n");
/*
	for (i = 0; i < IRP_MJ_MAXIMUM_FUNCTION; ++i) 
	{
		DriverObject->MajorFunction[i] = OnUnhandledRequest;
	}
*/

	Status = OnAddDevice(DriverObject, NULL);

	if(NT_SUCCESS(Status))
	{
		InputDisabled = FALSE;
		DriverOpened = FALSE;
		WaitTimeout.QuadPart = -300000000;
		
		KeInitializeSpinLock(&KbrdQueueLock);
		InitializeListHead(&KbrdQueue);
		KbrdQueueSize = KBRD_QUEUE_SIZE;
		KbrdQueueCount = 0;
		KeInitializeEvent(&KbrdEvent, SynchronizationEvent, FALSE);

		
		KeInitializeSpinLock(&MouseQueueLock);
		InitializeListHead(&MouseQueue);
		MouseQueueSize = MOUSE_QUEUE_SIZE;
		MouseQueueCount = 0;
		KeInitializeEvent(&MouseEvent, SynchronizationEvent, FALSE);

		MouseBufferSize = MOUSE_BUFFER_SIZE;
		MouseBufferCount = 0;
		MouseRelX = 0;
		MouseRelY = 0;
		MouseButtons = 0;
		MouseFirstPacket = TRUE;


		DriverObject->MajorFunction[IRP_MJ_READ]		   = OnReadRequest;
		DriverObject->MajorFunction[IRP_MJ_CREATE]         = OnCreateRequest;
		DriverObject->MajorFunction[IRP_MJ_CLOSE]          = OnCloseRequest;
		DriverObject->MajorFunction[IRP_MJ_FLUSH_BUFFERS]  =
		DriverObject->MajorFunction[IRP_MJ_CLEANUP]        = OnUnhandledRequest;
		DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = OnControlRequest;

//		DriverObject->DriverStartIo = OnStartIo;

		if(LowerKbrdDeviceObject->CurrentIrp)
		{
			DbgPrint("Cancelling previous request........\n");
			IoCancelIrp(LowerKbrdDeviceObject->CurrentIrp);
		}
	}

//	DriverObject->DriverUnload = UnloadDriver;

	return Status;
}
Exemplo n.º 24
0
Arquivo: wsk2.c Projeto: airhigh/wdrbd
PWSK_SOCKET
NTAPI
Accept(
	__in PWSK_SOCKET	WskSocket,
	__out_opt PSOCKADDR	LocalAddress,
	__out_opt PSOCKADDR	RemoteAddress,
	__out_opt NTSTATUS	*RetStaus,
	__in int			timeout
)
{
	KEVENT			CompletionEvent = { 0 };
	PIRP			Irp = NULL;
	NTSTATUS		Status = STATUS_UNSUCCESSFUL;
	PWSK_SOCKET		AcceptedSocket = NULL;
    struct task_struct *thread = current;
    PVOID waitObjects[2];
    int wObjCount = 1;

	if (g_SocketsState != INITIALIZED || !WskSocket)
	{
		*RetStaus = SOCKET_ERROR;
		return NULL;
	}

	Status = InitWskData(&Irp, &CompletionEvent);
	if (!NT_SUCCESS(Status)) {
		*RetStaus = Status;
		return NULL;
	}

	Status = ((PWSK_PROVIDER_LISTEN_DISPATCH) WskSocket->Dispatch)->WskAccept(
		WskSocket,
		0,
		NULL,
		NULL,
		LocalAddress,
		RemoteAddress,
		Irp);

	if (Status == STATUS_PENDING)
	{
		LARGE_INTEGER	nWaitTime;
		LARGE_INTEGER	*pTime;

		if (timeout <= 0 || timeout == MAX_SCHEDULE_TIMEOUT)
		{
			pTime = 0;
		}
		else
		{
			nWaitTime = RtlConvertLongToLargeInteger(-1 * timeout * 10000000);
			pTime = &nWaitTime;
		}

        waitObjects[0] = (PVOID) &CompletionEvent;
        if (thread->has_sig_event)
        {
            waitObjects[1] = (PVOID) &thread->sig_event;
            wObjCount = 2;
        }

        Status = KeWaitForMultipleObjects(wObjCount, &waitObjects[0], WaitAny, Executive, KernelMode, FALSE, pTime, NULL);

		switch (Status)
		{
			case STATUS_WAIT_0:
				break;

			case STATUS_WAIT_0 + 1:
				IoCancelIrp(Irp);
				KeWaitForSingleObject(&CompletionEvent, Executive, KernelMode, FALSE, NULL);
				*RetStaus = -EINTR;	
				break;

			case STATUS_TIMEOUT:
				IoCancelIrp(Irp);
				KeWaitForSingleObject(&CompletionEvent, Executive, KernelMode, FALSE, NULL);
				*RetStaus = STATUS_TIMEOUT;
				break;

			default:
				WDRBD_ERROR("Unexpected Error Status=0x%x\n", Status);
				break;
		}
	}
	else
	{
		if (Status != STATUS_SUCCESS)
		{
			WDRBD_TRACE("Accept Error Status=0x%x\n", Status);
		}
	}

	AcceptedSocket = (Status == STATUS_SUCCESS) ? (PWSK_SOCKET) Irp->IoStatus.Information : NULL;
	IoFreeIrp(Irp);
	return AcceptedSocket;
}
Exemplo n.º 25
0
// Send a USB command to device and then waiting for this command to complete.
NTSTATUS UsbDev::SendAwaitUrb(PURB Urb)
{
	//2010/8/25 03:13下午
	/*NTSTATUS ntStatus, status = STATUS_SUCCESS;
    PIRP irp;
    KEVENT TimeoutEvent;
    PIO_STACK_LOCATION nextStack;

    KeWaitForSingleObject(&CallUSBSemaphore,Executive,KernelMode,FALSE,NULL);

    // Initialize the event we'll wait on
    //
    KeInitializeEvent(&TimeoutEvent,SynchronizationEvent,FALSE);

    // Allocate the Irp
    //
    irp = IoAllocateIrp(m_pLdo->StackSize, FALSE);

    if (irp == NULL){
        ntStatus =  STATUS_UNSUCCESSFUL;
        goto Exit_CallUSB;
    }
    //
    // Set the Irp parameters
    //
    nextStack = IoGetNextIrpStackLocation(irp);
    //ASSERT(nextStack != NULL);
    nextStack->MajorFunction = IRP_MJ_INTERNAL_DEVICE_CONTROL;
    nextStack->Parameters.DeviceIoControl.IoControlCode =  IOCTL_INTERNAL_USB_SUBMIT_URB;
    nextStack->Parameters.Others.Argument1 = Urb;
    //
    // Set the completion routine.
    //
    IoSetCompletionRoutine(irp,SyncCompletionRoutine,&TimeoutEvent, TRUE, TRUE,TRUE);   
    //
    // pass the irp down usb stack
    //
    ntStatus = IoCallDriver(m_pLdo,irp);

    if (ntStatus == STATUS_PENDING) {
        // Irp i spending. we have to wait till completion..
        LARGE_INTEGER timeout;

        // Specify a timeout of 5 seconds to wait for this call to complete.
        //
        timeout.QuadPart = -10000 * 5000;

        ntStatus = KeWaitForSingleObject(&TimeoutEvent, Executive,KernelMode,FALSE, &timeout);

        if (ntStatus == STATUS_TIMEOUT) {
           ntStatus = STATUS_IO_TIMEOUT;

            // Cancel the Irp we just sent.
            //
            IoCancelIrp(irp);

            // And wait until the cancel completes
            //
            KeWaitForSingleObject(&TimeoutEvent,Executive, KernelMode, FALSE,NULL);
        }
        else {
            ntStatus = irp->IoStatus.Status;
        }
    }

    // Done with the Irp, now free it.
    //
    IoFreeIrp(irp);

Exit_CallUSB:

    KeReleaseSemaphore(&CallUSBSemaphore,LOW_REALTIME_PRIORITY,1,FALSE);

    if (NT_ERROR(ntStatus)) {
       DBGU_TRACE("***Error*** SendAwaitUrb (%x) (%x)\n", ntStatus,Urb->UrbHeader.Status);
    }

    return ntStatus;
	*/
	
	DBGU_TRACE("UsbDev::SendAwaitUrb\n");

	NTSTATUS ntStatus = STATUS_SUCCESS;
	IO_STATUS_BLOCK ioStatus;
	KEVENT event;
	PIRP Irp;
	PIO_STACK_LOCATION	nextStack;
	LARGE_INTEGER		dueTime;
	//UINT retry = 0;

	KeInitializeEvent(&event, NotificationEvent, FALSE);

	//	------------------  2006/09/27 [Saxen Ko]  ------------------
	// fix DELL bug, that we might re-use the Urb to sent commands!

	//for (retry = 0; retry < 3; ++retry)
	{
		Irp = IoBuildDeviceIoControlRequest(
					IOCTL_INTERNAL_USB_SUBMIT_URB,
					m_pLdo,
					NULL,
					0,
					NULL,
					0,
					TRUE, 
					&event,
					&ioStatus);

		if((Irp != NULL) && ((nextStack = IoGetNextIrpStackLocation(Irp)) != NULL))
		{//(Irp != NULL) && (nextStack != NULL)
			nextStack->Parameters.Others.Argument1 = Urb;

			//
			// Set the completion routine, which will signal the event
			//
			IoSetCompletionRoutine(Irp,
								   SyncCompletionRoutine,
								   &event,
								   FALSE,	// InvokeOnSuccess
								   FALSE,	// InvokeOnError
								   TRUE);	// InvokeOnCancel

			ntStatus = IoCallDriver(m_pLdo, Irp);

			if (ntStatus == STATUS_PENDING) 
			{//ntStatus == STATUS_PENDING
				dueTime.QuadPart = (-10000 * USB_COMMAND_TIMEOUT);
				ntStatus = KeWaitForSingleObject(&event, Suspended,	KernelMode,	FALSE, &dueTime);

				if (ntStatus == STATUS_TIMEOUT)
				{
					ntStatus = STATUS_IO_TIMEOUT;

					DBGU_TRACE("UsbDev::SendAwaitUrb STATUS_IO_TIMEOUT, We cancel this IRP!\n");
					// Reset the Event, then Cancel the Irp we just sent.
					KeResetEvent(&event);
					IoCancelIrp(Irp);

					// And wait until the cancel completes
					KeWaitForSingleObject(&event,
										  Executive,
										  KernelMode,
										  FALSE,
										  NULL);
				}
				else
					ntStatus = ioStatus.Status;
			}//ntStatus == STATUS_PENDING 
			//else 
			//{	
			//	ioStatus.Status = ntStatus;
			//}
		}//(Irp != NULL) && (nextStack != NULL)
		else
		{//Irp == NULL
			ntStatus = STATUS_INSUFFICIENT_RESOURCES;
		}//Irp == NULL

		DBGU_TRACE("SendAwaitUrb: ntStatus(%X) !\n", ntStatus);

		if(!NT_SUCCESS(ntStatus))
		{
			DBGU_TRACE("SendAwaitUrb: UrbStatus(%X) !\n", Urb->UrbHeader.Status);
			// make it more significant
			if (ntStatus == STATUS_UNSUCCESSFUL)
				ntStatus = Urb->UrbHeader.Status;
		}

		//if ((STATUS_UNSUCCESSFUL == ntStatus) && (USBD_STATUS_DEV_NOT_RESPONDING == Urb->UrbHeader.Status))
		//{
		//	KeResetEvent(&event);
		//	DBGU_TRACE("SendAwaitUrb: retry(%d)\n", (retry + 1));
		//}
		//else
		//{
		//	break;
		//}
	}

	return ntStatus;
}
Exemplo n.º 26
0
NTSTATUS
NTAPI
USBH_FdoPower(IN PUSBHUB_FDO_EXTENSION HubExtension,
              IN PIRP Irp,
              IN UCHAR Minor)
{
    NTSTATUS Status;
    PIO_STACK_LOCATION IoStack;
    POWER_STATE PowerState;
    POWER_STATE DevicePwrState;
    BOOLEAN IsAllPortsD3;
    PUSBHUB_PORT_DATA PortData;
    PDEVICE_OBJECT PdoDevice;
    PUSBHUB_PORT_PDO_EXTENSION PortExtension;
    ULONG Port;

    DPRINT_PWR("USBH_FdoPower: HubExtension - %p, Irp - %p, Minor - %X\n",
               HubExtension,
               Irp,
               Minor);

    switch (Minor)
    {
        case IRP_MN_WAIT_WAKE:
            DPRINT_PWR("USBH_FdoPower: IRP_MN_WAIT_WAKE\n");

            IoCopyCurrentIrpStackLocationToNext(Irp);

            IoSetCompletionRoutine(Irp,
                                   USBH_FdoWWIrpIoCompletion,
                                   HubExtension,
                                   TRUE,
                                   TRUE,
                                   TRUE);

            PoStartNextPowerIrp(Irp);
            IoMarkIrpPending(Irp);
            PoCallDriver(HubExtension->LowerDevice, Irp);

            return STATUS_PENDING;

        case IRP_MN_POWER_SEQUENCE:
            DPRINT_PWR("USBH_FdoPower: IRP_MN_POWER_SEQUENCE\n");
            break;

        case IRP_MN_SET_POWER:
            DPRINT_PWR("USBH_FdoPower: IRP_MN_SET_POWER\n");

            IoStack = IoGetCurrentIrpStackLocation(Irp);
            DPRINT_PWR("USBH_FdoPower: IRP_MN_SET_POWER/DevicePowerState\n");
            PowerState = IoStack->Parameters.Power.State;

            if (IoStack->Parameters.Power.Type == DevicePowerState)
            {
                DPRINT_PWR("USBH_FdoPower: PowerState - %x\n",
                           PowerState.DeviceState);

                if (HubExtension->CurrentPowerState.DeviceState == PowerState.DeviceState)
                {
                    IoCopyCurrentIrpStackLocationToNext(Irp);

                    PoStartNextPowerIrp(Irp);
                    IoMarkIrpPending(Irp);
                    PoCallDriver(HubExtension->LowerDevice, Irp);

                    return STATUS_PENDING;
                }

                switch (PowerState.DeviceState)
                {
                    case PowerDeviceD0:
                        if (!(HubExtension->HubFlags & USBHUB_FDO_FLAG_SET_D0_STATE))
                        {
                            HubExtension->HubFlags &= ~(USBHUB_FDO_FLAG_NOT_D0_STATE |
                                                        USBHUB_FDO_FLAG_DEVICE_STOPPING);

                            HubExtension->HubFlags |= USBHUB_FDO_FLAG_SET_D0_STATE;

                            IoCopyCurrentIrpStackLocationToNext(Irp);

                            IoSetCompletionRoutine(Irp,
                                                   USBH_PowerIrpCompletion,
                                                   HubExtension,
                                                   TRUE,
                                                   TRUE,
                                                   TRUE);
                        }
                        else
                        {
                            IoCopyCurrentIrpStackLocationToNext(Irp);
                            PoStartNextPowerIrp(Irp);
                        }

                        IoMarkIrpPending(Irp);
                        PoCallDriver(HubExtension->LowerDevice, Irp);
                        return STATUS_PENDING;

                    case PowerDeviceD1:
                    case PowerDeviceD2:
                    case PowerDeviceD3:
                        if (HubExtension->ResetRequestCount)
                        {
                            IoCancelIrp(HubExtension->ResetPortIrp);

                            KeWaitForSingleObject(&HubExtension->ResetEvent,
                                                  Executive,
                                                  KernelMode,
                                                  FALSE,
                                                  NULL);
                        }

                        if (!(HubExtension->HubFlags & USBHUB_FDO_FLAG_DEVICE_STOPPED))
                        {
                            HubExtension->HubFlags |= (USBHUB_FDO_FLAG_NOT_D0_STATE |
                                                       USBHUB_FDO_FLAG_DEVICE_STOPPING);

                            IoCancelIrp(HubExtension->SCEIrp);

                            KeWaitForSingleObject(&HubExtension->StatusChangeEvent,
                                                  Executive,
                                                  KernelMode,
                                                  FALSE,
                                                  NULL);
                        }

                        HubExtension->CurrentPowerState.DeviceState = PowerState.DeviceState;

                        if (HubExtension->HubFlags & USBHUB_FDO_FLAG_DO_SUSPENSE &&
                            USBH_CheckIdleAbort(HubExtension, TRUE, TRUE) == TRUE)
                        {
                            HubExtension->HubFlags &= ~(USBHUB_FDO_FLAG_NOT_D0_STATE |
                                                        USBHUB_FDO_FLAG_DEVICE_STOPPING);

                            HubExtension->CurrentPowerState.DeviceState = PowerDeviceD0;

                            USBH_SubmitStatusChangeTransfer(HubExtension);

                            PoStartNextPowerIrp(Irp);

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

                            HubExtension->HubFlags &= ~USBHUB_FDO_FLAG_DO_SUSPENSE;

                            KeReleaseSemaphore(&HubExtension->IdleSemaphore,
                                               LOW_REALTIME_PRIORITY,
                                               1,
                                               FALSE);

                            return STATUS_UNSUCCESSFUL;
                        }

                        IoCopyCurrentIrpStackLocationToNext(Irp);

                        IoSetCompletionRoutine(Irp,
                                               USBH_PowerIrpCompletion,
                                               HubExtension,
                                               TRUE,
                                               TRUE,
                                               TRUE);

                        PoStartNextPowerIrp(Irp);
                        IoMarkIrpPending(Irp);
                        PoCallDriver(HubExtension->LowerDevice, Irp);

                        if (HubExtension->HubFlags & USBHUB_FDO_FLAG_DO_SUSPENSE)
                        {
                            HubExtension->HubFlags &= ~USBHUB_FDO_FLAG_DO_SUSPENSE;

                            KeReleaseSemaphore(&HubExtension->IdleSemaphore,
                                               LOW_REALTIME_PRIORITY,
                                               1,
                                               FALSE);
                        }

                        return STATUS_PENDING;

                    default:
                        DPRINT1("USBH_FdoPower: Unsupported PowerState.DeviceState\n");
                        DbgBreakPoint();
                        break;
                }
            }
            else
            {
                if (PowerState.SystemState != PowerSystemWorking)
                {
                    USBH_GetRootHubExtension(HubExtension)->SystemPowerState.SystemState =
                                                            PowerState.SystemState;
                }

                if (PowerState.SystemState == PowerSystemHibernate)
                {
                    HubExtension->HubFlags |= USBHUB_FDO_FLAG_HIBERNATE_STATE;
                }

                PortData = HubExtension->PortData;

                IsAllPortsD3 = TRUE;

                if (PortData && HubExtension->HubDescriptor)
                {
                    for (Port = 0;
                         Port < HubExtension->HubDescriptor->bNumberOfPorts;
                         Port++)
                    {
                        PdoDevice = PortData[Port].DeviceObject;

                        if (PdoDevice)
                        {
                            PortExtension = PdoDevice->DeviceExtension;

                            if (PortExtension->CurrentPowerState.DeviceState != PowerDeviceD3)
                            {
                                IsAllPortsD3 = FALSE;
                                break;
                            }
                        }
                    }
                }

                if (PowerState.SystemState == PowerSystemWorking)
                {
                    DevicePwrState.DeviceState = PowerDeviceD0;
                }
                else if (HubExtension->HubFlags & USBHUB_FDO_FLAG_PENDING_WAKE_IRP ||
                         !IsAllPortsD3)
                {
                    DevicePwrState.DeviceState = HubExtension->DeviceState[PowerState.SystemState];

                    if (DevicePwrState.DeviceState == PowerDeviceUnspecified)
                    {
                        goto Exit;
                    }
                }
                else
                {
                    DevicePwrState.DeviceState = PowerDeviceD3;
                }

                if (DevicePwrState.DeviceState != HubExtension->CurrentPowerState.DeviceState &&
                    HubExtension->HubFlags & USBHUB_FDO_FLAG_DEVICE_STARTED)
                {
                    HubExtension->PowerIrp = Irp;

                    IoMarkIrpPending(Irp);

                    if (PoRequestPowerIrp(HubExtension->LowerPDO,
                                          IRP_MN_SET_POWER,
                                          DevicePwrState,
                                          USBH_FdoDeferPoRequestCompletion,
                                          (PVOID)HubExtension,
                                          NULL) == STATUS_PENDING)
                    {
                        return STATUS_PENDING;
                    }

                    IoCopyCurrentIrpStackLocationToNext(Irp);
                    PoStartNextPowerIrp(Irp);
                    PoCallDriver(HubExtension->LowerDevice, Irp);

                    return STATUS_PENDING;
                }

            Exit:

                HubExtension->SystemPowerState.SystemState = PowerState.SystemState;

                if (PowerState.SystemState == PowerSystemWorking)
                {
                    USBH_CheckIdleDeferred(HubExtension);
                }

                IoCopyCurrentIrpStackLocationToNext(Irp);
                PoStartNextPowerIrp(Irp);

                return PoCallDriver(HubExtension->LowerDevice, Irp);
            }

            break;

        case IRP_MN_QUERY_POWER:
            DPRINT_PWR("USBH_FdoPower: IRP_MN_QUERY_POWER\n");
            break;

        default:
            DPRINT1("USBH_FdoPower: unknown IRP_MN_POWER!\n");
            break;
    }

    IoCopyCurrentIrpStackLocationToNext(Irp);
    PoStartNextPowerIrp(Irp);
    Status = PoCallDriver(HubExtension->LowerDevice, Irp);

    return Status;
}
Exemplo n.º 27
0
VOID
CancelSelectSuspend(
    IN PDEVICE_EXTENSION DeviceExtension
    )
/*++
 
Routine Description:

    This routine is invoked to cancel selective suspend request.

Arguments:

    DeviceExtension - pointer to device extension

Return Value:

    None.

--*/
{
    PIRP  irp;
    KIRQL oldIrql;

    irp = NULL;

    BulkUsb_DbgPrint(3, ("CancelSelectSuspend - begins\n"));

    KeAcquireSpinLock(&DeviceExtension->IdleReqStateLock, &oldIrql);

    if(!CanDeviceSuspend(DeviceExtension))
    {
        BulkUsb_DbgPrint(3, ("Device is not idle\n"));
    
        irp = (PIRP) InterlockedExchangePointer(
                            &DeviceExtension->PendingIdleIrp, 
                            NULL);
    }

    KeReleaseSpinLock(&DeviceExtension->IdleReqStateLock, oldIrql);

    //
    // since we have a valid Irp ptr,
    // we can call IoCancelIrp on it,
    // without the fear of the irp 
    // being freed underneath us.
    //
    if(irp) {

        //
        // This routine has the irp pointer.
        // It is safe to call IoCancelIrp because we know that
        // the compleiton routine will not free this irp unless...
        // 
        //        
        if(IoCancelIrp(irp)) {

            BulkUsb_DbgPrint(3, ("IoCancelIrp returns TRUE\n"));
        }
        else {
            BulkUsb_DbgPrint(3, ("IoCancelIrp returns FALSE\n"));
        }

        //
        // ....we decrement the FreeIdleIrpCount from 2 to 1.
        // if completion routine runs ahead of us, then this routine 
        // decrements the FreeIdleIrpCount from 1 to 0 and hence shall
        // free the irp.
        //
        if(0 == InterlockedDecrement(&DeviceExtension->FreeIdleIrpCount)) {

            BulkUsb_DbgPrint(3, ("CancelSelectSuspend frees the irp\n"));
            IoFreeIrp(irp);

            KeSetEvent(&DeviceExtension->NoIdleReqPendEvent,
                       IO_NO_INCREMENT,
                       FALSE);
        }
    }

    BulkUsb_DbgPrint(3, ("CancelSelectSuspend - ends\n"));

    return;
}
Exemplo n.º 28
0
NTSTATUS
NtCancelIoFile (
    __in HANDLE FileHandle,
    __out PIO_STATUS_BLOCK IoStatusBlock
    )

/*++

Routine Description:

    This service causes all pending I/O operations for the specified file to be
    marked as canceled.  Most types of operations can be canceled immediately,
    while others may continue toward completion before they are actually
    canceled and the caller is notified.

    Only those pending operations that were issued by the current thread using
    the specified handle are canceled.  Any operations issued for the file by
    any other thread or any other process continues normally.

Arguments:

    FileHandle - Supplies a handle to the file whose operations are to be
        canceled.

    IoStatusBlock - Address of the caller's I/O status block.

Return Value:

    The status returned is the final completion status of the operation.

--*/

{
    PIRP irp;
    NTSTATUS status;
    PFILE_OBJECT fileObject;
    KPROCESSOR_MODE requestorMode;
    PETHREAD thread;
    BOOLEAN found = FALSE;
    PLIST_ENTRY header;
    PLIST_ENTRY entry;
    KIRQL irql;

    PAGED_CODE();


    //
    // Get the address of the current thread.  The thread contains a list of
    // the pending operations for this file.
    //

    thread = PsGetCurrentThread();

    //
    // Get the previous mode;  i.e., the mode of the caller.
    //

    requestorMode = KeGetPreviousModeByThread(&thread->Tcb);

    if (requestorMode != KernelMode) {

        //
        // The caller's access mode is user, so probe each of the arguments
        // and capture them as necessary.  If any failures occur, the condition
        // handler will be invoked to handle them.  It will simply cleanup and
        // return an access violation status code back to the system service
        // dispatcher.
        //

        try {

            //
            // The IoStatusBlock parameter must be writeable by the caller.
            //

            ProbeForWriteIoStatus( IoStatusBlock );

        } except(EXCEPTION_EXECUTE_HANDLER) {

            //
            // An exception was incurred attempting to probe the caller'
            // I/O status block.  Simply return an appropriate error status
            // code.
            //

            return GetExceptionCode();
        }
    }

    //
    // There were no blatant errors so far, so reference the file object so
    // the target device object can be found.  Note that if the handle does
    // not refer to a file object, or if the caller does not have the required
    // access to the file, then it will fail.
    //

    status = ObReferenceObjectByHandle( FileHandle,
                                        0,
                                        IoFileObjectType,
                                        requestorMode,
                                        (PVOID *) &fileObject,
                                        NULL );
    if (!NT_SUCCESS( status )) {
        return(status);
    }

    //
    // Note that here the I/O system would normally make a check to determine
    // whether or not the file was opened for synchronous I/O.  If it was, then
    // it would attempt to exclusively acquire the file object lock.  However,
    // since this service is attempting to cancel all of the I/O for the file,
    // it does not make much sense to wait until it has all completed before
    // attempting to cancel it.
    //


    //
    // Update the operation count statistic for the current process for
    // operations other than read and write.
    //

    IopUpdateOtherOperationCount();

    //
    // Walk the list of IRPs on the thread's pending I/O queue looking for IRPs
    // which specify the same file as the FileHandle refers to.  For each IRP
    // found, set its cancel flag.  If no IRPs are found, simply complete the
    // I/O here.  The only synchronization needed here is to block out all APCs
    // for this thread so that no I/O can complete and remove packets from the
    // queue.  No considerations need be made for multi-processing since this
    // thread can only be running on one processor at a time and this routine
    // has control of the thread for now.
    //

    KeRaiseIrql( APC_LEVEL, &irql );

    header = &thread->IrpList;
    entry = thread->IrpList.Flink;

    while (header != entry) {

        //
        // An IRP has been found for this thread.  If the IRP refers to the
        // appropriate file object, set its cancel flag and remember that it
        // was found;  otherwise, simply continue the loop.
        //

        irp = CONTAINING_RECORD( entry, IRP, ThreadListEntry );
        if (irp->Tail.Overlay.OriginalFileObject == fileObject) {
            found = TRUE;
            IoCancelIrp( irp );
        }

        entry = entry->Flink;
    }

    //
    // Lower the IRQL back down to what it was on entry to this procedure.
    //

    KeLowerIrql( irql );

    if (found) {

        LARGE_INTEGER interval;

        //
        // Delay execution for a time and let the request
        // finish.  The delay time is 10ms.
        //

        interval.QuadPart = -10 * 1000 * 10;

        //
        // Wait for a while so the canceled requests can complete.
        //

        while (found) {

            (VOID) KeDelayExecutionThread( KernelMode, FALSE, &interval );

            found = FALSE;

            //
            // Raise the IRQL to prevent modification to the IRP list by the
            // thread's APC routine.
            //

            KeRaiseIrql( APC_LEVEL, &irql );

            //
            // Check the IRP list for requests which refer to the specified
            // file object.
            //

            entry = thread->IrpList.Flink;

            while (header != entry) {

                //
                // An IRP has been found for this thread.  If the IRP refers
                // to the appropriate file object,  remember that it
                // was found;  otherwise, simply continue the loop.
                //

                irp = CONTAINING_RECORD( entry, IRP, ThreadListEntry );
                if (irp->Tail.Overlay.OriginalFileObject == fileObject) {
                    found = TRUE;
                    break;
                }

                entry = entry->Flink;
            }

            //
            // Lower the IRQL back down to what it was on entry to this procedure.
            //

            KeLowerIrql( irql );

        }
    }

    try {

        //
        // Write the status back to the user.
        //

        IoStatusBlock->Status = STATUS_SUCCESS;
        IoStatusBlock->Information = 0L;

    } except(EXCEPTION_EXECUTE_HANDLER) {

        //
        // An exception was incurred attempting to write the caller's
        // I/O status block; however, the service completed successfully so
        // just return success.
        //

    }

    //
    // Dereference the file object.
    //

    ObDereferenceObject( fileObject );

    return STATUS_SUCCESS;
}