Example #1
0
/*
    @implemented
*/
KSDDKAPI
NTSTATUS
NTAPI
KsCopyObjectBagItems(
    IN KSOBJECT_BAG ObjectBagDestination,
    IN KSOBJECT_BAG ObjectBagSource)
{
    PKSIOBJECT_BAG ObjectBagDest, ObjectBagSrc;
    PLIST_ENTRY Entry;
    PKSIOBJECT_BAG_ENTRY BagEntry;
    NTSTATUS Status = STATUS_SUCCESS;

    /* get object bag src */
    ObjectBagSrc = (PKSIOBJECT_BAG)ObjectBagSource;

    /* get object bag dst */
    ObjectBagDest = (PKSIOBJECT_BAG)ObjectBagDestination;

    /* acquire source mutex */
    KeWaitForSingleObject(ObjectBagSrc->BagMutex, Executive, KernelMode, FALSE, NULL);

    if (ObjectBagSrc->BagMutex != ObjectBagDest->BagMutex)
    {
        /* acquire destination mutex */
        KeWaitForSingleObject(ObjectBagDest->BagMutex, Executive, KernelMode, FALSE, NULL);
    }

    /* point to first item */
    Entry = ObjectBagSrc->ObjectList.Flink;
    /* first scan the list if the item is already inserted */
    while(Entry != &ObjectBagSrc->ObjectList)
    {
        /* get bag entry */
        BagEntry = (PKSIOBJECT_BAG_ENTRY)CONTAINING_RECORD(Entry, KSIOBJECT_BAG_ENTRY, Entry);

        /* add the item */
        Status = KsAddItemToObjectBag(ObjectBagDestination, BagEntry->Item, BagEntry->Free);

        /* check for success */
        if (!NT_SUCCESS(Status))
            break;

        /* move to next entry */
        Entry = Entry->Flink;
    }

    if (ObjectBagSrc->BagMutex != ObjectBagDest->BagMutex)
    {
        /* release destination mutex */
        KeReleaseMutex(ObjectBagDest->BagMutex, FALSE);
    }

    /* release source mutex */
     KeReleaseMutex(ObjectBagSrc->BagMutex, FALSE);

    return Status;
}
Example #2
0
u32 _rtw_down_sema(_sema *sema)
{

#ifdef PLATFORM_LINUX
	
	if (down_interruptible(sema))
		return _FAIL;
	else
		return _SUCCESS;

#endif    	
#ifdef PLATFORM_FREEBSD
	sema_wait(sema);
	return  _SUCCESS;
#endif
#ifdef PLATFORM_OS_XP

	if(STATUS_SUCCESS == KeWaitForSingleObject(sema, Executive, KernelMode, TRUE, NULL))
		return  _SUCCESS;
	else
		return _FAIL;
#endif

#ifdef PLATFORM_OS_CE
	if(WAIT_OBJECT_0 == WaitForSingleObject(*sema, INFINITE ))
		return _SUCCESS; 
	else
		return _FAIL;
#endif
}
Example #3
0
static
VOID
NTAPI
AcquireMutexThread(
    PVOID Parameter)
{
    PTHREAD_DATA ThreadData = Parameter;
    KIRQL Irql;
    BOOLEAN Ret = FALSE;
    NTSTATUS Status;

    KeRaiseIrql(ThreadData->Irql, &Irql);

    if (ThreadData->Try)
    {
        Ret = ThreadData->TryAcquire(ThreadData->Mutex);
        ok_eq_bool(Ret, ThreadData->RetExpected);
    }
    else
        ThreadData->Acquire(ThreadData->Mutex);

    ok_bool_false(KeSetEvent(&ThreadData->OutEvent, 0, TRUE), "KeSetEvent returned");
    Status = KeWaitForSingleObject(&ThreadData->InEvent, Executive, KernelMode, FALSE, NULL);
    ok_eq_hex(Status, STATUS_SUCCESS);

    if (!ThreadData->Try || Ret)
        ThreadData->Release(ThreadData->Mutex);

    KeLowerIrql(Irql);
}
Example #4
0
VOID DLDpWaitForResource(
    IN PERESOURCE Resource, 
    IN DISPATCHER_HEADER *DispatcherObject,
    IN PTHREAD_STRUCT ThrdStruct
    ) {
    KIRQL oldIrql;
    ULONG ResourceWaitCount = 0;

    Resource->ContentionCount++;

    while (KeWaitForSingleObject(DispatcherObject,Executive,KernelMode,FALSE,&DLDpTimeout) == STATUS_TIMEOUT) {
        KeAcquireSpinLock(&Resource->SpinLock, &oldIrql);
        if (++ResourceWaitCount>DLDpResourceTimeoutCount) {
            // May be deadlock?
            ResourceWaitCount = 0;

            if (DLDProcessResource(Resource, ThrdStruct,DLD_MAX_REC_LEVEL)) {
                UDFPrint((" which thread %x has tried to acquire at (BugCheckId:%x:Line:%d)\n",
                ThrdStruct->ThreadId,
                ThrdStruct->BugCheckId,
                ThrdStruct->Line      
                ));
                BrutePoint();
            }
        } 
        // Priority boosts
        // .....
        // End of priority boosts
        KeReleaseSpinLock(&Resource->SpinLock, oldIrql);
    }

}        
Example #5
0
/*! .

	\param [in]
	\param [out]
	\param [in,out]

	\pre
	\post
	\return

*/
NTSTATUS
FlTimerThreadStop()
{
    LARGE_INTEGER tend_timeout;


    DBGPRINT("[flmonflt] Stopping timer thread.\n");

    tend_timeout.QuadPart = RELATIVE(SECONDS(8));
    TimerThreadStopExec = TRUE;


    KeCancelTimer(DriverInfoData->Timer);
    KeSetEvent(DriverInfoData->TimerThreadSleepWakeup, 0, FALSE);

    DBGPRINT("[flmonflt] Waiting for thread to exit.\n");
    KeWaitForSingleObject(DriverInfoData->TimerThread, Executive, KernelMode, TRUE, &tend_timeout);

    DBGPRINT("[flmonflt] Thread exited, dereferencing object.\n");
    ObDereferenceObject(DriverInfoData->TimerThread);

    DBGPRINT("[flmonflt] Thread dereferenced.\n");

    return STATUS_SUCCESS;
}
Example #6
0
NTSTATUS EncryptedIoQueueStop (EncryptedIoQueue *queue)
{
	ASSERT (!queue->StopPending);
	queue->StopPending = TRUE;
	
	while (InterlockedExchangeAdd (&queue->OutstandingIoCount, 0) > 0)
	{
		KeWaitForSingleObject (&queue->NoOutstandingIoEvent, Executive, KernelMode, FALSE, NULL);
	}

	Dump ("Queue stopping  out=%d\n", queue->OutstandingIoCount);

	queue->ThreadExitRequested = TRUE;

	TCStopThread (queue->MainThread, &queue->MainThreadQueueNotEmptyEvent);
	TCStopThread (queue->IoThread, &queue->IoThreadQueueNotEmptyEvent);
	TCStopThread (queue->CompletionThread, &queue->CompletionThreadQueueNotEmptyEvent);

	TCfree (queue->FragmentBufferA);
	TCfree (queue->FragmentBufferB);
	TCfree (queue->ReadAheadBuffer);

	FreePoolBuffers (queue);

	Dump ("Queue stopped  out=%d\n", queue->OutstandingIoCount);
	return STATUS_SUCCESS;
}
Example #7
0
void dtrace_hook_int(UCHAR ivec, void (*InterruptHandler)( void ), uintptr_t *paddr)
{
	INT_VECTOR OrgVec;
	int i;
	PRKDPC Dpc;

	cpunos = 0;
	if (paddr != 0) {
		BackupInterrupt(ivec, &OrgVec);
#ifdef _AMD64_
   		*(ULONG64 *)paddr = VEC_OFFSET_TO_ADDR(OrgVec);
#else
		*(ULONG32 *)paddr = VEC_OFFSET_TO_ADDR(OrgVec);
#endif
   	}

   	Dpc = (PRKDPC) ExAllocatePoolWithTag(NonPagedPool, sizeof(KDPC)*KeNumberProcessors, 'Tag1');
   	for (i = 0; i < KeNumberProcessors; i++) {
		KeInitializeDpc(&Dpc[i], hook_init, NULL);
	}
	
	KeInitializeEvent(&SyncIDT, NotificationEvent, FALSE);
	for (i=0; i < KeNumberProcessors; i++) {
		KeSetTargetProcessorDpc(&Dpc[i], (char) i);
		KeSetImportanceDpc(&Dpc[i], HighImportance);
		KeInsertQueueDpc(&Dpc[i], (PVOID) ivec, (PVOID)InterruptHandler);
	}
	
	KeWaitForSingleObject(&SyncIDT,Executive,KernelMode,0,NULL);
    	KeClearEvent(&SyncIDT);
   	ExFreePoolWithTag(Dpc, 'Tag1');
}
Example #8
0
/*
 * @implemented
 */
VOID
WaitForOnlinesToComplete(IN PDEVICE_EXTENSION DeviceExtension)
{
    KIRQL OldIrql;

    KeInitializeEvent(&(DeviceExtension->OnlineNotificationEvent), NotificationEvent, FALSE);

    KeAcquireSpinLock(&(DeviceExtension->WorkerLock), &OldIrql);

    /* Just wait all the worker are done */
    if (DeviceExtension->OnlineNotificationCount != 1)
    {
        DeviceExtension->OnlineNotificationCount--;
        KeReleaseSpinLock(&(DeviceExtension->WorkerLock), OldIrql);

        KeWaitForSingleObject(&(DeviceExtension->OnlineNotificationEvent),
                              Executive,
                              KernelMode,
                              FALSE,
                              NULL);

        KeAcquireSpinLock(&(DeviceExtension->WorkerLock), &OldIrql);
        DeviceExtension->OnlineNotificationCount++;
    }

    KeReleaseSpinLock(&(DeviceExtension->WorkerLock), OldIrql);
}
int FlFdcDeviceIo(int DeviceObject , int Ioctl , int Data ) 
{ int ntStatus ;
  int irp ;
  int irpStack ;
  int doneEvent = __VERIFIER_nondet_int() ;
  int ioStatus = __VERIFIER_nondet_int() ;
  int irp__Tail__Overlay__CurrentStackLocation = __VERIFIER_nondet_int() ;
  int irpStack__Parameters__DeviceIoControl__Type3InputBuffer ;
  long __cil_tmp11 ;

  {
  {
  irp = IoBuildDeviceIoControlRequest(Ioctl, DeviceObject, 0, 0, 0, 0, 1, doneEvent,
                                      ioStatus);
  }
  if (irp == 0) {
    return (-1073741670);
  }
  {
  irpStack = irp__Tail__Overlay__CurrentStackLocation - 1;
  irpStack__Parameters__DeviceIoControl__Type3InputBuffer = Data;
  ntStatus = IofCallDriver(DeviceObject, irp);
  }
  {
  __cil_tmp11 = (long )ntStatus;
  if (__cil_tmp11 == 259L) {
    {
    KeWaitForSingleObject(doneEvent, Suspended, KernelMode, 0, 0);
    ntStatus = myStatus;
    }
  }
  }
  return (ntStatus);
}
}
Example #10
0
NTSTATUS
ForwardIrpAndWait(
    IN PDEVICE_OBJECT DeviceObject,
    IN PIRP Irp)
{
    PDEVICE_OBJECT LowerDevice = ((PSERIAL_DEVICE_EXTENSION)DeviceObject->DeviceExtension)->LowerDevice;
    KEVENT Event;
    NTSTATUS Status;

    ASSERT(LowerDevice);

    KeInitializeEvent(&Event, NotificationEvent, FALSE);
    IoCopyCurrentIrpStackLocationToNext(Irp);

    TRACE_(SERIAL, "Calling lower device %p\n", LowerDevice);
    IoSetCompletionRoutine(Irp, ForwardIrpAndWaitCompletion, &Event, TRUE, TRUE, TRUE);

    Status = IoCallDriver(LowerDevice, Irp);
    if (Status == STATUS_PENDING)
    {
        Status = KeWaitForSingleObject(&Event, Suspended, KernelMode, FALSE, NULL);
        if (NT_SUCCESS(Status))
            Status = Irp->IoStatus.Status;
    }

    return Status;
}
Example #11
0
/*
 * @implemented
 */
VOID
NTAPI
FsRtlpPostStackOverflow(IN PVOID Context,
                        IN PKEVENT Event,
                        IN PFSRTL_STACK_OVERFLOW_ROUTINE StackOverflowRoutine,
                        IN BOOLEAN IsPaging)
{
    PSTACK_OVERFLOW_WORK_ITEM WorkItem;

    /* Try to allocate a work item */
    WorkItem = ExAllocatePoolWithTag(NonPagedPool, sizeof(STACK_OVERFLOW_WORK_ITEM), 'FSrs');
    if (WorkItem == NULL)
    {
        /* If we failed, and we are not a paging file, just raise an error */
        if (!IsPaging)
        {
            RtlRaiseStatus(STATUS_INSUFFICIENT_RESOURCES);
        }

        /* Otherwise, wait for fallback workitem to be available and use it */
        KeWaitForSingleObject(&StackOverflowFallbackSerialEvent, Executive, KernelMode, FALSE, NULL);
        WorkItem = &StackOverflowFallback;
    }

    /* Initialize work item */
    WorkItem->Context = Context;
    WorkItem->Event = Event;
    WorkItem->Routine = StackOverflowRoutine;
    ExInitializeWorkItem(&WorkItem->WorkItem, FsRtlStackOverflowRead, WorkItem);

    /* And queue it in the appropriate queue (paging or not?) */
    KeInsertQueue(&FsRtlWorkerQueues[IsPaging], &WorkItem->WorkItem.List);
}
Example #12
0
NTSTATUS
NTAPI
PciCallDownIrpStack(IN PPCI_FDO_EXTENSION DeviceExtension,
                    IN PIRP Irp)
{
    NTSTATUS Status;
    KEVENT Event;
    PAGED_CODE();
    DPRINT1("PciCallDownIrpStack ...\n");
    ASSERT_FDO(DeviceExtension);

    /* Initialize the wait event */
    KeInitializeEvent(&Event, SynchronizationEvent, 0);

    /* Setup a completion routine */
    IoCopyCurrentIrpStackLocationToNext(Irp);
    IoSetCompletionRoutine(Irp, PciSetEventCompletion, &Event, TRUE, TRUE, TRUE);

    /* Call the attached device */
    Status = IoCallDriver(DeviceExtension->AttachedDeviceObject, Irp);
    if (Status == STATUS_PENDING)
    {
        /* Wait for it to complete the request, and get its status */
        KeWaitForSingleObject(&Event, Executive, KernelMode, FALSE, NULL);
        Status = Irp->IoStatus.Status;
    }

    /* Return that status back to the caller */
    return Status;
}
Example #13
0
NTSTATUS
NTAPI
PcRequestNewPowerState(
    IN  PDEVICE_OBJECT DeviceObject,
    IN  DEVICE_POWER_STATE RequestedNewState)
{
    KEVENT Event;
    NTSTATUS Status;
    POWER_STATE PowerState;
    PPCLASS_DEVICE_EXTENSION DeviceExt;

    PC_ASSERT_IRQL_EQUAL(PASSIVE_LEVEL);

    if (!DeviceObject || !RequestedNewState)
        return STATUS_INVALID_PARAMETER;

    DeviceExt = (PPCLASS_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
    KeInitializeEvent(&Event, SynchronizationEvent, FALSE);

    PowerState.DeviceState = RequestedNewState;
    PowerState.SystemState = PowerSystemUnspecified;

    Status = PoRequestPowerIrp(DeviceExt->PhysicalDeviceObject, IRP_MN_SET_POWER, PowerState, PwrCompletionCallback, (PVOID)&Event, NULL);
    if (NT_SUCCESS(Status))
    {
        KeWaitForSingleObject((PVOID)&Event, Executive, KernelMode, FALSE, NULL);
    }


    return Status;
}
Example #14
0
static void AcquireFragmentBuffer (EncryptedIoQueue *queue, byte *buffer)
{
	NTSTATUS status = STATUS_INVALID_PARAMETER;

	if (buffer == queue->FragmentBufferA)
	{
		status = KeWaitForSingleObject (&queue->FragmentBufferAFreeEvent, Executive, KernelMode, FALSE, NULL);
	}
	else if (buffer == queue->FragmentBufferB)
	{
		status = KeWaitForSingleObject (&queue->FragmentBufferBFreeEvent, Executive, KernelMode, FALSE, NULL);
	}

	if (!NT_SUCCESS (status))
		TC_BUG_CHECK (status);
}
VOID DestroyNodeEventHandlerVisitor(PVOID context, UINT key, PVOID value)
{
	NTSTATUS status;
	PIRP irp = NULL;
	unsigned int i = 0;
	KEVENT irp_complete_event;
	IO_STATUS_BLOCK io_status_block;
	NodeEventHandler* node_event_handler = NULL;
	EventHandlerManager* event_handler_manager = NULL;

	node_event_handler = (NodeEventHandler*)value;
	event_handler_manager = (EventHandlerManager*)context;

	if(node_event_handler == NULL ||
		event_handler_manager == NULL )
		return;

	KeInitializeEvent(&irp_complete_event, NotificationEvent, FALSE);

	// For each hooked event handler send an IRP to set the event handler
	// back to what it originally was
	for(i = 0; i < TDI_EVENT_HANDLERS_MAX; i++)
	{
		PFILE_OBJECT node = node_event_handler->handlers[i].node;
		TdiEventHandler* original_handler = &node_event_handler->handlers[i].original_handler;

		if(original_handler->EventHandler == NULL)
			continue;

		irp = TdiBuildInternalDeviceControlIrp(TDI_SET_EVENT_HANDLER, event_handler_manager->connection_manager->device, node, 
			&irp_complete_event, &io_status_block);

		if(irp == NULL)
			continue;

		TdiBuildSetEventHandler(irp, event_handler_manager->connection_manager->device, node, NULL, NULL, 
			original_handler->EventType, original_handler->EventHandler, original_handler->EventContext);

		status = IoCallDriver(event_handler_manager->connection_manager->next_device, irp);

		if(status == STATUS_PENDING)                                
		{
			// Wait for the IRP to finish
			KeWaitForSingleObject((PVOID)&irp_complete_event, Executive, KernelMode, TRUE, NULL); 
			status = io_status_block.Status; 
		}

		if(status == STATUS_SUCCESS)
		{
			DbgPrint("EventHandlerManager: Successfully set original event handler n=%08x t=%08x\n", node, original_handler->EventType);
		}
		else
		{
			DbgPrint("EventHandlerManager: Failed to set original event handler - code=%08x n=%08x t=%08x\n", status, node, original_handler->EventType);
		}

		KeResetEvent(&irp_complete_event);
	}
}
Example #16
0
/*
    @implemented
*/
NTSTATUS
NTAPI
KsAddItemToObjectBag(
    IN KSOBJECT_BAG  ObjectBag,
    IN PVOID  Item,
    IN PFNKSFREE  Free  OPTIONAL)
{
    PKSIOBJECT_BAG Bag;
    PKSIOBJECT_BAG_ENTRY BagEntry;

    DPRINT("KsAddItemToObjectBag\n");

    /* get real object bag */
    Bag = (PKSIOBJECT_BAG)ObjectBag;

    /* acquire bag mutex */
    KeWaitForSingleObject(Bag->BagMutex, Executive, KernelMode, FALSE, NULL);

    /* is the item already present in this object bag */
    BagEntry = KspFindObjectBagItem(&Bag->ObjectList, Item);

    if (BagEntry)
    {
        /* is is, update reference count */
        InterlockedIncrement((PLONG)&BagEntry->References);
        /* release mutex */
        KeReleaseMutex(Bag->BagMutex, FALSE);
        /* return result */
        return STATUS_SUCCESS;
    }

    /* item is new, allocate entry */
    BagEntry = AllocateItem(NonPagedPool, sizeof(KSIOBJECT_BAG_ENTRY));
    if (!BagEntry)
    {
        /* no memory */
        KeReleaseMutex(Bag->BagMutex, FALSE);
        /* return result */
        return STATUS_INSUFFICIENT_RESOURCES;
    }

    /* initialize bag entry */
    BagEntry->References = 1;
    BagEntry->Item = Item;
    if (Free)
        BagEntry->Free = Free;
    else
        BagEntry->Free = ExFreePool;

    /* insert item */
    InsertTailList(&Bag->ObjectList, &BagEntry->Entry);

    /* release mutex */
    KeReleaseMutex(Bag->BagMutex, FALSE);

    /* done */
    return STATUS_SUCCESS;
}
Example #17
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;
}
Example #18
0
NTSTATUS
NTAPI
IKsDevice_fnAcquireDevice(
    IN IKsDevice * iface)
{
    PKSIDEVICE_HEADER This = (PKSIDEVICE_HEADER)CONTAINING_RECORD(iface, KSIDEVICE_HEADER, BasicHeader.OuterUnknown);

    return KeWaitForSingleObject(&This->DeviceMutex, Executive, KernelMode, FALSE, NULL);
}
Example #19
0
VOID EnterCriticalSection(LPCRITICAL_SECTION CritSect)
{
    KeWaitForSingleObject((PKMUTEX)CritSect,
                          Executive,
                          KernelMode,
                          FALSE,
                          0);

}
Example #20
0
//
// find bridge limit worker [checked]
//
UCHAR PciFindBridgeNumberLimitWorker(__in PPCI_FDO_EXTENSION StartFdoExt,__in PPCI_FDO_EXTENSION CurFdoExt,__in UCHAR BaseBus,__out PBOOLEAN Include)
{
	PAGED_CODE();

	if(CurFdoExt != StartFdoExt)
	{
		KeEnterCriticalRegion();
		KeWaitForSingleObject(&CurFdoExt->ChildListLock,Executive,KernelMode,FALSE,0);
	}

	PPCI_PDO_EXTENSION ChildBridgeExt					= CurFdoExt->ChildBridgePdoList;
	UCHAR Limit											= 0;
	if(ChildBridgeExt)
	{
		while(ChildBridgeExt)
		{
			if(ChildBridgeExt->NotPresent)
			{
				PciDebugPrintf(0x100000,"Skipping not present bridge PDOX @ %p\n",ChildBridgeExt);
			}
			else if(PciAreBusNumbersConfigured(ChildBridgeExt))
			{
				if(ChildBridgeExt->Dependent.type1.SecondaryBus > BaseBus && (ChildBridgeExt->Dependent.type1.SecondaryBus < Limit || !Limit))
					Limit								= ChildBridgeExt->Dependent.type1.SecondaryBus;
			}

			ChildBridgeExt								= ChildBridgeExt->NextBridge;
		}
	}

	if(Limit)
	{
		*Include										= FALSE;
	}
	else
	{
		if(CurFdoExt->ParentFdoExtension)
		{
			Limit										= PciFindBridgeNumberLimitWorker(StartFdoExt,CurFdoExt->ParentFdoExtension,BaseBus,Include);
		}
		else
		{
			Limit										= CurFdoExt->MaxSubordinateBus;
			*Include									= TRUE;
		}
	}

	if(CurFdoExt != StartFdoExt)
	{
		KeSetEvent(&CurFdoExt->ChildListLock,IO_NO_INCREMENT,FALSE);
		KeLeaveCriticalRegion();
	}

	return Limit;
}
Example #21
0
BOOLEAN
NTAPI
FsRecGetDeviceSectors(IN PDEVICE_OBJECT DeviceObject,
                      IN ULONG SectorSize,
                      OUT PLARGE_INTEGER SectorCount)
{
    PARTITION_INFORMATION PartitionInfo;
    IO_STATUS_BLOCK IoStatusBlock;
    KEVENT Event;
    PIRP Irp;
    NTSTATUS Status;
    ULONG Remainder;
    PAGED_CODE();

    /* Only needed for disks */
    if (DeviceObject->DeviceType != FILE_DEVICE_DISK) return FALSE;

    /* Build the information IRP */
    KeInitializeEvent(&Event, SynchronizationEvent, FALSE);
    Irp = IoBuildDeviceIoControlRequest(IOCTL_DISK_GET_PARTITION_INFO,
                                        DeviceObject,
                                        NULL,
                                        0,
                                        &PartitionInfo,
                                        sizeof(PARTITION_INFORMATION),
                                        FALSE,
                                        &Event,
                                        &IoStatusBlock);
    if (!Irp) return FALSE;

    /* Override verification */
    IoGetNextIrpStackLocation(Irp)->Flags |= SL_OVERRIDE_VERIFY_VOLUME;

    /* Do the request */
    Status = IoCallDriver(DeviceObject, Irp);
    if (Status == STATUS_PENDING)
    {
        /* Wait for completion */
        KeWaitForSingleObject(&Event,
                              Executive,
                              KernelMode,
                              FALSE,
                              NULL);
        Status = IoStatusBlock.Status;
    }

    /* Fail if we couldn't get the data */
    if (!NT_SUCCESS(Status)) return FALSE;

    /* Otherwise, return the number of sectors */
    *SectorCount = RtlExtendedLargeIntegerDivide(PartitionInfo.PartitionLength,
                                                 SectorSize,
                                                 &Remainder);
    return TRUE;
}
Example #22
0
/*
 * @implemented
 */
VOID
SendOnlineNotification(IN PUNICODE_STRING SymbolicName)
{
    PIRP Irp;
    KEVENT Event;
    NTSTATUS Status;
    PFILE_OBJECT FileObject;
    PIO_STACK_LOCATION Stack;
    PDEVICE_OBJECT DeviceObject;
    IO_STATUS_BLOCK IoStatusBlock;

    /* Get device object */
    Status = IoGetDeviceObjectPointer(SymbolicName,
                                      FILE_READ_ATTRIBUTES,
                                      &FileObject,
                                      &DeviceObject);
    if (!NT_SUCCESS(Status))
    {
        return;
    }

    /* And attached device object */
    DeviceObject = IoGetAttachedDeviceReference(FileObject->DeviceObject);

    /* And send VOLUME_ONLINE */
    KeInitializeEvent(&Event, NotificationEvent, FALSE);
    Irp = IoBuildDeviceIoControlRequest(IOCTL_VOLUME_ONLINE,
                                        DeviceObject,
                                        NULL, 0,
                                        NULL, 0,
                                        FALSE,
                                        &Event,
                                        &IoStatusBlock);
    if (!Irp)
    {
        goto Cleanup;
    }

    Stack = IoGetNextIrpStackLocation(Irp);
    Stack->FileObject = FileObject;

    Status = IoCallDriver(DeviceObject, Irp);
    if (Status == STATUS_PENDING)
    {
        KeWaitForSingleObject(&Event, Executive, KernelMode, FALSE, NULL);
    }

Cleanup:
    ObDereferenceObject(DeviceObject);
    ObDereferenceObject(FileObject);

    return;
}
Example #23
0
VBOXDRVTOOL_DECL(NTSTATUS) VBoxDrvToolIoPostSync(PDEVICE_OBJECT pDevObj, PIRP pIrp)
{
    KEVENT Event;
    KeInitializeEvent(&Event, NotificationEvent, FALSE);
    NTSTATUS Status = VBoxDrvToolIoPostAsync(pDevObj, pIrp, &Event);
    if (Status == STATUS_PENDING)
    {
        KeWaitForSingleObject(&Event, Executive, KernelMode, FALSE, NULL);
        Status = pIrp->IoStatus.Status;
    }
    return Status;
}
Example #24
0
static NTSTATUS
HalpXboxReadSector(IN PDEVICE_OBJECT DeviceObject,
                   IN ULONG SectorSize,
                   IN PLARGE_INTEGER SectorOffset,
                   OUT PVOID Sector)
{
    IO_STATUS_BLOCK StatusBlock;
    KEVENT Event;
    PIRP Irp;
    NTSTATUS Status;

    DPRINT("HalpXboxReadSector(%p %lu 0x%08x%08x %p)\n",
           DeviceObject, SectorSize, SectorOffset->u.HighPart, SectorOffset->u.LowPart, Sector);

    ASSERT(DeviceObject);
    ASSERT(Sector);

    KeInitializeEvent(&Event,
                      NotificationEvent,
                      FALSE);

    /* Read the sector */
    Irp = IoBuildSynchronousFsdRequest(IRP_MJ_READ,
                                       DeviceObject,
                                       Sector,
                                       SectorSize,
                                       SectorOffset,
                                       &Event,
                                       &StatusBlock);
    if (!Irp) return STATUS_INSUFFICIENT_RESOURCES;

    Status = IoCallDriver(DeviceObject,
                          Irp);
    if (Status == STATUS_PENDING)
    {
        KeWaitForSingleObject(&Event,
                              Executive,
                              KernelMode,
                              FALSE,
                              NULL);
        Status = StatusBlock.Status;
    }

    if (!NT_SUCCESS(Status))
    {
        DPRINT("Reading sector failed (Status 0x%08lx)\n", Status);
        return Status;
    }

    return Status;
}
Example #25
0
NTSTATUS ForwardAndWait(PGENERIC_EXTENSION pdx, PIRP Irp)
	{							// ForwardAndWait
	PAGED_CODE();
	
	KEVENT event;
	KeInitializeEvent(&event, NotificationEvent, FALSE);

	IoCopyCurrentIrpStackLocationToNext(Irp);
	IoSetCompletionRoutine(Irp, (PIO_COMPLETION_ROUTINE) OnRequestComplete,
		(PVOID) &event, TRUE, TRUE, TRUE);

	IoCallDriver(pdx->LowerDeviceObject, Irp);
	KeWaitForSingleObject(&event, Executive, KernelMode, FALSE, NULL);
	return Irp->IoStatus.Status;
	}							// ForwardAndWait
Example #26
0
NTSTATUS EncryptedIoQueueHoldWhenIdle (EncryptedIoQueue *queue, int64 timeout)
{
	NTSTATUS status;
	ASSERT (!queue->Suspended);

	queue->SuspendPending = TRUE;
	
	while (TRUE)
	{
		while (InterlockedExchangeAdd (&queue->OutstandingIoCount, 0) > 0)
		{
			LARGE_INTEGER waitTimeout;

			waitTimeout.QuadPart = timeout * -10000;
			status = KeWaitForSingleObject (&queue->NoOutstandingIoEvent, Executive, KernelMode, FALSE, timeout != 0 ? &waitTimeout : NULL);

			if (status == STATUS_TIMEOUT)
				status = STATUS_UNSUCCESSFUL;

			if (!NT_SUCCESS (status))
			{
				queue->SuspendPending = FALSE;
				return status;
			}

			TCSleep (1);
			if (InterlockedExchangeAdd (&queue->OutstandingIoCount, 0) > 0)
			{
				queue->SuspendPending = FALSE;
				return STATUS_UNSUCCESSFUL;
			}
		}

		KeClearEvent (&queue->QueueResumedEvent);
		queue->Suspended = TRUE;

		if (InterlockedExchangeAdd (&queue->OutstandingIoCount, 0) == 0)
			break;

		queue->Suspended = FALSE;
		KeSetEvent (&queue->QueueResumedEvent, IO_DISK_INCREMENT, FALSE);
	}

	queue->ReadAheadBufferValid = FALSE;

	queue->SuspendPending = FALSE;
	return STATUS_SUCCESS;
}
Example #27
0
NTSTATUS SendDIOC(PUNICODE_STRING uDeviceName, ULONG IoControlCode,PVOID InputBuffer,ULONG InputBufferLength,PVOID OutputBuffer,ULONG OutputBufferLength)
{
	HANDLE              hPidDrv;
	OBJECT_ATTRIBUTES   ObjAttr;
	IO_STATUS_BLOCK     ioStatus;
	PDEVICE_OBJECT      DevObj;
	PFILE_OBJECT        fileObject;
	NTSTATUS            ntStatus;
	KEVENT              Event;
	PIRP                Irp;
	//	PIO_STACK_LOCATION irpSp;
	//	RtlInitUnicodeString(&us,L"\\Device\\"KLPID_NAME);
	
	InitializeObjectAttributes(&ObjAttr,uDeviceName,OBJ_CASE_INSENSITIVE,NULL,NULL);
	ntStatus=ZwCreateFile(&hPidDrv,SYNCHRONIZE|FILE_ANY_ACCESS,&ObjAttr,&ioStatus,NULL,0,FILE_SHARE_READ|FILE_SHARE_WRITE,FILE_OPEN,FILE_SYNCHRONOUS_IO_NONALERT,NULL,0);
	if(NT_SUCCESS(ntStatus)) {
		ntStatus=ObReferenceObjectByHandle(hPidDrv,FILE_READ_DATA,NULL,KernelMode,(PVOID*)&fileObject,NULL);
		if(NT_SUCCESS(ntStatus)) {
			if((DevObj=IoGetRelatedDeviceObject(fileObject))!=NULL) {
				KeInitializeEvent(&Event,NotificationEvent,FALSE);
				Irp=IoBuildDeviceIoControlRequest(IoControlCode,DevObj,InputBuffer,InputBufferLength,OutputBuffer,OutputBufferLength,FALSE,&Event,&ioStatus);
				if(Irp!=NULL) {
					//					irpSp=IoGetNextIrpStackLocation(Irp);
					//					irpSp->FileObject = fileObject;
					ntStatus=IoCallDriver(DevObj,Irp);
					if(ntStatus==STATUS_PENDING) {
						KeWaitForSingleObject(&Event,Executive,KernelMode,FALSE,(PLARGE_INTEGER)NULL);
						ntStatus = ioStatus.Status;
					}
				} else {
					//					HOOKKdPrint(4, ("HOOK: IoBuildDeviceIoControlRequest failed\n"));
					ntStatus=STATUS_UNSUCCESSFUL;
				}
			} else {
				//				HOOKKdPrint(1, ("HOOK: IoGetRelatedDeviceObject %S failed \n",us.Buffer));
				ntStatus=STATUS_UNSUCCESSFUL;
			}
			ObDereferenceObject(fileObject);
		} else {
			//			HOOKKdPrint(1, ("HOOK: ObReferenceObjectByHandle %S failed status=%x\n",us.Buffer,ntStatus));
		}
		ZwClose(hPidDrv);
	} else {
		//		HOOKKdPrint(1, ("HOOK: ZwCreateFile %S failed status=%x\n",us.Buffer,ntStatus));
	}
	return ntStatus;
}
Example #28
0
static VOID CompletionThreadProc (PVOID threadArg)
{
	EncryptedIoQueue *queue = (EncryptedIoQueue *) threadArg;
	PLIST_ENTRY listEntry;
	EncryptedIoRequest *request;
	UINT64_STRUCT dataUnit;

	if (IsEncryptionThreadPoolRunning())
		KeSetPriorityThread (KeGetCurrentThread(), LOW_REALTIME_PRIORITY);

	while (!queue->ThreadExitRequested)
	{
		if (!NT_SUCCESS (KeWaitForSingleObject (&queue->CompletionThreadQueueNotEmptyEvent, Executive, KernelMode, FALSE, NULL)))
			continue;

		if (queue->ThreadExitRequested)
			break;

		while ((listEntry = ExInterlockedRemoveHeadList (&queue->CompletionThreadQueue, &queue->CompletionThreadQueueLock)))
		{
			request = CONTAINING_RECORD (listEntry, EncryptedIoRequest, CompletionListEntry);

			if (request->EncryptedLength > 0 && NT_SUCCESS (request->Item->Status))
			{
				ASSERT (request->EncryptedOffset + request->EncryptedLength <= request->Offset.QuadPart + request->Length);
				dataUnit.Value = (request->Offset.QuadPart + request->EncryptedOffset) / ENCRYPTION_DATA_UNIT_SIZE;

				if (queue->CryptoInfo->bPartitionInInactiveSysEncScope)
					dataUnit.Value += queue->CryptoInfo->FirstDataUnitNo.Value;
				else if (queue->RemapEncryptedArea)
					dataUnit.Value += queue->RemappedAreaDataUnitOffset;

				DecryptDataUnits (request->Data + request->EncryptedOffset, &dataUnit, request->EncryptedLength / ENCRYPTION_DATA_UNIT_SIZE, queue->CryptoInfo);
			}

			if (request->CompleteOriginalIrp)
			{
				CompleteOriginalIrp (request->Item, request->Item->Status,
					NT_SUCCESS (request->Item->Status) ? request->Item->OriginalLength : 0);
			}

			ReleasePoolBuffer (queue, request);
		}
	}

	PsTerminateSystemThread (STATUS_SUCCESS);
}
Example #29
0
static
VOID
FinishThread(
    PTHREAD_DATA ThreadData)
{
    NTSTATUS Status = STATUS_SUCCESS;

    KeSetEvent(&ThreadData->InEvent, 0, TRUE);
    Status = KeWaitForSingleObject(ThreadData->Thread, Executive, KernelMode, FALSE, NULL);
    ok_eq_hex(Status, STATUS_SUCCESS);

    ObDereferenceObject(ThreadData->Thread);
    Status = ZwClose(ThreadData->Handle);
    ok_eq_hex(Status, STATUS_SUCCESS);
    KeClearEvent(&ThreadData->InEvent);
    KeClearEvent(&ThreadData->OutEvent);
}
Example #30
0
VOID
ParReleasePortInfoToPortDevice(
    IN  PDEVICE_EXTENSION   Extension
)

/*++

Routine Description:

    This routine will release the port information back to the port driver.

Arguments:

    Extension   - Supplies the device extension.

Return Value:

    None.

--*/

{
    KEVENT          event;
    PIRP            irp;
    IO_STATUS_BLOCK ioStatus;
    NTSTATUS        status;

    KeInitializeEvent(&event, NotificationEvent, FALSE);

    irp = IoBuildDeviceIoControlRequest(IOCTL_INTERNAL_RELEASE_PARALLEL_PORT_INFO,
                                        Extension->PortDeviceObject,
                                        NULL, 0, NULL, 0,
                                        TRUE, &event, &ioStatus);

    if (!irp) {
        return;
    }

    status = IoCallDriver(Extension->PortDeviceObject, irp);

    if (!NT_SUCCESS(status)) {
        return;
    }

    KeWaitForSingleObject(&event, Executive, KernelMode, FALSE, NULL);
}