예제 #1
1
파일: adapter.cpp 프로젝트: GYGit/reactos
NTSTATUS
NTAPI
PcRegisterSubdevice(
    IN  PDEVICE_OBJECT DeviceObject,
    IN  PWCHAR Name,
    IN  PUNKNOWN Unknown)
{
    PPCLASS_DEVICE_EXTENSION DeviceExt;
    NTSTATUS Status;
    ISubdevice *SubDevice;
    UNICODE_STRING SymbolicLinkName;
    PSUBDEVICE_DESCRIPTOR SubDeviceDescriptor;
    ULONG Index;
    UNICODE_STRING RefName;
    PSYMBOLICLINK_ENTRY SymEntry;

    DPRINT("PcRegisterSubdevice DeviceObject %p Name %S Unknown %p\n", DeviceObject, Name, Unknown);

    PC_ASSERT_IRQL_EQUAL(PASSIVE_LEVEL);

    // check if all parameters are valid
    if (!DeviceObject || !Name || !Unknown)
    {
        DPRINT("PcRegisterSubdevice invalid parameter\n");
        return STATUS_INVALID_PARAMETER;
    }

    // get device extension
    DeviceExt = (PPCLASS_DEVICE_EXTENSION)DeviceObject->DeviceExtension;

    if (!DeviceExt)
    {
        // should not happen
        DbgBreakPoint();
        return STATUS_UNSUCCESSFUL;
    }

    // look up our undocumented interface
    Status = Unknown->QueryInterface(IID_ISubdevice, (LPVOID*)&SubDevice);
    if (!NT_SUCCESS(Status))
    {
        DPRINT("No ISubdevice interface\n");
        // the provided port driver doesnt support ISubdevice
        return STATUS_INVALID_PARAMETER;
    }

    // get the subdevice descriptor
    Status = SubDevice->GetDescriptor(&SubDeviceDescriptor);
    if (!NT_SUCCESS(Status))
    {
        DPRINT("Failed to get subdevice descriptor %x\n", Status);
        SubDevice->Release();
        return STATUS_UNSUCCESSFUL;
    }

    // add an create item to the device header
    Status = KsAddObjectCreateItemToDeviceHeader(DeviceExt->KsDeviceHeader, PcCreateItemDispatch, (PVOID)SubDevice, Name, NULL);
    if (!NT_SUCCESS(Status))
    {
        // failed to attach
        SubDevice->Release();
        DPRINT("KsAddObjectCreateItemToDeviceHeader failed with %x\n", Status);
        return Status;
    }

    // initialize reference string
    RtlInitUnicodeString(&RefName, Name);
    RtlInitUnicodeString(&SubDeviceDescriptor->RefString, Name);

    for(Index = 0; Index < SubDeviceDescriptor->InterfaceCount; Index++)
    {
        // FIXME
        // check if reference string with that name already exists
        
        Status = IoRegisterDeviceInterface(DeviceExt->PhysicalDeviceObject,
                                           &SubDeviceDescriptor->Interfaces[Index],
                                           &RefName,
                                           &SymbolicLinkName);

        if (NT_SUCCESS(Status))
        {
            // activate device interface
            IoSetDeviceInterfaceState(&SymbolicLinkName, TRUE);
            // allocate symbolic link entry
            SymEntry = (PSYMBOLICLINK_ENTRY)AllocateItem(NonPagedPool, sizeof(SYMBOLICLINK_ENTRY), TAG_PORTCLASS);
            if (SymEntry)
            {
                // initialize symbolic link item
                RtlInitUnicodeString(&SymEntry->SymbolicLink, SymbolicLinkName.Buffer);
                // store item
                InsertTailList(&SubDeviceDescriptor->SymbolicLinkList, &SymEntry->Entry);
            }
            else
            {
                // allocating failed
                RtlFreeUnicodeString(&SymbolicLinkName);
            }
        }
    }

    // release SubDevice reference
    SubDevice->Release();

    return STATUS_SUCCESS;
}
예제 #2
0
static
VOID
Test_IoRegisterDeviceInterface(VOID)
{
    GUID Guid = {0x378de44c, 0x56ef, 0x11d1, {0xbc, 0x8c, 0x00, 0xa0, 0xc9, 0x14, 0x05, 0xdd}};
    DEVICE_OBJECT DeviceObject;
    EXTENDED_DEVOBJ_EXTENSION DeviceObjectExtension;
    DEVICE_NODE DeviceNode;
    UNICODE_STRING SymbolicLinkName;
    NTSTATUS Status;

    RtlInitUnicodeString(&SymbolicLinkName, L"");

    // Prepare our surrogate of a Device Object
    DeviceObject.DeviceObjectExtension = (PDEVOBJ_EXTENSION)&DeviceObjectExtension;

    // 1. DeviceNode = NULL
    DeviceObjectExtension.DeviceNode = NULL;
    Status = IoRegisterDeviceInterface(&DeviceObject, &Guid, NULL,
        &SymbolicLinkName);

    ok(Status == STATUS_INVALID_DEVICE_REQUEST,
        "IoRegisterDeviceInterface returned 0x%08lX\n", Status);

    // 2. DeviceNode->InstancePath is of a null length
    DeviceObjectExtension.DeviceNode = &DeviceNode;
    DeviceNode.InstancePath.Length = 0;
    Status = IoRegisterDeviceInterface(&DeviceObject, &Guid, NULL,
        &SymbolicLinkName);

    ok(Status == STATUS_INVALID_DEVICE_REQUEST,
        "IoRegisterDeviceInterface returned 0x%08lX\n", Status);

    DeviceInterfaceTest_Func();
}
예제 #3
0
NTSTATUS
SysAudioRegisterDeviceInterfaces(
    IN PDEVICE_OBJECT DeviceObject)
{
    NTSTATUS Status;
    UNICODE_STRING SymbolicLink;

    Status = IoRegisterDeviceInterface(DeviceObject, &KSCATEGORY_PREFERRED_MIDIOUT_DEVICE, NULL, &SymbolicLink);
    if (NT_SUCCESS(Status))
    {
        IoSetDeviceInterfaceState(&SymbolicLink, TRUE);
        RtlFreeUnicodeString(&SymbolicLink);
    }
    else
    {
        DPRINT("Failed to register KSCATEGORY_PREFERRED_MIDIOUT_DEVICE interface Status %x\n", Status);
        return Status;
    }

    Status = IoRegisterDeviceInterface(DeviceObject, &KSCATEGORY_PREFERRED_WAVEIN_DEVICE, NULL, &SymbolicLink);
    if (NT_SUCCESS(Status))
    {
        IoSetDeviceInterfaceState(&SymbolicLink, TRUE);
        RtlFreeUnicodeString(&SymbolicLink);
    }
    else
    {
        DPRINT("Failed to register KSCATEGORY_PREFERRED_WAVEIN_DEVICE interface Status %x\n", Status);
        return Status;
    }

    Status = IoRegisterDeviceInterface(DeviceObject, &KSCATEGORY_PREFERRED_WAVEOUT_DEVICE, NULL, &SymbolicLink);
    if (NT_SUCCESS(Status))
    {
        IoSetDeviceInterfaceState(&SymbolicLink, TRUE);
        RtlFreeUnicodeString(&SymbolicLink);
    }
    else
    {
        DPRINT("Failed to register KSCATEGORY_PREFERRED_WAVEOUT_DEVICE interface Status %x\n", Status);
    }

    Status = IoRegisterDeviceInterface(DeviceObject, &KSCATEGORY_SYSAUDIO, NULL, &SymbolicLink);
    if (NT_SUCCESS(Status))
    {
        IoSetDeviceInterfaceState(&SymbolicLink, TRUE);
        RtlFreeUnicodeString(&SymbolicLink);
    }
    else
    {
        DPRINT("Failed to register KSCATEGORY_SYSAUDIO interface Status %x\n", Status);
    }

    return Status;
}
예제 #4
0
NTSTATUS
WdmAudRegisterDeviceInterface(
    IN PDEVICE_OBJECT PhysicalDeviceObject,
    IN PWDMAUD_DEVICE_EXTENSION DeviceExtension)
{
    NTSTATUS Status;
    UNICODE_STRING SymlinkName = RTL_CONSTANT_STRING(L"\\DosDevices\\wdmaud");
    UNICODE_STRING DeviceName = RTL_CONSTANT_STRING(L"\\Device\\wdmaud");
    UNICODE_STRING SymbolicLinkName;

    Status = IoRegisterDeviceInterface(PhysicalDeviceObject, &KSCATEGORY_WDMAUD, NULL, &SymbolicLinkName);
    if (NT_SUCCESS(Status))
    {
        IoSetDeviceInterfaceState(&SymbolicLinkName, TRUE);
        RtlFreeUnicodeString(&SymbolicLinkName);
        DeviceExtension->DeviceInterfaceSupport = TRUE;
        return Status;
    }

    /* failed to register device interface
     * create a symbolic link instead 
     */
    DeviceExtension->DeviceInterfaceSupport = FALSE;

    Status = IoCreateSymbolicLink(&SymlinkName, &DeviceName);
    if (!NT_SUCCESS(Status))
    {
        IoDeleteDevice(PhysicalDeviceObject); //FIXME
        DPRINT("Failed to create wdmaud symlink!\n");
        return Status;
    }

    return Status;
}
예제 #5
0
NTSTATUS hsac_pcieAddDevice(IN PDRIVER_OBJECT  DriverObject, IN PDEVICE_OBJECT  PhysicalDeviceObject)
{
	PDEVICE_OBJECT DeviceObject = NULL;
	Phsac_pcie_DEVICE_EXTENSION pExtension = NULL;
	NTSTATUS status;
	
	status = IoCreateDevice(DriverObject,
						    sizeof(hsac_pcie_DEVICE_EXTENSION),
							NULL,
							FILE_DEVICE_UNKNOWN,
							0,
							0,
							&DeviceObject);

	if (!NT_SUCCESS(status))
		return status;

	pExtension = (Phsac_pcie_DEVICE_EXTENSION)DeviceObject->DeviceExtension;

	pExtension->DeviceObject = DeviceObject;
	pExtension->PhysicalDeviceObject = PhysicalDeviceObject;
	pExtension->TargetDeviceObject = IoAttachDeviceToDeviceStack(DeviceObject, PhysicalDeviceObject);

	status = IoRegisterDeviceInterface(PhysicalDeviceObject, &GUID_hsac_pcieInterface, NULL, &pExtension->DeviceInterface);
	ASSERT(NT_SUCCESS(status));

	DeviceObject->Flags &= ~DO_DEVICE_INITIALIZING;
	return STATUS_SUCCESS;
}
예제 #6
0
파일: init.c 프로젝트: MelcherSt/dokany
NTSTATUS
DokanRegisterMountedDeviceInterface(__in PDEVICE_OBJECT DeviceObject,
                                    __in PDokanDCB Dcb) {
  NTSTATUS status;
  UNICODE_STRING interfaceName;
  DDbgPrint("=> DokanRegisterMountedDeviceInterface\n");

  status = IoRegisterDeviceInterface(
      DeviceObject, &MOUNTDEV_MOUNTED_DEVICE_GUID, NULL, &interfaceName);

  if (NT_SUCCESS(status)) {
    DDbgPrint("  InterfaceName:%wZ\n", &interfaceName);

    Dcb->MountedDeviceInterfaceName = interfaceName;
    status = IoSetDeviceInterfaceState(&interfaceName, TRUE);

    if (!NT_SUCCESS(status)) {
      DDbgPrint("  IoSetDeviceInterfaceState failed: 0x%x\n", status);
      RtlFreeUnicodeString(&interfaceName);
    }
  } else {
    DDbgPrint("  IoRegisterDeviceInterface failed: 0x%x\n", status);
  }

  if (!NT_SUCCESS(status)) {
    RtlInitUnicodeString(&(Dcb->MountedDeviceInterfaceName), NULL);
  }
  DDbgPrint("<= DokanRegisterMountedDeviceInterface\n");
  return status;
}
예제 #7
0
파일: pnp.c 프로젝트: hoangduit/reactos
NTSTATUS
NTAPI
DiskInitPdo(
    IN PDEVICE_OBJECT Pdo
    )

/*++

Routine Description:

    This routine will create the well known names for a PDO and register
    it's device interfaces.

--*/

{
    PCOMMON_DEVICE_EXTENSION pdoExtension = Pdo->DeviceExtension;
    PDISK_DATA diskData = pdoExtension->DriverData;

    UNICODE_STRING interfaceName;

    NTSTATUS status;

    PAGED_CODE();

    DiskCreateSymbolicLinks(Pdo);

    //
    // Register interfaces for this device
    //

    RtlInitUnicodeString(&interfaceName, NULL);

    status = IoRegisterDeviceInterface(Pdo,
                                       (LPGUID) &PartitionClassGuid,
                                       NULL,
                                       &interfaceName);

    if(NT_SUCCESS(status)) {

        diskData->PartitionInterfaceString = interfaceName;
        status = IoSetDeviceInterfaceState(&interfaceName, TRUE);

    } else {
        interfaceName.Buffer = NULL;
    }

    if(!NT_SUCCESS(status)) {
        DebugPrint((1, "DiskInitPdo: Unable to register partition DCA for "
                    "pdo %p [%lx]\n", Pdo, status));

        RtlFreeUnicodeString(&interfaceName);
        RtlInitUnicodeString(&(diskData->PartitionInterfaceString), NULL);
    }

    return STATUS_SUCCESS;
}
예제 #8
0
NTSTATUS DriverExampleAddDevice(IN PDRIVER_OBJECT  DriverObject, IN PDEVICE_OBJECT  PhysicalDeviceObject)
{
	DbgPrint("Enter AddDevice\n");
	PDEVICE_OBJECT DeviceObject = NULL;
	PDriverExample_DEVICE_EXTENSION pExtension = NULL;
	NTSTATUS status;
	UNICODE_STRING uszDriverString;
	RtlInitUnicodeString(&uszDriverString, L"\\Device\\DriverExample");// Задача функции RtlInitUnicodeString измерить unicode-строку и заполнить 
	
	
	status = IoCreateDevice(DriverObject,
						    sizeof(DriverExample_DEVICE_EXTENSION),
							&uszDriverString,
							FILE_DEVICE_UNKNOWN,
							0,
							0,
							&DeviceObject);
	
	UNICODE_STRING uszDeviceString;

	RtlInitUnicodeString(&uszDeviceString, L"\\DosDevices\\DriverExample");
    //
	// Create symbolic link to the user-visible name

    status = IoCreateSymbolicLink(&uszDeviceString, &uszDriverString);

	if (!NT_SUCCESS(status))
	{
		DbgPrint("Not success status \n");
		return status;
	}
	g_pDeviceObject = DeviceObject; //Save Device object

	pExtension = (PDriverExample_DEVICE_EXTENSION)DeviceObject->DeviceExtension;

	pExtension->DeviceObject = DeviceObject;
	pExtension->PhysicalDeviceObject = PhysicalDeviceObject;
	pExtension->TargetDeviceObject = IoAttachDeviceToDeviceStack(DeviceObject, PhysicalDeviceObject);

	status = IoRegisterDeviceInterface(PhysicalDeviceObject, &GUID_DriverExampleInterface, NULL, &pExtension->DeviceInterface);
	ASSERT(NT_SUCCESS(status));

	UNICODE_STRING uszProcessEventString;
	HANDLE hProcessHandle;

	RtlInitUnicodeString(&uszProcessEventString,L"\\BaseNamedObjects\\ProcessEvent");
    pExtension->ProcessEvent = IoCreateNotificationEvent(&uszProcessEventString,	&hProcessHandle);
	//
    // Clear it out
	//
    KeClearEvent(pExtension->ProcessEvent);

	DeviceObject->Flags &= ~DO_DEVICE_INITIALIZING;
	DbgPrint("Exit AddDevice \n");
	return STATUS_SUCCESS;
}
예제 #9
0
파일: device.c 프로젝트: iXit/wine
NTSTATUS HID_LinkDevice(DEVICE_OBJECT *device)
{
    SP_DEVINFO_DATA Data;
    UNICODE_STRING nameW;
    NTSTATUS status;
    HDEVINFO devinfo;
    GUID hidGuid;
    BASE_DEVICE_EXTENSION *ext;

    HidD_GetHidGuid(&hidGuid);
    ext = device->DeviceExtension;

    RtlInitUnicodeString( &nameW, ext->device_name);

    devinfo = SetupDiGetClassDevsW(&GUID_DEVCLASS_HIDCLASS, NULL, NULL, DIGCF_DEVICEINTERFACE);
    if (!devinfo)
    {
        FIXME( "failed to get ClassDevs %x\n", GetLastError());
        return STATUS_UNSUCCESSFUL;
    }
    Data.cbSize = sizeof(Data);
    if (!SetupDiCreateDeviceInfoW(devinfo, ext->instance_id, &GUID_DEVCLASS_HIDCLASS, NULL, NULL, DICD_INHERIT_CLASSDRVS, &Data))
    {
        if (GetLastError() == ERROR_DEVINST_ALREADY_EXISTS)
        {
            SetupDiDestroyDeviceInfoList(devinfo);
            return STATUS_SUCCESS;
        }
        FIXME( "failed to Create Device Info %x\n", GetLastError());
        goto error;
    }
    if (!SetupDiRegisterDeviceInfo( devinfo, &Data, 0, NULL, NULL, NULL ))
    {
        FIXME( "failed to Register Device Info %x\n", GetLastError());
        goto error;
    }
    SetupDiDestroyDeviceInfoList(devinfo);

    status = IoRegisterDeviceInterface(device, &hidGuid, NULL, &ext->link_name);
    if (status != STATUS_SUCCESS)
    {
        FIXME( "failed to register device interface %x\n", status );
        return status;
    }

    return STATUS_SUCCESS;

error:
    SetupDiDestroyDeviceInfoList(devinfo);
    return STATUS_UNSUCCESSFUL;
}
예제 #10
0
NTSTATUS HelloWDMAddDevice(IN PDRIVER_OBJECT DriverObject,
                           IN PDEVICE_OBJECT PhysicalDeviceObject)
{ 
	PAGED_CODE();
	KdPrint(("Enter HelloWDMAddDevice\n"));

	NTSTATUS status;
	PDEVICE_OBJECT fdo;
	status = IoCreateDevice(
		DriverObject,
		sizeof(DEVICE_EXTENSION),
		NULL,//没有指定设备名
		FILE_DEVICE_UNKNOWN,
		0,
		FALSE,
		&fdo);
	if( !NT_SUCCESS(status))
		return status;
	PDEVICE_EXTENSION pdx = (PDEVICE_EXTENSION)fdo->DeviceExtension;
	pdx->fdo = fdo;
	pdx->NextStackDevice = IoAttachDeviceToDeviceStack(fdo, PhysicalDeviceObject);

	//创建设备接口
	status = IoRegisterDeviceInterface(PhysicalDeviceObject, &MY_WDM_DEVICE, NULL, &pdx->interfaceName);
	if( !NT_SUCCESS(status))
	{
		IoDeleteDevice(fdo);
		return status;
	}
	KdPrint(("%wZ\n",&pdx->interfaceName));
	IoSetDeviceInterfaceState(&pdx->interfaceName, TRUE);

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

	fdo->Flags |= DO_BUFFERED_IO | DO_POWER_PAGABLE;
	fdo->Flags &= ~DO_DEVICE_INITIALIZING;

	KdPrint(("Leave HelloWDMAddDevice\n"));
	return STATUS_SUCCESS;
}
예제 #11
0
파일: Pnp.cpp 프로젝트: Kallameet/TPG2
NTSTATUS PassThruAddDevice(	IN PDRIVER_OBJECT DriverObject,
						IN PDEVICE_OBJECT pdo)
{
	DebugPrint("AddDevice");
	NTSTATUS status;
	PDEVICE_OBJECT fdo;

	// Create our Functional Device Object in fdo
	status = IoCreateDevice (DriverObject,
		sizeof(PASSTHRU_DEVICE_EXTENSION),
		NULL,	// No Name
		FILE_DEVICE_UNKNOWN,
		0,
		FALSE,	// Not exclusive
		&fdo);
	if( !NT_SUCCESS(status))
		return status;

	// Remember fdo in our device extension
	PPASSTHRU_DEVICE_EXTENSION dx = (PPASSTHRU_DEVICE_EXTENSION)fdo->DeviceExtension;
	dx->fdo = fdo;
	DebugPrint("FDO is %x",fdo);

	// Register and enable our device interface
	status = IoRegisterDeviceInterface(pdo, &WDM1_GUID, NULL, &dx->ifSymLinkName);
	if( !NT_SUCCESS(status))
	{
		IoDeleteDevice(fdo);
		return status;
	}
	IoSetDeviceInterfaceState(&dx->ifSymLinkName, TRUE);
	DebugPrint("Symbolic Link Name is %T",&dx->ifSymLinkName);

	// Attach to the driver stack below us
	dx->NextStackDevice = IoAttachDeviceToDeviceStack(fdo,pdo);

	// Set fdo flags appropriately
	fdo->Flags |= DO_BUFFERED_IO|DO_POWER_PAGABLE;
	fdo->Flags &= ~DO_DEVICE_INITIALIZING;

	return STATUS_SUCCESS;
}
예제 #12
0
NTSTATUS SarKsDeviceAdd(IN PKSDEVICE device)
{
    NTSTATUS status;
    UNICODE_STRING referenceString;
    SarDriverExtension *extension =
        (SarDriverExtension *)IoGetDriverObjectExtension(
            device->FunctionalDeviceObject->DriverObject, DriverEntry);

    RtlUnicodeStringInit(&referenceString, SAR_CONTROL_REFERENCE_STRING + 1);
    status = IoRegisterDeviceInterface(device->PhysicalDeviceObject,
        &GUID_DEVINTERFACE_SYNCHRONOUSAUDIOROUTER, &referenceString,
        &extension->sarInterfaceName);

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

    SAR_LOG("KSDevice was created for %p, dev interface: %wZ",
        device, &extension->sarInterfaceName);
    return status;
}
예제 #13
0
파일: filter.c 프로젝트: hoangduit/reactos
VOID
RegisterDeviceInterfaces(
    IN PSTREAM_DEVICE_EXTENSION DeviceExtension)
{
    ULONG Index;
    PHW_STREAM_INFORMATION StreamInformation;
    UNICODE_STRING SymbolicLink;
    NTSTATUS Status;

    /* Sanity check */
    ASSERT(DeviceExtension->StreamDescriptor);
    ASSERT(DeviceExtension->StreamDescriptorSize);

    /* Loop all stream descriptors and register device interfaces */
    StreamInformation = (PHW_STREAM_INFORMATION)&DeviceExtension->StreamDescriptor->StreamInfo;

    for(Index = 0; DeviceExtension->StreamDescriptor->StreamHeader.NumberOfStreams; Index++)
    {
        if (StreamInformation->Category)
        {
            /* Register device interface */
            Status = IoRegisterDeviceInterface(DeviceExtension->PhysicalDeviceObject,
                                               StreamInformation->Category,
                                               NULL, /* see bug 4566 */
                                               &SymbolicLink);

            if (NT_SUCCESS(Status))
            {
                /* Activate device interface */
                IoSetDeviceInterfaceState(&SymbolicLink, TRUE);
                /* Release Symbolic Link */
                RtlFreeUnicodeString(&SymbolicLink);
            }
        }
        StreamInformation = (PHW_STREAM_INFORMATION) (ULONG_PTR)StreamInformation + DeviceExtension->StreamDescriptor->StreamHeader.SizeOfHwStreamInformation;
    }

}
예제 #14
0
// AddDevice, called when an instance of our supported hardware is found
// Returning anything other than NT_SUCCESS here causes the device to fail
// to initialise
NTSTATUS NTAPI FreeBT_AddDevice(IN PDRIVER_OBJECT DriverObject, IN PDEVICE_OBJECT PhysicalDeviceObject)
{
    NTSTATUS			ntStatus;
    PDEVICE_OBJECT		deviceObject;
    PDEVICE_EXTENSION	deviceExtension;
    POWER_STATE			state;
    KIRQL				oldIrql;
	UNICODE_STRING		uniDeviceName;
	WCHAR				wszDeviceName[255]={0};
	UNICODE_STRING		uniDosDeviceName;
	LONG				instanceNumber=0;

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

    deviceObject = NULL;

	swprintf(wszDeviceName, L"\\Device\\FbtUsb%02d", instanceNumber);
	RtlInitUnicodeString(&uniDeviceName, wszDeviceName);
	ntStatus=STATUS_OBJECT_NAME_COLLISION;
	while (instanceNumber<99 && !NT_SUCCESS(ntStatus))
	{
		swprintf(wszDeviceName, L"\\Device\\FbtUsb%02d", instanceNumber);
		uniDeviceName.Length = wcslen(wszDeviceName) * sizeof(WCHAR);
		FreeBT_DbgPrint(1, ("FBTUSB: Attempting to create device %ws\n", wszDeviceName));
		ntStatus = IoCreateDevice(
						DriverObject,                   // our driver object
						sizeof(DEVICE_EXTENSION),       // extension size for us
						&uniDeviceName,					// name for this device
						FILE_DEVICE_UNKNOWN,
						0,								// device characteristics
						FALSE,                          // Not exclusive
						&deviceObject);                 // Our device object

		if (!NT_SUCCESS(ntStatus))
			instanceNumber++;

	}

    if (!NT_SUCCESS(ntStatus))
	{
        FreeBT_DbgPrint(1, ("FBTUSB: Failed to create device object\n"));
        return ntStatus;

    }

	FreeBT_DbgPrint(1, ("FBTUSB: Created device %ws\n", wszDeviceName));

    deviceExtension = (PDEVICE_EXTENSION) deviceObject->DeviceExtension;
    deviceExtension->FunctionalDeviceObject = deviceObject;
    deviceExtension->PhysicalDeviceObject = PhysicalDeviceObject;
    deviceObject->Flags |= DO_DIRECT_IO;

	swprintf(deviceExtension->wszDosDeviceName, L"\\DosDevices\\FbtUsb%02d", instanceNumber);
	RtlInitUnicodeString(&uniDosDeviceName, deviceExtension->wszDosDeviceName);
	ntStatus=IoCreateSymbolicLink(&uniDosDeviceName, &uniDeviceName);
	if (!NT_SUCCESS(ntStatus))
	{
		FreeBT_DbgPrint(1, ("FBTUSB: Failed to create symbolic link %ws to %ws, status=0x%08x\n", deviceExtension->wszDosDeviceName, wszDeviceName, ntStatus));
		IoDeleteDevice(deviceObject);
		return ntStatus;

	}

	FreeBT_DbgPrint(1, ("FBTUSB: Created symbolic link %ws\n", deviceExtension->wszDosDeviceName));

    KeInitializeSpinLock(&deviceExtension->DevStateLock);

    INITIALIZE_PNP_STATE(deviceExtension);

    deviceExtension->OpenHandleCount = 0;

    // Initialize the selective suspend variables
    KeInitializeSpinLock(&deviceExtension->IdleReqStateLock);
    deviceExtension->IdleReqPend = 0;
    deviceExtension->PendingIdleIrp = NULL;

    // Hold requests until the device is started
    deviceExtension->QueueState = HoldRequests;

    // Initialize the queue and the queue spin lock
    InitializeListHead(&deviceExtension->NewRequestsQueue);
    KeInitializeSpinLock(&deviceExtension->QueueLock);

    // Initialize the remove event to not-signaled.
    KeInitializeEvent(&deviceExtension->RemoveEvent, SynchronizationEvent, FALSE);

    // Initialize the stop event to signaled.
    // This event is signaled when the OutstandingIO becomes 1
    KeInitializeEvent(&deviceExtension->StopEvent, SynchronizationEvent, TRUE);

    // OutstandingIo count biased to 1.
    // Transition to 0 during remove device means IO is finished.
    // Transition to 1 means the device can be stopped
    deviceExtension->OutStandingIO = 1;
    KeInitializeSpinLock(&deviceExtension->IOCountLock);

#ifdef ENABLE_WMI 
    // Delegating to WMILIB
    ntStatus = FreeBT_WmiRegistration(deviceExtension);
    if (!NT_SUCCESS(ntStatus))
	{
        FreeBT_DbgPrint(1, ("FBTUSB: FreeBT_WmiRegistration failed with %X\n", ntStatus));
        IoDeleteDevice(deviceObject);
		IoDeleteSymbolicLink(&uniDosDeviceName);
        return ntStatus;

    }
#endif

    // Set the flags as underlying PDO
    if (PhysicalDeviceObject->Flags & DO_POWER_PAGABLE)
	{
        deviceObject->Flags |= DO_POWER_PAGABLE;

    }

    // Typically, the function driver for a device is its
    // power policy owner, although for some devices another
    // driver or system component may assume this role.
    // Set the initial power state of the device, if known, by calling
    // PoSetPowerState.
    deviceExtension->DevPower = PowerDeviceD0;
    deviceExtension->SysPower = PowerSystemWorking;

    state.DeviceState = PowerDeviceD0;
    PoSetPowerState(deviceObject, DevicePowerState, state);

    // attach our driver to device stack
    // The return value of IoAttachDeviceToDeviceStack is the top of the
    // attachment chain.  This is where all the IRPs should be routed.
    deviceExtension->TopOfStackDeviceObject = IoAttachDeviceToDeviceStack(deviceObject, PhysicalDeviceObject);
    if (NULL == deviceExtension->TopOfStackDeviceObject)
	{
#ifdef ENABLE_WMI
        FreeBT_WmiDeRegistration(deviceExtension);
#endif
        IoDeleteDevice(deviceObject);
		IoDeleteSymbolicLink(&uniDosDeviceName);
        return STATUS_NO_SUCH_DEVICE;

    }

    // Register device interfaces
    ntStatus = IoRegisterDeviceInterface(deviceExtension->PhysicalDeviceObject,
                                         &GUID_CLASS_FREEBT_USB,
                                         NULL,
                                         &deviceExtension->InterfaceName);
    if (!NT_SUCCESS(ntStatus))
	{
#ifdef ENABLE_WMI
        FreeBT_WmiDeRegistration(deviceExtension);
#endif
        IoDetachDevice(deviceExtension->TopOfStackDeviceObject);
        IoDeleteDevice(deviceObject);
		IoDeleteSymbolicLink(&uniDosDeviceName);
        return ntStatus;

    }

    if (IoIsWdmVersionAvailable(1, 0x20))
	{
        deviceExtension->WdmVersion = WinXpOrBetter;

    }

    else if (IoIsWdmVersionAvailable(1, 0x10))
	{
        deviceExtension->WdmVersion = Win2kOrBetter;

    }

    else if (IoIsWdmVersionAvailable(1, 0x5))
	{
        deviceExtension->WdmVersion = WinMeOrBetter;

    }

    else if (IoIsWdmVersionAvailable(1, 0x0))
	{
        deviceExtension->WdmVersion = Win98OrBetter;

    }

    deviceExtension->SSRegistryEnable = 0;
    deviceExtension->SSEnable = 0;

    // WinXP only: check the registry flag indicating whether
	// the device should selectively suspend when idle
    if (WinXpOrBetter == deviceExtension->WdmVersion)
	{
        FreeBT_GetRegistryDword(FREEBT_REGISTRY_PARAMETERS_PATH,
                                 L"BulkUsbEnable",
                                 (PULONG)(&deviceExtension->SSRegistryEnable));
        if (deviceExtension->SSRegistryEnable)
		{
            // initialize DPC
            KeInitializeDpc(&deviceExtension->DeferredProcCall, DpcRoutine, deviceObject);

            // initialize the timer.
            // the DPC and the timer in conjunction,
            // monitor the state of the device to
            // selectively suspend the device.
            KeInitializeTimerEx(&deviceExtension->Timer, NotificationTimer);

            // Initialize the NoDpcWorkItemPendingEvent to signaled state.
            // This event is cleared when a Dpc is fired and signaled
            // on completion of the work-item.
            KeInitializeEvent(&deviceExtension->NoDpcWorkItemPendingEvent, NotificationEvent, TRUE);

            // Initialize the NoIdleReqPendEvent to ensure that the idle request
            // is indeed complete before we unload the drivers.
            KeInitializeEvent(&deviceExtension->NoIdleReqPendEvent, NotificationEvent, TRUE);

        }

    }

    // Initialize the NoIdleReqPendEvent to ensure that the idle request
    // is indeed complete before we unload the drivers.
    KeInitializeEvent(&deviceExtension->DelayEvent, NotificationEvent, FALSE);

    // Clear the DO_DEVICE_INITIALIZING flag.
    // Note: Do not clear this flag until the driver has set the
    // device power state and the power DO flags.
    deviceObject->Flags &= ~DO_DEVICE_INITIALIZING;
    InterlockedIncrement(&instanceNumber);

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

    return ntStatus;

}
예제 #15
0
NTSTATUS NTAPI
AddDevice(PDRIVER_OBJECT DriverObject, PDEVICE_OBJECT Pdo)
{
    NTSTATUS Status = STATUS_UNSUCCESSFUL;
    PDEVICE_OBJECT Fdo;
    ULONG UsbDeviceNumber = 0;
    WCHAR CharDeviceName[64];
    WCHAR CharSymLinkName[64];
    UNICODE_STRING DeviceName;
    UNICODE_STRING SymLinkName;
    UNICODE_STRING InterfaceSymLinkName;
    ULONG BytesRead;
    PCI_COMMON_CONFIG PciConfig;

    PFDO_DEVICE_EXTENSION FdoDeviceExtension;

    DPRINT1("Ehci: AddDevice\n");

    /* Create the FDO with next available number */
    while (TRUE)
    {
        /* FIXME: Use safe string sprintf*/
        /* RtlStringCchPrintfW(CharDeviceName, 64, L"USBFDO-%d", UsbDeviceNumber); */
        swprintf(CharDeviceName, L"\\Device\\USBFDO-%d", UsbDeviceNumber);
        RtlInitUnicodeString(&DeviceName, CharDeviceName);
        DPRINT("DeviceName %wZ\n", &DeviceName);

        Status = IoCreateDevice(DriverObject,
                                sizeof(FDO_DEVICE_EXTENSION),
                                &DeviceName,
                                FILE_DEVICE_CONTROLLER,
                                0,
                                FALSE,
                                &Fdo);

        if (NT_SUCCESS(Status))
            break;

        if ((Status == STATUS_OBJECT_NAME_EXISTS) || (Status == STATUS_OBJECT_NAME_COLLISION))
        {
            /* Try the next name */
            UsbDeviceNumber++;
            continue;
        }

        /* Bail on any other error */
        if (!NT_SUCCESS(Status))
        {
            DPRINT1("UsbEhci: Failed to create %wZ, Status %x\n", &DeviceName, Status);
            return Status;
        }
    }

    swprintf(CharSymLinkName, L"\\Device\\HCD%d", UsbDeviceNumber);
    RtlInitUnicodeString(&SymLinkName, CharSymLinkName);
    Status = IoCreateSymbolicLink(&SymLinkName, &DeviceName);

    if (!NT_SUCCESS(Status))
    {
        DPRINT1("Warning: Unable to create symbolic link for ehci host controller!\n");
    }

    FdoDeviceExtension = (PFDO_DEVICE_EXTENSION) Fdo->DeviceExtension;
    RtlZeroMemory(FdoDeviceExtension, sizeof(PFDO_DEVICE_EXTENSION));

    KeInitializeTimerEx(&FdoDeviceExtension->UpdateTimer, SynchronizationTimer);

    FdoDeviceExtension->Common.IsFdo = TRUE;
    FdoDeviceExtension->DeviceObject = Fdo;

    FdoDeviceExtension->LowerDevice = IoAttachDeviceToDeviceStack(Fdo, Pdo);

    if (FdoDeviceExtension->LowerDevice == NULL)
    {
        DPRINT1("UsbEhci: Failed to attach to device stack!\n");
        IoDeleteSymbolicLink(&SymLinkName);
        IoDeleteDevice(Fdo);

        return STATUS_NO_SUCH_DEVICE;
    }

    Fdo->Flags |= DO_BUFFERED_IO;// | DO_POWER_PAGABLE;

    ASSERT(FdoDeviceExtension->LowerDevice == Pdo);

    /* Get the EHCI Device ID and Vendor ID */
    Status = GetBusInterface(FdoDeviceExtension->LowerDevice, &FdoDeviceExtension->BusInterface);

    if (!NT_SUCCESS(Status))
    {
        DPRINT1("GetBusInterface() failed with %x\n", Status);
        IoDetachDevice(FdoDeviceExtension->LowerDevice);
        IoDeleteSymbolicLink(&SymLinkName);
        IoDeleteDevice(Fdo);
        return Status;
    }

    BytesRead = (*FdoDeviceExtension->BusInterface.GetBusData)(
        FdoDeviceExtension->BusInterface.Context,
        PCI_WHICHSPACE_CONFIG,
        &PciConfig,
        0,
        PCI_COMMON_HDR_LENGTH);


    if (BytesRead != PCI_COMMON_HDR_LENGTH)
    {
        DPRINT1("GetBusData failed!\n");
        IoDetachDevice(FdoDeviceExtension->LowerDevice);
        IoDeleteSymbolicLink(&SymLinkName);
        IoDeleteDevice(Fdo);
        return STATUS_UNSUCCESSFUL;
    }

    if (PciConfig.Command & PCI_ENABLE_IO_SPACE)
        DPRINT("PCI_ENABLE_IO_SPACE\n");

    if (PciConfig.Command & PCI_ENABLE_MEMORY_SPACE)
        DPRINT("PCI_ENABLE_MEMORY_SPACE\n");

    if (PciConfig.Command & PCI_ENABLE_BUS_MASTER)
        DPRINT("PCI_ENABLE_BUS_MASTER\n");

    DPRINT("BaseAddress[0] %x\n", PciConfig.u.type0.BaseAddresses[0]);
    DPRINT1("Vendor %x\n", PciConfig.VendorID);
    DPRINT1("Device %x\n", PciConfig.DeviceID);

    FdoDeviceExtension->VendorId = PciConfig.VendorID;
    FdoDeviceExtension->DeviceId = PciConfig.DeviceID;

    FdoDeviceExtension->DeviceState = DEVICEINTIALIZED;

    Status = IoRegisterDeviceInterface(Pdo, &GUID_DEVINTERFACE_USB_HOST_CONTROLLER, NULL, &InterfaceSymLinkName);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("Unable to register device interface!\n");
        return Status;
    }
    else
    {
        Status = IoSetDeviceInterfaceState(&InterfaceSymLinkName, TRUE);
        DPRINT1("SetInterfaceState %x\n", Status);
        if (!NT_SUCCESS(Status))
            return Status;
    }
    Fdo->Flags &= ~DO_DEVICE_INITIALIZING;

    return STATUS_SUCCESS;
}
예제 #16
0
// add device
NTSTATUS AddDevice(PDRIVER_OBJECT pDriver,PDEVICE_OBJECT pPhysicalDeviceObject)
{
	NTSTATUS status;
	PDEVICE_OBJECT pDevice = NULL;
	PFdoExt pFdoExt = NULL;
	__try
	{
		UNICODE_STRING busFdoName;
		RtlInitUnicodeString(&busFdoName,BUS_FDO_NAME);
		status = IoCreateDevice(pDriver,sizeof(FdoExt),&busFdoName,FILE_DEVICE_BUS_EXTENDER,FILE_DEVICE_SECURE_OPEN,
								FALSE,&pDevice);

		if(!NT_SUCCESS(status))
			ExRaiseStatus(status);

		pFdoExt = static_cast<PFdoExt>(pDevice->DeviceExtension);
		RtlZeroMemory(pFdoExt,sizeof(FdoExt));

		status = IoRegisterDeviceInterface(pPhysicalDeviceObject,&GUID_TIAMO_BUS,NULL,&pFdoExt->m_symbolicName);
		if(!NT_SUCCESS(status))
			ExRaiseStatus(status);

		KeInitializeEvent(&pFdoExt->m_evRemove,SynchronizationEvent,FALSE);

		KeInitializeEvent(&pFdoExt->m_evStop,SynchronizationEvent,TRUE);

		ExInitializeFastMutex (&pFdoExt->m_mutexEnumPdo);

		pFdoExt->m_sysPowerState = PowerSystemWorking;
		pFdoExt->m_devPowerState = PowerDeviceD3;

		pFdoExt->m_bFdo = TRUE;
		pFdoExt->m_pPhysicalDevice = pPhysicalDeviceObject;

		pFdoExt->m_pLowerDevice = IoAttachDeviceToDeviceStack(pDevice,pPhysicalDeviceObject);

		pFdoExt->m_ulCurrentPnpState = -1;
		pFdoExt->m_ulPrevPnpState = -1;

		pFdoExt->m_ulOutstandingIO = 1;

		//pDevice->Flags |= DO_POWER_PAGABLE;

		POWER_STATE state;
		state.DeviceState = PowerDeviceD0;
		PoSetPowerState(pDevice,DevicePowerState,state);

		pDevice->Flags &= ~DO_DEVICE_INITIALIZING;

		devDebugPrint(DRIVER_NAME"*******AddDevice called,fdo createed.\n");
	}
	__except(EXCEPTION_EXECUTE_HANDLER)
	{
		if(pFdoExt && pFdoExt->m_pLowerDevice)
		{
			IoDetachDevice(pFdoExt->m_pLowerDevice);
			RtlFreeUnicodeString(&pFdoExt->m_symbolicName);
		}

		if(pDevice)
		{
			IoDeleteDevice(pDevice);
		}
	}

	return status;
}
예제 #17
0
NTSTATUS NTAPI
PdoDispatchPnp(
    IN PDEVICE_OBJECT DeviceObject,
    IN PIRP Irp)
{
    ULONG MinorFunction;
    PIO_STACK_LOCATION Stack;
    ULONG_PTR Information = Irp->IoStatus.Information;
    NTSTATUS Status = Irp->IoStatus.Status;
    PDEVICE_CAPABILITIES DeviceCapabilities;
    ULONG i;

    Stack = IoGetCurrentIrpStackLocation(Irp);
    MinorFunction = Stack->MinorFunction;

    switch (MinorFunction)
    {
    case IRP_MN_QUERY_REMOVE_DEVICE:
    case IRP_MN_REMOVE_DEVICE:
    case IRP_MN_CANCEL_REMOVE_DEVICE:
    case IRP_MN_STOP_DEVICE:
    case IRP_MN_QUERY_STOP_DEVICE:
    case IRP_MN_CANCEL_STOP_DEVICE:
    case IRP_MN_QUERY_DEVICE_TEXT:
    case IRP_MN_SURPRISE_REMOVAL:
    case IRP_MN_QUERY_RESOURCES:
    case IRP_MN_QUERY_RESOURCE_REQUIREMENTS:
    case IRP_MN_FILTER_RESOURCE_REQUIREMENTS:
    {
        Status = STATUS_SUCCESS;
        break;
    }

    case IRP_MN_START_DEVICE:
    {
        PUSB_DEVICE RootHubDevice;
        PPDO_DEVICE_EXTENSION PdoDeviceExtension;
        PFDO_DEVICE_EXTENSION FdoDeviceExtension;
        UNICODE_STRING InterfaceSymLinkName;

        DPRINT1("Ehci: PDO StartDevice\n");
        PdoDeviceExtension = (PPDO_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
        FdoDeviceExtension = (PFDO_DEVICE_EXTENSION)PdoDeviceExtension->ControllerFdo->DeviceExtension;

        /* Create the root hub */
        RootHubDevice = InternalCreateUsbDevice(1, 0, NULL, TRUE);

        RtlCopyMemory(&RootHubDevice->DeviceDescriptor,
                      ROOTHUB2_DEVICE_DESCRIPTOR,
                      sizeof(ROOTHUB2_DEVICE_DESCRIPTOR));

        RootHubDevice->DeviceDescriptor.idVendor = FdoDeviceExtension->VendorId;
        RootHubDevice->DeviceDescriptor.idProduct = FdoDeviceExtension->DeviceId;

        /* Here config, interfaces and descriptors are stored. This was duplicated from XEN PV Usb Drivers implementation.
           Not sure that it is really needed as the information can be queueried from the device. */

        RootHubDevice->Configs = ExAllocatePoolWithTag(NonPagedPool,
                                 sizeof(PVOID) * RootHubDevice->DeviceDescriptor.bNumConfigurations,
                                 USB_POOL_TAG);

        RootHubDevice->Configs[0] = ExAllocatePoolWithTag(NonPagedPool,
                                    sizeof(USB_CONFIGURATION) + sizeof(PVOID) * ROOTHUB2_CONFIGURATION_DESCRIPTOR[4],
                                    USB_POOL_TAG);

        RootHubDevice->Configs[0]->Interfaces[0] = ExAllocatePoolWithTag(NonPagedPool,
                sizeof(USB_INTERFACE) + sizeof(PVOID) * ROOTHUB2_INTERFACE_DESCRIPTOR[4],
                USB_POOL_TAG);

        RootHubDevice->Configs[0]->Interfaces[0]->EndPoints[0] = ExAllocatePoolWithTag(NonPagedPool,
                sizeof(USB_ENDPOINT),
                USB_POOL_TAG);

        RootHubDevice->ActiveConfig = RootHubDevice->Configs[0];
        RootHubDevice->ActiveInterface = RootHubDevice->ActiveConfig->Interfaces[0];

        RtlCopyMemory(&RootHubDevice->ActiveConfig->ConfigurationDescriptor,
                      ROOTHUB2_CONFIGURATION_DESCRIPTOR,
                      sizeof(ROOTHUB2_CONFIGURATION_DESCRIPTOR));

        RtlCopyMemory(&RootHubDevice->ActiveConfig->Interfaces[0]->InterfaceDescriptor,
                      ROOTHUB2_INTERFACE_DESCRIPTOR,
                      sizeof(ROOTHUB2_INTERFACE_DESCRIPTOR));

        RtlCopyMemory(&RootHubDevice->ActiveConfig->Interfaces[0]->EndPoints[0]->EndPointDescriptor,
                      ROOTHUB2_ENDPOINT_DESCRIPTOR,
                      sizeof(ROOTHUB2_ENDPOINT_DESCRIPTOR));
        RootHubDevice->DeviceSpeed = UsbHighSpeed;
        RootHubDevice->DeviceType = Usb20Device;

        PdoDeviceExtension->UsbDevices[0] = RootHubDevice;

        Status = IoRegisterDeviceInterface(DeviceObject, &GUID_DEVINTERFACE_USB_HUB, NULL, &InterfaceSymLinkName);
        if (!NT_SUCCESS(Status))
        {
            DPRINT1("Failed to register interface\n");
            return Status;
        }
        else
        {
            Status = IoSetDeviceInterfaceState(&InterfaceSymLinkName, TRUE);
            if (!NT_SUCCESS(Status))
                return Status;
        }

        Status = STATUS_SUCCESS;
        break;
    }
    case IRP_MN_QUERY_DEVICE_RELATIONS:
    {
        DPRINT1("Ehci: PDO QueryDeviceRelations\n");
        switch (Stack->Parameters.QueryDeviceRelations.Type)
        {
        case TargetDeviceRelation:
        {
            PDEVICE_RELATIONS DeviceRelations = NULL;
            Status = PdoQueryDeviceRelations(DeviceObject, &DeviceRelations);
            Information = (ULONG_PTR)DeviceRelations;
            break;
        }
        case BusRelations:
        {
            PPDO_DEVICE_EXTENSION PdoDeviceExtension;
            PdoDeviceExtension = (PPDO_DEVICE_EXTENSION)DeviceObject->DeviceExtension;

            DPRINT("BusRelations!!!!!\n");

            /* The hub driver has created the new device object and reported to pnp, as a result the pnp manager
               has sent this IRP and type, so leave the next SCE request pending until a new device arrives.
               Is there a better way to do this? */
            ExAcquireFastMutex(&PdoDeviceExtension->ListLock);
            PdoDeviceExtension->HaltQueue = TRUE;
            ExReleaseFastMutex(&PdoDeviceExtension->ListLock);
        }
        case RemovalRelations:
        case EjectionRelations:
        {
            /* Ignore the request */
            Information = Irp->IoStatus.Information;
            Status = Irp->IoStatus.Status;
            break;

        }
        default:
        {
            DPRINT1("IRP_MJ_PNP / IRP_MN_QUERY_DEVICE_RELATIONS / Unhandled type 0x%lx\n",
                    Stack->Parameters.QueryDeviceRelations.Type);
            Status = STATUS_NOT_SUPPORTED;
            break;
        }
        }
        break;
    }
    case IRP_MN_QUERY_CAPABILITIES:
    {
        DPRINT("Ehci: PDO Query Capabilities\n");

        DeviceCapabilities = (PDEVICE_CAPABILITIES)Stack->Parameters.DeviceCapabilities.Capabilities;

        DeviceCapabilities->LockSupported = FALSE;
        DeviceCapabilities->EjectSupported = FALSE;
        DeviceCapabilities->Removable = FALSE;
        DeviceCapabilities->DockDevice = FALSE;
        DeviceCapabilities->UniqueID = FALSE;
        DeviceCapabilities->SilentInstall = FALSE;
        DeviceCapabilities->RawDeviceOK = FALSE;
        DeviceCapabilities->SurpriseRemovalOK = FALSE;
        DeviceCapabilities->Address = 0;
        DeviceCapabilities->UINumber = 0;
        DeviceCapabilities->DeviceD2 = 1;

        /* FIXME: Verify these settings are correct */
        DeviceCapabilities->HardwareDisabled = FALSE;
        //DeviceCapabilities->NoDisplayInUI = FALSE;
        DeviceCapabilities->DeviceState[0] = PowerDeviceD0;
        for (i = 0; i < PowerSystemMaximum; i++)
            DeviceCapabilities->DeviceState[i] = PowerDeviceD3;
        DeviceCapabilities->DeviceWake = 0;
        DeviceCapabilities->D1Latency = 0;
        DeviceCapabilities->D2Latency = 0;
        DeviceCapabilities->D3Latency = 0;
        Information = 0;
        Status = STATUS_SUCCESS;
        break;
    }
    /*case IRP_MN_QUERY_DEVICE_TEXT:
    {
        Status = STATUS_NOT_SUPPORTED;
        break;
    }*/

    case IRP_MN_QUERY_ID:
    {
        DPRINT("Ehci: PDO Query ID\n");
        Status = PdoQueryId(DeviceObject, Irp, &Information);
        break;
    }
    case IRP_MN_QUERY_INTERFACE:
    {
        UNICODE_STRING GuidString;
        PUSB_BUS_INTERFACE_HUB_V5 InterfaceHub;
        PUSB_BUS_INTERFACE_USBDI_V2 InterfaceDI;
        PPDO_DEVICE_EXTENSION PdoDeviceExtension;
        PFDO_DEVICE_EXTENSION FdoDeviceExtension;

        DPRINT("Ehci: PDO Query Interface\n");

        PdoDeviceExtension = (PPDO_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
        FdoDeviceExtension = (PFDO_DEVICE_EXTENSION)PdoDeviceExtension->ControllerFdo->DeviceExtension;

        Status = RtlStringFromGUID(Stack->Parameters.QueryInterface.InterfaceType, &GuidString);
        if (!NT_SUCCESS(Status))
        {
            DPRINT1("Failed to create string from GUID!\n");
        }

        /* Assume success */
        Status = STATUS_SUCCESS;
        Information = 0;

        if (IsEqualGUIDAligned(Stack->Parameters.QueryInterface.InterfaceType, &USB_BUS_INTERFACE_HUB_GUID))
        {
            InterfaceHub = (PUSB_BUS_INTERFACE_HUB_V5)Stack->Parameters.QueryInterface.Interface;
            InterfaceHub->Version = Stack->Parameters.QueryInterface.Version;
            if (Stack->Parameters.QueryInterface.Version >= 0)
            {
                InterfaceHub->Size = Stack->Parameters.QueryInterface.Size;
                InterfaceHub->BusContext = PdoDeviceExtension->DeviceObject;
                InterfaceHub->InterfaceReference = (PINTERFACE_REFERENCE)InterfaceReference;
                InterfaceHub->InterfaceDereference = (PINTERFACE_DEREFERENCE)InterfaceDereference;
            }
            if (Stack->Parameters.QueryInterface.Version >= 1)
            {
                InterfaceHub->CreateUsbDevice = CreateUsbDevice;
                InterfaceHub->InitializeUsbDevice = InitializeUsbDevice;
                InterfaceHub->GetUsbDescriptors = GetUsbDescriptors;
                InterfaceHub->RemoveUsbDevice = RemoveUsbDevice;
                InterfaceHub->RestoreUsbDevice = RestoreUsbDevice;
                InterfaceHub->GetPortHackFlags = GetPortHackFlags;
                InterfaceHub->QueryDeviceInformation = QueryDeviceInformation;
            }
            if (Stack->Parameters.QueryInterface.Version >= 2)
            {
                InterfaceHub->GetControllerInformation = GetControllerInformation;
                InterfaceHub->ControllerSelectiveSuspend = ControllerSelectiveSuspend;
                InterfaceHub->GetExtendedHubInformation = GetExtendedHubInformation;
                InterfaceHub->GetRootHubSymbolicName = GetRootHubSymbolicName;
                InterfaceHub->GetDeviceBusContext = GetDeviceBusContext;
                InterfaceHub->Initialize20Hub = Initialize20Hub;

            }
            if (Stack->Parameters.QueryInterface.Version >= 3)
            {
                InterfaceHub->RootHubInitNotification = RootHubInitNotification;
            }
            if (Stack->Parameters.QueryInterface.Version >= 4)
            {
                InterfaceHub->FlushTransfers = FlushTransfers;
            }
            if (Stack->Parameters.QueryInterface.Version >= 5)
            {
                InterfaceHub->SetDeviceHandleData = SetDeviceHandleData;
            }
            if (Stack->Parameters.QueryInterface.Version >= 6)
            {
                DPRINT1("USB_BUS_INTERFACE_HUB_GUID version not supported!\n");
            }
            break;
        }

        if (IsEqualGUIDAligned(Stack->Parameters.QueryInterface.InterfaceType, &USB_BUS_INTERFACE_USBDI_GUID))
        {
            InterfaceDI = (PUSB_BUS_INTERFACE_USBDI_V2) Stack->Parameters.QueryInterface.Interface;
            InterfaceDI->Version = Stack->Parameters.QueryInterface.Version;
            if (Stack->Parameters.QueryInterface.Version >= 0)
            {
                //InterfaceDI->Size = sizeof(USB_BUS_INTERFACE_USBDI_V2);
                InterfaceDI->Size = Stack->Parameters.QueryInterface.Size;
                InterfaceDI->BusContext = PdoDeviceExtension->DeviceObject;
                InterfaceDI->InterfaceReference = (PINTERFACE_REFERENCE)InterfaceReference;
                InterfaceDI->InterfaceDereference = (PINTERFACE_DEREFERENCE)InterfaceDereference;
                InterfaceDI->GetUSBDIVersion = GetUSBDIVersion;
                InterfaceDI->QueryBusTime = QueryBusTime;
                InterfaceDI->SubmitIsoOutUrb = SubmitIsoOutUrb;
                InterfaceDI->QueryBusInformation = QueryBusInformation;
            }
            if (Stack->Parameters.QueryInterface.Version >= 1)
            {
                InterfaceDI->IsDeviceHighSpeed = IsDeviceHighSpeed;
            }
            if (Stack->Parameters.QueryInterface.Version >= 2)
            {
                InterfaceDI->EnumLogEntry = EnumLogEntry;
            }

            if (Stack->Parameters.QueryInterface.Version >= 3)
            {
                DPRINT1("SB_BUS_INTERFACE_USBDI_GUID version not supported!\n");
            }
            break;
        }

        DPRINT1("GUID Not Supported\n");
        Status = Irp->IoStatus.Status;
        Information = Irp->IoStatus.Information;

        break;
    }
    case IRP_MN_QUERY_BUS_INFORMATION:
    {
        PPNP_BUS_INFORMATION BusInfo;

        BusInfo = (PPNP_BUS_INFORMATION)ExAllocatePool(PagedPool, sizeof(PNP_BUS_INFORMATION));
        if (!BusInfo)
            Status = STATUS_INSUFFICIENT_RESOURCES;
        else
        {
            /* FIXME */
            /*RtlCopyMemory(
                &BusInfo->BusTypeGuid,
                &GUID_DEVINTERFACE_XXX,
                sizeof(GUID));*/

            BusInfo->LegacyBusType = PNPBus;
            BusInfo->BusNumber = 0;
            Information = (ULONG_PTR)BusInfo;
            Status = STATUS_SUCCESS;
        }
        break;
    }
    default:
    {
        /* We are the PDO. So ignore */
        DPRINT1("IRP_MJ_PNP / Unknown minor function 0x%lx\n", MinorFunction);
        break;
    }
    }

    Irp->IoStatus.Information = Information;
    Irp->IoStatus.Status = Status;
    IoCompleteRequest(Irp, IO_NO_INCREMENT);
    return Status;
}
예제 #18
0
파일: isousb.c 프로젝트: bluefix/picsdr
NTSTATUS
IsoUsb_SymbolicLink(
    IN PDEVICE_OBJECT DeviceObject,
    IN OUT PUNICODE_STRING deviceLinkUnicodeString

    )
/*++

Routine Description:

    This routine is called to create and initialize
    a GUID-based symbolic link to our device to be used to open/create
    instances of us from user mode.

    Called from IsoUsb_CreateDeviceObject() to create the link.

Arguments:

    DeviceObject - pointer to our Physical Device Object ( PDO )

    deviceLinkUnicodeString - Points to a unicode string structure allocated by the caller.
	If this routine is successful, it initializes the unicode string and allocates
	the string buffer containing the kernel-mode path to the symbolic link for this
	device interface.


Return Value:

    STATUS_SUCCESS if successful,
    STATUS_UNSUCCESSFUL otherwise

--*/{
    NTSTATUS ntStatus = STATUS_SUCCESS;


    //  Create the symbolic link

    // IoRegisterDeviceInterface registers device functionality (a device interface)
    // that a driver will enable for use by applications or other system components.

    ntStatus = IoRegisterDeviceInterface(
		DeviceObject,
		(LPGUID)&GUID_CLASS_I82930_ISO,
		NULL,
		deviceLinkUnicodeString);

    ISOUSB_KdPrintCond( DBGLVL_MEDIUM, (!(NT_SUCCESS(ntStatus))),
	    ("FAILED to IoRegisterDeviceInterface()\n"));

   if (NT_SUCCESS(ntStatus)) {

       // IoSetDeviceInterfaceState enables or disables a previously
       // registered device interface. Applications and other system components
       // can open only interfaces that are enabled.

	ntStatus = IoSetDeviceInterfaceState(deviceLinkUnicodeString, TRUE);

        ISOUSB_KdPrintCond( DBGLVL_MEDIUM,
		(!(NT_SUCCESS(ntStatus))),
		("FAILED to IoSetDeviceInterfaceState()\n"));

        ISOUSB_KdPrintCond( DBGLVL_MEDIUM,
		((NT_SUCCESS(ntStatus))),
		("SUCCEEDED  IoSetDeviceInterfaceState()\n"));

    }

    return ntStatus;
}
예제 #19
0
파일: pnp.c 프로젝트: hoangduit/reactos
NTSTATUS
NTAPI
DiskInitFdo(
    IN PDEVICE_OBJECT Fdo
    )

/*++

Routine Description:

    This routine is called to do one-time initialization of new device objects


Arguments:

    Fdo - a pointer to the functional device object for this device

Return Value:

    status

--*/

{
    PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = Fdo->DeviceExtension;

    PDISK_DATA diskData = (PDISK_DATA) fdoExtension->CommonExtension.DriverData;

    //ULONG srbFlags = 0;

    ULONG timeOut = 0;

    ULONG bytesPerSector;
    //UCHAR sectorShift;

    //BOOLEAN dmActive = FALSE;
    PULONG dmSkew;
    //ULONG dmByteSkew;

    NTSTATUS status;

    PAGED_CODE();

    //
    // Build the lookaside list for srb's for the physical disk. Should only
    // need a couple.  If this fails then we don't have an emergency SRB so
    // fail the call to initialize.
    //

    ClassInitializeSrbLookasideList((PCOMMON_DEVICE_EXTENSION) fdoExtension,
                                    PARTITION0_LIST_SIZE);

    //
    // Because all requests share a common sense buffer, it is possible
    // for the buffer to be overwritten if the port driver completes
    // multiple failed requests that require a request sense before the
    // class driver's completion routine can consume the data in the buffer.
    // To prevent this, we allow the port driver to allocate a unique sense
    // buffer each time it needs one.  We are responsible for freeing this
    // buffer.  This also allows the adapter to be configured to support
    // additional sense data beyond the minimum 18 bytes.
    //

    fdoExtension->SrbFlags = SRB_FLAGS_PORT_DRIVER_ALLOCSENSE;

    //
    // Initialize the srb flags.
    //

    if (fdoExtension->DeviceDescriptor->CommandQueueing &&
        fdoExtension->AdapterDescriptor->CommandQueueing) {

        fdoExtension->SrbFlags = SRB_FLAGS_QUEUE_ACTION_ENABLE;

    }

    if (!TEST_FLAG(Fdo->Characteristics, FILE_REMOVABLE_MEDIA)) {
        SET_FLAG(fdoExtension->DeviceFlags, DEV_SAFE_START_UNIT);
    }

    //
    // Look for controllers that require special flags.
    //

    ClassScanForSpecial(fdoExtension, DiskBadControllers, DiskSetSpecialHacks);

    //
    // Look into the registry to see if this device
    // requires special attention - [ like a hack ]
    //

    DiskScanRegistryForSpecial(fdoExtension);

    //srbFlags = fdoExtension->SrbFlags;

    //
    // Clear buffer for drive geometry.
    //

    RtlZeroMemory(&(fdoExtension->DiskGeometry),
                  sizeof(DISK_GEOMETRY));

    //
    // Allocate request sense buffer.
    //

    fdoExtension->SenseData = ExAllocatePoolWithTag(NonPagedPoolCacheAligned,
                                                    SENSE_BUFFER_SIZE,
                                                    DISK_TAG_START);

    if (fdoExtension->SenseData == NULL) {

        //
        // The buffer can not be allocated.
        //

        DebugPrint((1, "DiskInitFdo: Can not allocate request sense buffer\n"));

        status = STATUS_INSUFFICIENT_RESOURCES;
        return status;
    }

    //
    // Physical device object will describe the entire
    // device, starting at byte offset 0.
    //

    fdoExtension->CommonExtension.StartingOffset.QuadPart = (LONGLONG)(0);

    //
    // Set timeout value in seconds.
    //

    timeOut = ClassQueryTimeOutRegistryValue(Fdo);
    if (timeOut) {
        fdoExtension->TimeOutValue = timeOut;
    } else {
        fdoExtension->TimeOutValue = SCSI_DISK_TIMEOUT;
    }

    //
    // If this is a removable drive, build an entry in devicemap\scsi
    // indicating it's physicaldriveN name, set up the appropriate
    // update partitions routine and set the flags correctly.
    // note: only do this after the timeout value is set, above.
    //

    if (fdoExtension->DeviceDescriptor->RemovableMedia) {
        ClassUpdateInformationInRegistry( Fdo,
                                          "PhysicalDrive",
                                          fdoExtension->DeviceNumber,
                                          NULL,
                                          0);
        //
        // Enable media change notification for removable disks
        //
        ClassInitializeMediaChangeDetection(fdoExtension,
                                            "Disk");

        SET_FLAG(Fdo->Characteristics, FILE_REMOVABLE_MEDIA);
        diskData->UpdatePartitionRoutine = DiskUpdateRemovablePartitions;

    } else {

        SET_FLAG(fdoExtension->SrbFlags, SRB_FLAGS_NO_QUEUE_FREEZE);
        diskData->UpdatePartitionRoutine = DiskUpdatePartitions;

    }

    //
    // Read the drive capacity.  Don't use the disk version of the routine here
    // since we don't know the disk signature yet - the disk version will
    // attempt to determine the BIOS reported geometry.
    //

    status = ClassReadDriveCapacity(Fdo);

    //
    // If the read capcity failed then just return, unless this is a
    // removable disk where a device object partition needs to be created.
    //

    if (!NT_SUCCESS(status) &&
        !(Fdo->Characteristics & FILE_REMOVABLE_MEDIA)) {

        DebugPrint((1,
            "DiskInitFdo: Can't read capacity for device %p\n",
            Fdo));

        if (fdoExtension->DeviceDescriptor->RemovableMedia) {
            fdoExtension->DiskGeometry.MediaType = RemovableMedia;
            Fdo->Flags &= ~DO_VERIFY_VOLUME;
        } else {
            fdoExtension->DiskGeometry.MediaType = FixedMedia;
        }

        status = STATUS_SUCCESS;
    }

    //
    // Set up sector size fields.
    //
    // Stack variables will be used to update
    // the partition device extensions.
    //
    // The device extension field SectorShift is
    // used to calculate sectors in I/O transfers.
    //
    // The DiskGeometry structure is used to service
    // IOCTls used by the format utility.
    //

    bytesPerSector = fdoExtension->DiskGeometry.BytesPerSector;

    //
    // Make sure sector size is not zero.
    //

    if (bytesPerSector == 0) {

        //
        // Default sector size for disk is 512.
        //

        bytesPerSector = fdoExtension->DiskGeometry.BytesPerSector = 512;
    }

    //sectorShift = fdoExtension->SectorShift;

    //
    // Determine is DM Driver is loaded on an IDE drive that is
    // under control of Atapi - this could be either a crashdump or
    // an Atapi device is sharing the controller with an IDE disk.
    //

    HalExamineMBR(fdoExtension->CommonExtension.DeviceObject,
                  fdoExtension->DiskGeometry.BytesPerSector,
                  (ULONG)0x54,
                  (PVOID*)&dmSkew);

    if (dmSkew) {

        //
        // Update the device extension, so that the call to IoReadPartitionTable
        // will get the correct information. Any I/O to this disk will have
        // to be skewed by *dmSkew sectors aka DMByteSkew.
        //

        fdoExtension->DMSkew = *dmSkew;
        fdoExtension->DMActive = TRUE;
        fdoExtension->DMByteSkew = fdoExtension->DMSkew * bytesPerSector;

        //
        // Save away the infomation that we need, since this deviceExtension will soon be
        // blown away.
        //

        //dmActive = TRUE;
        //dmByteSkew = fdoExtension->DMByteSkew;

    }

#if defined(_X86_)
    //
    // Try to read the signature off the disk and determine the correct drive
    // geometry based on that.  This requires rereading the disk size to get
    // the cylinder count updated correctly.
    //

    if(fdoExtension->DeviceDescriptor->RemovableMedia == FALSE) {
        DiskReadSignature(Fdo);
        DiskReadDriveCapacity(Fdo);
    }
#endif

    //
    // Register interfaces for this device
    //
    {
        UNICODE_STRING interfaceName;

        RtlInitUnicodeString(&interfaceName, NULL);

        status = IoRegisterDeviceInterface(fdoExtension->LowerPdo,
                                           (LPGUID) &DiskClassGuid,
                                           NULL,
                                           &interfaceName);

        if(NT_SUCCESS(status)) {

            diskData->DiskInterfaceString = interfaceName;
            status = IoSetDeviceInterfaceState(&interfaceName, TRUE);

        } else {
            interfaceName.Buffer = NULL;
        }

        if(!NT_SUCCESS(status)) {

            DebugPrint((1, "DiskInitFdo: Unable to register or set disk DCA "
                           "for fdo %p [%lx]\n", Fdo, status));

            RtlFreeUnicodeString(&interfaceName);
            RtlInitUnicodeString(&(diskData->DiskInterfaceString), NULL);
        }
    }

    DiskCreateSymbolicLinks(Fdo);

    //
    // Determine the type of disk and enable failure preiction in the hardware
    // and enable failure prediction polling.
    //

    if (InitSafeBootMode == 0)
    {
        DiskDetectFailurePrediction(fdoExtension,
                                  &diskData->FailurePredictionCapability);

        if (diskData->FailurePredictionCapability != FailurePredictionNone)
        {
            //
            // Cool, we've got some sort of failure prediction, enable it
            // at the hardware and then enable polling for it
            //

            //
            // By default we allow performance to be degradeded if failure
            // prediction is enabled.
            //
            // TODO: Make a registry entry ?
            //

            diskData->AllowFPPerfHit = TRUE;

            //
            // Enable polling only after Atapi and SBP2 add support for the new
            // SRB flag that indicates that the request should not reset the
            // drive spin down idle timer.
            //

            status = DiskEnableDisableFailurePredictPolling(fdoExtension,
                                          TRUE,
                                          DISK_DEFAULT_FAILURE_POLLING_PERIOD);

            DebugPrint((3, "DiskInitFdo: Failure Prediction Poll enabled as "
                           "%d for device %p\n",
                     diskData->FailurePredictionCapability,
                     Fdo));
        }
    } else {

        //
        // In safe boot mode we do not enable failure prediction, as perhaps
        // it is the reason why normal boot does not work
        //

        diskData->FailurePredictionCapability = FailurePredictionNone;

    }

    //
    // Initialize the verify mutex
    //

    KeInitializeMutex(&diskData->VerifyMutex, MAX_SECTORS_PER_VERIFY);

    return(STATUS_SUCCESS);

} // end DiskInitFdo()
예제 #20
0
파일: pnp.c 프로젝트: imahmoodz/ScpToolkit
NTSTATUS Bus_AddDevice(__in PDRIVER_OBJECT DriverObject, __in PDEVICE_OBJECT PhysicalDeviceObject)
{
    NTSTATUS            status;
    PDEVICE_OBJECT      deviceObject = NULL;
    PFDO_DEVICE_DATA    deviceData = NULL;
    PWCHAR              deviceName = NULL;
    ULONG               nameLength;

    UNREFERENCED_PARAMETER(nameLength);
    PAGED_CODE();

    Bus_KdPrint(("Add Device: 0x%p\n", PhysicalDeviceObject));

    status = IoCreateDevice(DriverObject, sizeof(FDO_DEVICE_DATA), NULL, FILE_DEVICE_BUS_EXTENDER, FILE_DEVICE_SECURE_OPEN, TRUE, &deviceObject);

    if (!NT_SUCCESS (status))
    {
        goto End;
    }

    deviceData = (PFDO_DEVICE_DATA) deviceObject->DeviceExtension;
    RtlZeroMemory(deviceData, sizeof (FDO_DEVICE_DATA));

    INITIALIZE_PNP_STATE(deviceData);

    deviceData->IsFDO = TRUE;
    deviceData->Self  = deviceObject;

    ExInitializeFastMutex(&deviceData->Mutex);
    InitializeListHead(&deviceData->ListOfPDOs);

    deviceData->UnderlyingPDO = PhysicalDeviceObject;

    deviceData->DevicePowerState = PowerDeviceUnspecified;
    deviceData->SystemPowerState = PowerSystemWorking;
    deviceData->OutstandingIO = 1;

    KeInitializeEvent(&deviceData->RemoveEvent, SynchronizationEvent, FALSE);
    KeInitializeEvent(&deviceData->StopEvent,   SynchronizationEvent, TRUE);

    deviceObject->Flags |= DO_POWER_PAGABLE;

    status = IoRegisterDeviceInterface(PhysicalDeviceObject, (LPGUID) &GUID_DEVINTERFACE_SCPVBUS, NULL, &deviceData->InterfaceName);

    if (!NT_SUCCESS(status))
	{
        Bus_KdPrint(("AddDevice: IoRegisterDeviceInterface failed (%x)", status));
        goto End;
    }

    deviceData->NextLowerDriver = IoAttachDeviceToDeviceStack(deviceObject, PhysicalDeviceObject);

    if (deviceData->NextLowerDriver == NULL)
	{
        status = STATUS_NO_SUCH_DEVICE;
        goto End;
    }

    deviceObject->Flags &= ~DO_DEVICE_INITIALIZING;

End:

    if (deviceName)
	{
        ExFreePool(deviceName);
    }

    if (!NT_SUCCESS(status) && deviceObject)
	{
        if (deviceData && deviceData->NextLowerDriver)
		{
            IoDetachDevice(deviceData->NextLowerDriver);
        }

        IoDeleteDevice(deviceObject);
    }

    return status;
}
예제 #21
0
파일: PPJoyBus.c 프로젝트: Cyborg11/PPJoy
NTSTATUS PPJoyBus_AddDevice (IN PDRIVER_OBJECT DriverObject, IN PDEVICE_OBJECT PhysicalDeviceObject)
{
 NTSTATUS			ntStatus;
 PDEVICE_OBJECT		DeviceObject;
 PBUS_DEVICE_DATA	BusDeviceData;

 PAGED_CODE ();

 ntStatus= STATUS_SUCCESS;

 PPJOY_DBGPRINT (FILE_PPJOYBUS|PPJOY_FENTRY, ("PPJoyBus_AddDevice(DriverObject=0x%p,FunctionalDeviceObject=0x%p)",DriverObject,PhysicalDeviceObject) );

 /* Create our FDO device */
 ntStatus= IoCreateDevice (DriverObject,sizeof(BUS_DEVICE_DATA),NULL,FILE_DEVICE_BUS_EXTENDER,FILE_DEVICE_SECURE_OPEN,TRUE,&DeviceObject);
 /* Check to see if we could create the device. If not, exit. */
 if (!NT_SUCCESS (ntStatus)) 
 {
  PPJoyBus_WriteEventLog (PPJ_MSG_ERRORCREATINGBUS,&ntStatus,sizeof(ntStatus),L"");
  PPJOY_DBGPRINT (FILE_PPJOYBUS|PPJOY_ERROR, ("PPJoyBus_AddDevice: IoCreateDevice failed status= 0x%x)",ntStatus) );
  goto ExitNoDelete;
 }

 /* Setup our DeviceExtension */
 BusDeviceData= (PBUS_DEVICE_DATA) DeviceObject->DeviceExtension;
 RtlZeroMemory (BusDeviceData,sizeof(BUS_DEVICE_DATA));
 BusDeviceData->Flags|= PPJFLAGS_ISBUSDEV;

 /* Tell IOManager et al that we are pagable. */
 DeviceObject->Flags|= DO_POWER_PAGABLE;

 /* Attempt to register an interface for this DeviceObject. It will be */
 /* called by the configuration utility to add and remove joysticks.   */
 ntStatus= IoRegisterDeviceInterface (PhysicalDeviceObject,(LPGUID) &GUID_PPJOY_BUS,NULL,&BusDeviceData->InterfaceName);
 /* If we could not register the interface then we exit and delete the DO */
 if (!NT_SUCCESS (ntStatus))
 {
  PPJOY_DBGPRINT (FILE_PPJOYBUS|PPJOY_ERROR, ("PPJoyBus_AddDevice: IoRegisterDeviceInterface failed status= 0x%x)",ntStatus) );
  PPJoyBus_WriteEventLog (PPJ_MSG_ERRORBUSIF,&ntStatus,sizeof(ntStatus),L"");
  goto ExitDeleteDevice;
 }

 PPJOY_DBGPRINT (FILE_PPJOYBUS|PPJOY_BABBLE2, ("PPJoyBus_AddDevice: IoRegisterDeviceInterface interface name= %S)",BusDeviceData->InterfaceName.Buffer) );
 
 /* Now attach ourselves to the device stack. The return value is the next */
 /* lower down Device Object. This is where all the IRPs should be routed. */
 BusDeviceData->NextLowerDriver= IoAttachDeviceToDeviceStack (DeviceObject,PhysicalDeviceObject);
 /* Test if our attach was successful, exit if not. */
 if(!BusDeviceData->NextLowerDriver)
 {
  PPJOY_DBGPRINT (FILE_PPJOYBUS|PPJOY_ERROR, ("PPJoyBus_AddDevice: IoAttachDeviceToDeviceStack failed status= 0x%x)",ntStatus) );
  ntStatus= STATUS_NO_SUCH_DEVICE;

  PPJoyBus_WriteEventLog (PPJ_MSG_ERRORBUSATTACH,&ntStatus,sizeof(ntStatus),L"");
  RtlFreeUnicodeString (&BusDeviceData->InterfaceName);
  goto ExitDeleteDevice;
 }

 /* Save important pointers in our DeviceExtenstion for later use. */
 BusDeviceData->DriverObject= DriverObject;
 BusDeviceData->Self= DeviceObject;
 BusDeviceData->UnderlyingPDO= PhysicalDeviceObject;

 /* Initialise per DeviceObject objects */
 InitializeListHead (&BusDeviceData->JoystickList);
 KeInitializeEvent (&BusDeviceData->RemoveEvent,SynchronizationEvent,FALSE);

 /* Read configuration options from the registry */
 PPJoyBus_ReadOptionsFromReg (DeviceObject);

 /* Read persistent joystick device data from the registry and create PDOs */
 /* This call can possibly move to the DriverEntry routine???              */
 PPJoyBus_CreateFromRegistry (DeviceObject);

 /* Done initializing, clear flag. Should be the final step in AddDevice.  */
 DeviceObject->Flags &= ~DO_DEVICE_INITIALIZING;
 goto ExitNoDelete;

ExitDeleteDevice:
 IoDeleteDevice (DeviceObject);

ExitNoDelete:
 PPJOY_EXITPROC (FILE_PPJOYBUS|PPJOY_FEXIT_STATUSOK, "PPJoyBus_AddDevice",ntStatus);

 return ntStatus;
}
예제 #22
0
static VOID NTAPI
i8042PowerWorkItem(
	IN PDEVICE_OBJECT DeviceObject,
	IN PVOID Context)
{
	PI8042_KEYBOARD_EXTENSION DeviceExtension;
	PIRP WaitingIrp;
	NTSTATUS Status;

	DeviceExtension = (PI8042_KEYBOARD_EXTENSION)Context;

	UNREFERENCED_PARAMETER(DeviceObject);

	/* See http://blogs.msdn.com/doronh/archive/2006/09/08/746961.aspx */

	/* Register GUID_DEVICE_SYS_BUTTON interface and report capability */
	if (DeviceExtension->NewCaps != DeviceExtension->ReportedCaps)
	{
		WaitingIrp = InterlockedExchangePointer((PVOID)&DeviceExtension->PowerIrp, NULL);
		if (WaitingIrp)
		{
			/* Cancel the current power irp, as capability changed */
			WaitingIrp->IoStatus.Status = STATUS_UNSUCCESSFUL;
			WaitingIrp->IoStatus.Information = sizeof(ULONG);
			IoCompleteRequest(WaitingIrp, IO_NO_INCREMENT);
		}

		if (DeviceExtension->PowerInterfaceName.MaximumLength == 0)
		{
			/* We have never registred this interface ; do it */
			Status = IoRegisterDeviceInterface(
				DeviceExtension->Common.Pdo,
				&GUID_DEVICE_SYS_BUTTON,
				NULL,
				&DeviceExtension->PowerInterfaceName);
			if (!NT_SUCCESS(Status))
			{
				/* We can't do more yet, ignore the keypress... */
				WARN_(I8042PRT, "IoRegisterDeviceInterface(GUID_DEVICE_SYS_BUTTON) failed with status 0x%08lx\n",
					Status);
				DeviceExtension->PowerInterfaceName.MaximumLength = 0;
				return;
			}
		}
		else
		{
			/* Disable the interface. Once activated again, capabilities would be asked again */
			Status = IoSetDeviceInterfaceState(
				&DeviceExtension->PowerInterfaceName,
				FALSE);
			if (!NT_SUCCESS(Status))
			{
				/* Ignore the key press... */
				WARN_(I8042PRT, "Disabling interface %wZ failed with status 0x%08lx\n",
					&DeviceExtension->PowerInterfaceName, Status);
				return;
			}
		}
		/* Enable the interface. This leads to receving a IOCTL_GET_SYS_BUTTON_CAPS,
		 * so we can report new capability */
		Status = IoSetDeviceInterfaceState(
				&DeviceExtension->PowerInterfaceName,
				TRUE);
		if (!NT_SUCCESS(Status))
		{
			/* Ignore the key press... */
			WARN_(I8042PRT, "Enabling interface %wZ failed with status 0x%08lx\n",
					&DeviceExtension->PowerInterfaceName, Status);
			return;
		}
	}

	/* Directly complete the IOCTL_GET_SYS_BUTTON_EVENT Irp (if any) */
	WaitingIrp = InterlockedExchangePointer((PVOID)&DeviceExtension->PowerIrp, NULL);
	if (WaitingIrp)
	{
		PULONG pEvent = (PULONG)WaitingIrp->AssociatedIrp.SystemBuffer;

		WaitingIrp->IoStatus.Status = STATUS_SUCCESS;
		WaitingIrp->IoStatus.Information = sizeof(ULONG);
		*pEvent = InterlockedExchange((PLONG)&DeviceExtension->LastPowerKey, 0);
		IoCompleteRequest(WaitingIrp, IO_NO_INCREMENT);
	}
}
예제 #23
0
int FloppyStartDevice(int DeviceObject , int Irp ) 
{ int DeviceObject__DeviceExtension = __VERIFIER_nondet_int() ;
  int Irp__Tail__Overlay__CurrentStackLocation = __VERIFIER_nondet_int() ;
  int Irp__IoStatus__Status ;
  int disketteExtension__TargetObject = __VERIFIER_nondet_int() ;
  int disketteExtension__MaxTransferSize ;
  int disketteExtension__DriveType = __VERIFIER_nondet_int() ;
  int disketteExtension__PerpendicularMode ;
  int disketteExtension__DeviceUnit ;
  int disketteExtension__DriveOnValue ;
  int disketteExtension__UnderlyingPDO = __VERIFIER_nondet_int() ;
  int disketteExtension__InterfaceString = __VERIFIER_nondet_int() ;
  int disketteExtension__IsStarted ;
  int disketteExtension__HoldNewRequests ;
  int ntStatus ;
  int pnpStatus ;
  int doneEvent = __VERIFIER_nondet_int() ;
  int fdcInfo = __VERIFIER_nondet_int() ;
  int fdcInfo__BufferCount ;
  int fdcInfo__BufferSize ;
  int fdcInfo__MaxTransferSize = __VERIFIER_nondet_int() ;
  int fdcInfo__AcpiBios = __VERIFIER_nondet_int() ;
  int fdcInfo__AcpiFdiSupported = __VERIFIER_nondet_int() ;
  int fdcInfo__PeripheralNumber = __VERIFIER_nondet_int() ;
  int fdcInfo__BusType ;
  int fdcInfo__ControllerNumber = __VERIFIER_nondet_int() ;
  int fdcInfo__UnitNumber = __VERIFIER_nondet_int() ;
  int fdcInfo__BusNumber = __VERIFIER_nondet_int() ;
  int Dc ;
  int Fp ;
  int disketteExtension ;
  int irpSp ;
  int irpSp___0 ;
  int nextIrpSp ;
  int nextIrpSp__Control ;
  int irpSp___1 ;
  int irpSp__Control ;
  int irpSp__Context ;
  int InterfaceType ;
  int KUSER_SHARED_DATA__AlternativeArchitecture_NEC98x86 = __VERIFIER_nondet_int() ;
  long __cil_tmp42 ;
  int __cil_tmp43 ;
  int __cil_tmp44 ;
  int __cil_tmp45 ;
  int __cil_tmp46 ;
  int __cil_tmp47 ;
  int __cil_tmp48 ;
  int __cil_tmp49 ;

  {
#line 503
  Dc = DiskController;
#line 504
  Fp = FloppyDiskPeripheral;
#line 505
  disketteExtension = DeviceObject__DeviceExtension;
#line 506
  irpSp = Irp__Tail__Overlay__CurrentStackLocation;
#line 507
  irpSp___0 = Irp__Tail__Overlay__CurrentStackLocation;
#line 508
  nextIrpSp = Irp__Tail__Overlay__CurrentStackLocation - 1;
#line 509
  nextIrpSp__Control = 0;
#line 510
  if (s != NP) {
    {
#line 512
    errorFn();
    }
  } else {
#line 515
    if (compRegistered != 0) {
      {
#line 517
      errorFn();
      }
    } else {
#line 520
      compRegistered = 1;
    }
  }
  {
#line 524
  irpSp___1 = Irp__Tail__Overlay__CurrentStackLocation - 1;
#line 525
  irpSp__Context = doneEvent;
#line 526
  irpSp__Control = 224;
#line 530
  ntStatus = IofCallDriver(disketteExtension__TargetObject, Irp);
  }
  {
#line 532
  __cil_tmp42 = (long )ntStatus;
#line 532
  if (__cil_tmp42 == 259L) {
    {
#line 534
    ntStatus = KeWaitForSingleObject(doneEvent, Executive, KernelMode, 0, 0);
#line 535
    ntStatus = myStatus;
    }
  }
  }
  {
#line 541
  fdcInfo__BufferCount = 0;
#line 542
  fdcInfo__BufferSize = 0;
#line 543
  __cil_tmp43 = 3080;
#line 543
  __cil_tmp44 = 458752;
#line 543
  __cil_tmp45 = 461832;
#line 543
  __cil_tmp46 = 461835;
#line 543
  ntStatus = FlFdcDeviceIo(disketteExtension__TargetObject, __cil_tmp46, fdcInfo);
  }
#line 546
  if (ntStatus >= 0) {
#line 547
    disketteExtension__MaxTransferSize = fdcInfo__MaxTransferSize;
#line 548
    if (fdcInfo__AcpiBios) {
#line 549
      if (fdcInfo__AcpiFdiSupported) {
        {
#line 551
        ntStatus = FlAcpiConfigureFloppy(disketteExtension, fdcInfo);
        }
#line 553
        if (disketteExtension__DriveType == 4) {
#line 554
          //__cil_tmp47 = uninf1();
#line 554
          //disketteExtension__PerpendicularMode |= __cil_tmp47;
        }
      } else {
        goto _L;
      }
    } else {
      _L: 
#line 563
      if (disketteExtension__DriveType == 4) {
#line 564
        //__cil_tmp48 = uninf1();
#line 564
        //disketteExtension__PerpendicularMode |= __cil_tmp48;
      }
#line 568
      InterfaceType = 0;
      {
#line 570
      while (1) {
        while_0_continue: /* CIL Label */ ;

#line 572
        if (InterfaceType >= MaximumInterfaceType) {
          goto while_1_break;
        }
        {
#line 578
        fdcInfo__BusType = InterfaceType;
#line 579
        ntStatus = IoQueryDeviceDescription(fdcInfo__BusType, fdcInfo__BusNumber,
                                            Dc, fdcInfo__ControllerNumber, Fp, fdcInfo__PeripheralNumber,
                                            FlConfigCallBack, disketteExtension);
        }
#line 583
        if (ntStatus >= 0) {
          goto while_1_break;
        }
#line 588
        InterfaceType ++;
      }
      while_0_break: /* CIL Label */ ;
      }
      while_1_break: ;
    }
#line 593
    if (ntStatus >= 0) {
#line 594
      if (KUSER_SHARED_DATA__AlternativeArchitecture_NEC98x86 != 0) {
#line 595
        disketteExtension__DeviceUnit = fdcInfo__UnitNumber;
#line 596
        //disketteExtension__DriveOnValue = fdcInfo__UnitNumber;
      } else {
#line 598
        disketteExtension__DeviceUnit = fdcInfo__PeripheralNumber;
#line 599
        //__cil_tmp49 = 16 << fdcInfo__PeripheralNumber;
#line 599
        //disketteExtension__DriveOnValue = fdcInfo__PeripheralNumber | __cil_tmp49;
      }
      {
#line 602
      pnpStatus = IoRegisterDeviceInterface(disketteExtension__UnderlyingPDO, MOUNTDEV_MOUNTED_DEVICE_GUID,
                                            0, disketteExtension__InterfaceString);
      }
#line 605
      if (pnpStatus >= 0) {
        {
#line 607
        pnpStatus = IoSetDeviceInterfaceState(disketteExtension__InterfaceString,
                                              1);
        }
      }
#line 613
      disketteExtension__IsStarted = 1;
#line 614
      disketteExtension__HoldNewRequests = 0;
    }
  }
  {
#line 622
  Irp__IoStatus__Status = ntStatus;
#line 623
  myStatus = ntStatus;
#line 624
  IofCompleteRequest(Irp, 0);
  }
#line 626
  return (ntStatus);
}
}
예제 #24
0
파일: pnp.c 프로젝트: wl500g/usbip-no-glib
NTSTATUS
Bus_AddDevice(
    __in PDRIVER_OBJECT DriverObject,
    __in PDEVICE_OBJECT PhysicalDeviceObject
    )
/*++
Routine Description.

    Our Toaster bus has been found.  Attach our FDO to it.
    Allocate any required resources.  Set things up.
    And be prepared for the ``start device''

Arguments:

    DriverObject - pointer to driver object.

    PhysicalDeviceObject  - Device object representing the bus to which we
                            will attach a new FDO.

--*/
{
    NTSTATUS            status;
    PDEVICE_OBJECT      deviceObject = NULL;
    PFDO_DEVICE_DATA    deviceData = NULL;
    PWCHAR              deviceName = NULL;
    ULONG               nameLength;
    PKTIMER		timer;
    PKDPC		dpc;

    PAGED_CODE ();

    Bus_KdPrint_Def (BUS_DBG_SS_TRACE, ("Add Device: 0x%p\n",
                                          PhysicalDeviceObject));

    status = IoCreateDevice (
                    DriverObject,               // our driver object
                    sizeof (FDO_DEVICE_DATA),   // device object extension size
                    NULL,                       // FDOs do not have names
                    FILE_DEVICE_BUS_EXTENDER,   // We are a bus
                    FILE_DEVICE_SECURE_OPEN,    //
                    TRUE,                       // our FDO is exclusive
                    &deviceObject);             // The device object created

    if (!NT_SUCCESS (status))
    {
        goto End;
    }

    deviceData = (PFDO_DEVICE_DATA) deviceObject->DeviceExtension;
    RtlZeroMemory (deviceData, sizeof (FDO_DEVICE_DATA));

    //
    // Set the initial state of the FDO
    //

    INITIALIZE_PNP_STATE(deviceData);

    deviceData->DebugLevel = BusEnumDebugLevel;

    deviceData->IsFDO = TRUE;

    deviceData->Self = deviceObject;

    ExInitializeFastMutex (&deviceData->Mutex);

    InitializeListHead (&deviceData->ListOfPDOs);

    // Set the PDO for use with PlugPlay functions

    deviceData->UnderlyingPDO = PhysicalDeviceObject;

    //
    // Set the initial powerstate of the FDO
    //

    deviceData->DevicePowerState = PowerDeviceUnspecified;
    deviceData->SystemPowerState = PowerSystemWorking;


    //
    // Biased to 1. Transition to zero during remove device
    // means IO is finished. Transition to 1 means the device
    // can be stopped.
    //

    deviceData->OutstandingIO = 1;

    //
    // Initialize the remove event to Not-Signaled.  This event
    // will be set when the OutstandingIO will become 0.
    //

    KeInitializeEvent(&deviceData->RemoveEvent,
                  SynchronizationEvent,
                  FALSE);
    //
    // Initialize the stop event to Signaled:
    // there are no Irps that prevent the device from being
    // stopped. This event will be set when the OutstandingIO
    // will become 0.
    //

    KeInitializeEvent(&deviceData->StopEvent,
                      SynchronizationEvent,
                      TRUE);

    deviceObject->Flags |= DO_POWER_PAGABLE|DO_BUFFERED_IO;

    //
    // Tell the Plug & Play system that this device will need a
    // device interface.
    //

    status = IoRegisterDeviceInterface (
                PhysicalDeviceObject,
                (LPGUID) &GUID_DEVINTERFACE_BUSENUM_TOASTER,
                NULL,
                &deviceData->InterfaceName);

    if (!NT_SUCCESS (status)) {
        Bus_KdPrint (deviceData, BUS_DBG_SS_ERROR,
                      ("AddDevice: IoRegisterDeviceInterface failed (%x)", status));
        goto End;
    }

    //
    // Attach our FDO to the device stack.
    // The return value of IoAttachDeviceToDeviceStack is the top of the
    // attachment chain.  This is where all the IRPs should be routed.
    //

    deviceData->NextLowerDriver = IoAttachDeviceToDeviceStack (
                                    deviceObject,
                                    PhysicalDeviceObject);

    if (NULL == deviceData->NextLowerDriver) {

        status = STATUS_NO_SUCH_DEVICE;
        goto End;
    }


#if DBG
    //
    // We will demonstrate here the step to retrieve the name of the PDO
    //

    status = IoGetDeviceProperty (PhysicalDeviceObject,
                                  DevicePropertyPhysicalDeviceObjectName,
                                  0,
                                  NULL,
                                  &nameLength);

    if (status != STATUS_BUFFER_TOO_SMALL)
    {
        Bus_KdPrint (deviceData, BUS_DBG_SS_ERROR,
                      ("AddDevice:IoGDP failed (0x%x)\n", status));
        goto End;
    }

    deviceName = ExAllocatePoolWithTag (NonPagedPool,
                            nameLength, BUSENUM_POOL_TAG);

    if (NULL == deviceName) {
        Bus_KdPrint (deviceData, BUS_DBG_SS_ERROR,
        ("AddDevice: no memory to alloc for deviceName(0x%x)\n", nameLength));
        status =  STATUS_INSUFFICIENT_RESOURCES;
        goto End;
    }

    status = IoGetDeviceProperty (PhysicalDeviceObject,
                         DevicePropertyPhysicalDeviceObjectName,
                         nameLength,
                         deviceName,
                         &nameLength);

    if (!NT_SUCCESS (status)) {

        Bus_KdPrint (deviceData, BUS_DBG_SS_ERROR,
                      ("AddDevice:IoGDP(2) failed (0x%x)", status));
        goto End;
    }

    Bus_KdPrint (deviceData, BUS_DBG_SS_TRACE,
                  ("AddDevice: %p to %p->%p (%ws) \n",
                   deviceObject,
                   deviceData->NextLowerDriver,
                   PhysicalDeviceObject,
                   deviceName));

#endif

    //
    // We are done with initializing, so let's indicate that and return.
    // This should be the final step in the AddDevice process.
    //
    deviceObject->Flags &= ~DO_DEVICE_INITIALIZING;

End:
    if (deviceName){
        ExFreePool(deviceName);
    }

    if (!NT_SUCCESS(status) && deviceObject){
        if (deviceData && deviceData->NextLowerDriver){
            IoDetachDevice (deviceData->NextLowerDriver);
        }
        IoDeleteDevice (deviceObject);
    }

    return status;

}
예제 #25
0
NTSTATUS
MobiUsb_AddDevice(
    IN PDRIVER_OBJECT DriverObject,
    IN PDEVICE_OBJECT PhysicalDeviceObject
    )
/*++

Description:

Arguments:

    DriverObject - Store the pointer to the object representing us.

    PhysicalDeviceObject - Pointer to the device object created by the
                           undelying bus driver.

Return:
	
    STATUS_SUCCESS - if successful 
    STATUS_UNSUCCESSFUL - otherwise

--*/
{
    NTSTATUS          ntStatus;
    PDEVICE_OBJECT    deviceObject;
    PDEVICE_EXTENSION deviceExtension;
    POWER_STATE       state;
    KIRQL             oldIrql;

    MobiUsb_DbgPrint(3, ("file mobiusb: MobiUsb_AddDevice - begins\n"));

    deviceObject = NULL;

    ntStatus = IoCreateDevice(
                    DriverObject,                   // our driver object
                    sizeof(DEVICE_EXTENSION),       // extension size for us
                    NULL,                           // name for this device
                    FILE_DEVICE_UNKNOWN,
                    FILE_AUTOGENERATED_DEVICE_NAME, // device characteristics
                    FALSE,                          // Not exclusive
                    &deviceObject);                 // Our device object

    if(!NT_SUCCESS(ntStatus)) {
        //
        // returning failure here prevents the entire stack from functioning,
        // but most likely the rest of the stack will not be able to create
        // device objects either, so it is still OK.
        //                
        MobiUsb_DbgPrint(1, ("file mobiusb: Failed to create device object\n"));
        return ntStatus;
    }

    //
    // Initialize the device extension
    //

    deviceExtension = (PDEVICE_EXTENSION) deviceObject->DeviceExtension;
    deviceExtension->FunctionalDeviceObject = deviceObject;
    deviceExtension->PhysicalDeviceObject = PhysicalDeviceObject;
#ifdef MOBI_DIRECT_IO
    deviceObject->Flags |= DO_DIRECT_IO;
#else
    deviceObject->Flags |= DO_BUFFERED_IO;
#endif
    //
    // initialize the device state lock and set the device state
    //

    KeInitializeSpinLock(&deviceExtension->DevStateLock);
    INITIALIZE_PNP_STATE(deviceExtension);

    //
    //initialize OpenHandleCount
    //
    deviceExtension->OpenHandleCount = 0;

    //
    // Initialize the selective suspend variables
    //
    KeInitializeSpinLock(&deviceExtension->IdleReqStateLock);
    deviceExtension->IdleReqPend = 0;
    deviceExtension->PendingIdleIrp = NULL;

	//
	// Initialize the vendor command semaphore
	//
    KeInitializeSemaphore(&deviceExtension->CallUSBSemaphore, 1, 1);


    //
    // Hold requests until the device is started
    //

    deviceExtension->QueueState = HoldRequests;

    //
    // Initialize the queue and the queue spin lock
    //

    InitializeListHead(&deviceExtension->NewRequestsQueue);
    KeInitializeSpinLock(&deviceExtension->QueueLock);

    //
    // Initialize the remove event to not-signaled.
    //

    KeInitializeEvent(&deviceExtension->RemoveEvent, 
                      SynchronizationEvent, 
                      FALSE);

    //
    // Initialize the stop event to signaled.
    // This event is signaled when the OutstandingIO becomes 1
    //

    KeInitializeEvent(&deviceExtension->StopEvent, 
                      SynchronizationEvent, 
                      TRUE);

    //
    // OutstandingIo count biased to 1.
    // Transition to 0 during remove device means IO is finished.
    // Transition to 1 means the device can be stopped
    //

    deviceExtension->OutStandingIO = 1;
    KeInitializeSpinLock(&deviceExtension->IOCountLock);

    //
    // Delegating to WMILIB
    //
    ntStatus = MobiUsb_WmiRegistration(deviceExtension);

    if(!NT_SUCCESS(ntStatus)) {

        MobiUsb_DbgPrint(1, ("file mobiusb: MobiUsb_WmiRegistration failed with %X\n", ntStatus));
        IoDeleteDevice(deviceObject);
        return ntStatus;
    }

    //
    // set the flags as underlying PDO
    //

    if(PhysicalDeviceObject->Flags & DO_POWER_PAGABLE) {

        deviceObject->Flags |= DO_POWER_PAGABLE;
    }

    //
    // Typically, the function driver for a device is its 
    // power policy owner, although for some devices another 
    // driver or system component may assume this role. 
    // Set the initial power state of the device, if known, by calling 
    // PoSetPowerState.
    // 

    deviceExtension->DevPower = PowerDeviceD0;
    deviceExtension->SysPower = PowerSystemWorking;

    state.DeviceState = PowerDeviceD0;
    PoSetPowerState(deviceObject, DevicePowerState, state);

    //
    // attach our driver to device stack
    // The return value of IoAttachDeviceToDeviceStack is the top of the
    // attachment chain.  This is where all the IRPs should be routed.
    //

    deviceExtension->TopOfStackDeviceObject = 
                IoAttachDeviceToDeviceStack(deviceObject,
                                            PhysicalDeviceObject);

    if(NULL == deviceExtension->TopOfStackDeviceObject) {

        MobiUsb_WmiDeRegistration(deviceExtension);
        IoDeleteDevice(deviceObject);
        return STATUS_NO_SUCH_DEVICE;
    }
        
    //
    // Register device interfaces
    //

    ntStatus = IoRegisterDeviceInterface(deviceExtension->PhysicalDeviceObject, 
                                         &GUID_CLASS_VCMOBI_MOBI, 
                                         NULL, 
                                         &deviceExtension->InterfaceName);

    if(!NT_SUCCESS(ntStatus)) {

        MobiUsb_WmiDeRegistration(deviceExtension);
        IoDetachDevice(deviceExtension->TopOfStackDeviceObject);
        IoDeleteDevice(deviceObject);
        return ntStatus;
    }
	
	//MobiUsb_DbgPrint(3, ("file mobiusb: interfacename: Filename = %ws nameLength = %d\n", deviceExtension->InterfaceName.Buffer, deviceExtension->InterfaceName.Length / sizeof(WCHAR)));
    
	if(IoIsWdmVersionAvailable(1, 0x20)) {

        deviceExtension->WdmVersion = WinXpOrBetter;
    }
    else if(IoIsWdmVersionAvailable(1, 0x10)) {

        deviceExtension->WdmVersion = Win2kOrBetter;
    }
    else if(IoIsWdmVersionAvailable(1, 0x5)) {

        deviceExtension->WdmVersion = WinMeOrBetter;
    }
    else if(IoIsWdmVersionAvailable(1, 0x0)) {

        deviceExtension->WdmVersion = Win98OrBetter;
    }
    MobiUsb_DbgPrint(3, ("file mobiusb: WdmVersion = %d\n", deviceExtension->WdmVersion));

    deviceExtension->SSRegistryEnable = 0;
    deviceExtension->SSEnable = 0;

    //
    // WinXP only
    // check the registry flag -
    // whether the device should selectively
    // suspend when idle
    //

    if(WinXpOrBetter == deviceExtension->WdmVersion) {

        MobiUsb_GetRegistryDword(MOBIUSB_REGISTRY_PARAMETERS_PATH,
                                 L"VCMobiEnable",
                                 &deviceExtension->SSRegistryEnable);

        if(deviceExtension->SSRegistryEnable) {

            //
            // initialize DPC
            //
            KeInitializeDpc(&deviceExtension->DeferredProcCall, 
                            DpcRoutine, 
                            deviceObject);

            //
            // initialize the timer.
            // the DPC and the timer in conjunction, 
            // monitor the state of the device to 
            // selectively suspend the device.
            //
            KeInitializeTimerEx(&deviceExtension->Timer,
                                NotificationTimer);

            //
            // Initialize the NoDpcWorkItemPendingEvent to signaled state.
            // This event is cleared when a Dpc is fired and signaled
            // on completion of the work-item.
            //
            KeInitializeEvent(&deviceExtension->NoDpcWorkItemPendingEvent, 
                              NotificationEvent, 
                              TRUE);

            //
            // Initialize the NoIdleReqPendEvent to ensure that the idle request
            // is indeed complete before we unload the drivers.
            //
            KeInitializeEvent(&deviceExtension->NoIdleReqPendEvent,
                              NotificationEvent,
                              TRUE);
        }
    }

    //
    // Clear the DO_DEVICE_INITIALIZING flag.
    // Note: Do not clear this flag until the driver has set the
    // device power state and the power DO flags. 
    //

    deviceObject->Flags &= ~DO_DEVICE_INITIALIZING;

    MobiUsb_DbgPrint(3, ("file mobiusb: MobiUsb_AddDevice - ends\n"));

    return ntStatus;
}
예제 #26
0
파일: pdo.c 프로젝트: RPG-7/reactos
NTSTATUS
HidClassPDO_PnP(
    IN PDEVICE_OBJECT DeviceObject,
    IN PIRP Irp)
{
    PHIDCLASS_PDO_DEVICE_EXTENSION PDODeviceExtension;
    PIO_STACK_LOCATION IoStack;
    NTSTATUS Status;
    PPNP_BUS_INFORMATION BusInformation;
    PDEVICE_RELATIONS DeviceRelation;
    ULONG Index, bFound;

    //
    // get device extension
    //
    PDODeviceExtension = DeviceObject->DeviceExtension;
    ASSERT(PDODeviceExtension->Common.IsFDO == FALSE);

    //
    // get current irp stack location
    //
    IoStack = IoGetCurrentIrpStackLocation(Irp);

    //
    // handle request
    //
    switch (IoStack->MinorFunction)
    {
        case IRP_MN_QUERY_ID:
        {
            if (IoStack->Parameters.QueryId.IdType == BusQueryDeviceID)
            {
                //
                // handle query device id
                //
                Status = HidClassPDO_HandleQueryDeviceId(DeviceObject, Irp);
                break;
            }
            else if (IoStack->Parameters.QueryId.IdType == BusQueryHardwareIDs)
            {
                //
                // handle instance id
                //
                Status = HidClassPDO_HandleQueryHardwareId(DeviceObject, Irp);
                break;
            }
            else if (IoStack->Parameters.QueryId.IdType == BusQueryInstanceID)
            {
                //
                // handle instance id
                //
                Status = HidClassPDO_HandleQueryInstanceId(DeviceObject, Irp);
                break;
            }
            else if (IoStack->Parameters.QueryId.IdType == BusQueryCompatibleIDs)
            {
                //
                // handle instance id
                //
                Status = HidClassPDO_HandleQueryCompatibleId(DeviceObject, Irp);
                break;
            }

            DPRINT1("[HIDCLASS]: IRP_MN_QUERY_ID IdType %x unimplemented\n", IoStack->Parameters.QueryId.IdType);
            Status = STATUS_NOT_SUPPORTED;
            Irp->IoStatus.Information = 0;
            break;
        }
        case IRP_MN_QUERY_CAPABILITIES:
        {
            if (IoStack->Parameters.DeviceCapabilities.Capabilities == NULL)
            {
                //
                // invalid request
                //
                Status = STATUS_DEVICE_CONFIGURATION_ERROR;
                break;
            }

            //
            // copy capabilities
            //
            RtlCopyMemory(IoStack->Parameters.DeviceCapabilities.Capabilities,
                          &PDODeviceExtension->Capabilities,
                          sizeof(DEVICE_CAPABILITIES));
            Status = STATUS_SUCCESS;
            break;
        }
        case IRP_MN_QUERY_BUS_INFORMATION:
        {
            //
            //
            //
            BusInformation = ExAllocatePoolWithTag(NonPagedPool, sizeof(PNP_BUS_INFORMATION), HIDCLASS_TAG);

            //
            // fill in result
            //
            RtlCopyMemory(&BusInformation->BusTypeGuid, &GUID_BUS_TYPE_HID, sizeof(GUID));
            BusInformation->LegacyBusType = PNPBus;
            BusInformation->BusNumber = 0; //FIXME

            //
            // store result
            //
            Irp->IoStatus.Information = (ULONG_PTR)BusInformation;
            Status = STATUS_SUCCESS;
            break;
        }
        case IRP_MN_QUERY_PNP_DEVICE_STATE:
        {
            //
            // FIXME set flags when driver fails / disabled
            //
            Status = STATUS_SUCCESS;
            break;
        }
        case IRP_MN_QUERY_DEVICE_RELATIONS:
        {
            //
            // only target relations are supported
            //
            if (IoStack->Parameters.QueryDeviceRelations.Type != TargetDeviceRelation)
            {
                //
                // not supported
                //
                Status = Irp->IoStatus.Status;
                break;
            }

            //
            // allocate device relations
            //
            DeviceRelation = ExAllocatePoolWithTag(NonPagedPool, sizeof(DEVICE_RELATIONS), HIDCLASS_TAG);
            if (!DeviceRelation)
            {
                //
                // no memory
                //
                Status = STATUS_INSUFFICIENT_RESOURCES;
                break;
            }

            //
            // init device relation
            //
            DeviceRelation->Count = 1;
            DeviceRelation->Objects[0] = DeviceObject;
            ObReferenceObject(DeviceRelation->Objects[0]);

            //
            // store result
            //
            Irp->IoStatus.Information = (ULONG_PTR)DeviceRelation;
            Status = STATUS_SUCCESS;
            break;
        }
        case IRP_MN_START_DEVICE:
        {
            //
            // FIXME: support polled devices
            //
            ASSERT(PDODeviceExtension->Common.DriverExtension->DevicesArePolled == FALSE);

            //
            // now register the device interface
            //
            Status = IoRegisterDeviceInterface(PDODeviceExtension->Common.HidDeviceExtension.PhysicalDeviceObject,
                                               &GUID_DEVINTERFACE_HID,
                                               NULL,
                                               &PDODeviceExtension->DeviceInterface);
            DPRINT("[HIDCLASS] IoRegisterDeviceInterfaceState Status %x\n", Status);
            if (NT_SUCCESS(Status))
            {
                //
                // enable device interface
                //
                Status = IoSetDeviceInterfaceState(&PDODeviceExtension->DeviceInterface, TRUE);
                DPRINT("[HIDCLASS] IoSetDeviceInterFaceState %x\n", Status);
            }

            //
            // done
            //
            Status = STATUS_SUCCESS;
            break;
        }
        case IRP_MN_REMOVE_DEVICE:
        {
            /* Disable the device interface */
            if (PDODeviceExtension->DeviceInterface.Length != 0)
                IoSetDeviceInterfaceState(&PDODeviceExtension->DeviceInterface, FALSE);

            //
            // remove us from the fdo's pdo list
            //
            bFound = FALSE;
            for (Index = 0; Index < PDODeviceExtension->FDODeviceExtension->DeviceRelations->Count; Index++)
            {
                if (PDODeviceExtension->FDODeviceExtension->DeviceRelations->Objects[Index] == DeviceObject)
                {
                    //
                    // remove us
                    //
                    bFound = TRUE;
                    PDODeviceExtension->FDODeviceExtension->DeviceRelations->Objects[Index] = NULL;
                    break;
                }
            }

            /* Complete the IRP */
            Irp->IoStatus.Status = STATUS_SUCCESS;
            IoCompleteRequest(Irp, IO_NO_INCREMENT);

            if (bFound)
            {
                /* Delete our device object*/
                IoDeleteDevice(DeviceObject);
            }

            return STATUS_SUCCESS;
        }
        case IRP_MN_QUERY_INTERFACE:
        {
            DPRINT1("[HIDCLASS] PDO IRP_MN_QUERY_INTERFACE not implemented\n");

            //
            // do nothing
            //
            Status = Irp->IoStatus.Status;
            break;
        }
        case IRP_MN_QUERY_REMOVE_DEVICE:
        case IRP_MN_CANCEL_STOP_DEVICE:
        case IRP_MN_QUERY_STOP_DEVICE:
        case IRP_MN_CANCEL_REMOVE_DEVICE:
        {
            //
            // no/op
            //
#if 0
            Status = STATUS_SUCCESS;
#else
            DPRINT1("Denying removal of HID device due to IRP cancellation bugs\n");
            Status = STATUS_UNSUCCESSFUL;
#endif
            break;
        }
        default:
        {
            //
            // do nothing
            //
            Status = Irp->IoStatus.Status;
            break;
        }
    }

    //
    // complete request
    //
    if (Status != STATUS_PENDING)
    {
        //
        // store result
        //
        Irp->IoStatus.Status = Status;

        //
        // complete request
        //
        IoCompleteRequest(Irp, IO_NO_INCREMENT);
    }

    //
    // done processing
    //
    return Status;
}
예제 #27
0
NTSTATUS AddDevice(IN PDRIVER_OBJECT DriverObject, IN PDEVICE_OBJECT pdo)
{
    PAGED_CODE();

    UNICODE_STRING interfaceName;

    KdPrint((DRIVERNAME " - Entering AddDevice: DriverObject %8.8lX, pdo %8.8lX\n", DriverObject, pdo));

    NTSTATUS status;

    // Create a function device object to represent the hardware we're managing.

    PDEVICE_OBJECT fdo;
    
    ULONG dxsize = (sizeof(DEVICE_EXTENSION) + 7) & ~7;
    ULONG xsize = dxsize + GetSizeofGenericExtension();
    
    status = IoCreateDevice(DriverObject, 
                            xsize, 
                            NULL,
                            FILE_DEVICE_UNKNOWN, 
                            FILE_DEVICE_SECURE_OPEN, 
                            FALSE, 
                            &fdo);
    
    if(!NT_SUCCESS(status)){
        KdPrint((DRIVERNAME " - IoCreateDevice failed - %X\n", status));
        return status;
    }
    
    PDEVICE_EXTENSION pdx = (PDEVICE_EXTENSION) fdo->DeviceExtension;

    pdx->operationsInterfaceName.Buffer = NULL;
    pdx->inquiriesInterfaceName .Buffer = NULL;

    RtlInitUnicodeString( &interfaceName, OperationInterface );
    
    status = IoRegisterDeviceInterface(pdo,
                                       &MfUsbGuidOperations,
                                       &interfaceName,
                                       &pdx->operationsInterfaceName);

    if(!NT_SUCCESS(status)){
        KdPrint((DRIVERNAME " - IoRegisterDeviceInterface failed for operations interface - %X\n", status));
        return status;
    }

    RtlInitUnicodeString( &interfaceName, InquiryInterface );
    
    status = IoRegisterDeviceInterface(pdo,
                                       &MfUsbGuidInquiries,
                                       &interfaceName,
                                       &pdx->inquiriesInterfaceName);

    if(!NT_SUCCESS(status)){
        KdPrint((DRIVERNAME " - IoRegisterDeviceInterface failed for inquiry interface - %X\n", status));
        return status;
    }

    // From this point forward, any error will have side effects that need to
    // be cleaned up. Using a do-once allows us to modify the program
    // easily without losing track of the side effects.

    do {
        pdx->DeviceObject = fdo;
        pdx->Pdo = pdo;

        pdx->handles              = 0;
        pdx->devHash              = NULL;        
        pdx->RecoveryThread       = NULL;
        pdx->PollingIrp           = NULL;
        pdx->LowerDeviceObject    = NULL;

        pdx->manufacturer.Buffer  = NULL;      
        pdx->product     .Buffer  = NULL;      
        pdx->serialNumber.Buffer  = NULL;      
        pdx->displayName .Buffer  = NULL;                     
        
        // Declare the buffering method we'll use for read/write requests
        fdo->Flags |= DO_BUFFERED_IO;

        // Initialize irp related locks
        KeInitializeSpinLock(&pdx->ReadIrpLock);
        KeInitializeSpinLock(&pdx->PollLock);

        // Initialize queued read list
        InitializeListHead(&pdx->ReadIrpList);
        
        // Initialize fifo
        KeInitializeSpinLock(&pdx->FifoLock);
        pdx->FifoReadPointer = pdx->FifoWritePointer = 0;

        // Link our device object into the stack leading to the PDO
        pdx->LowerDeviceObject = IoAttachDeviceToDeviceStack(fdo, pdo);
        if(!pdx->LowerDeviceObject) {
            KdPrint((DRIVERNAME " - IoAttachDeviceToDeviceStack failed\n"));
            status = STATUS_DEVICE_REMOVED;
            break;
        }

        // allocate IRP for polling
        pdx->PollingIrp = IoAllocateIrp(pdx->LowerDeviceObject->StackSize, FALSE);

        if(!pdx->PollingIrp) {
            KdPrint((DRIVERNAME " - IoAllocateIrp failed\n"));
            status = STATUS_INSUFFICIENT_RESOURCES;
            break;
        }

        // Set power management flags in the device object
        fdo->Flags |= DO_POWER_PAGABLE;

        // Initialize to use the GENERIC.SYS library
        pdx->pgx = (PGENERIC_EXTENSION) ((PUCHAR) pdx + dxsize);

        GENERIC_INIT_STRUCT gis = {sizeof(GENERIC_INIT_STRUCT)};
        gis.DeviceObject = fdo;
        gis.Pdo = pdo;
        gis.Ldo = pdx->LowerDeviceObject;
        gis.RemoveLock = &pdx->RemoveLock;
        gis.StartDevice = StartDevice;
        gis.StopDevice = StopDevice;
        gis.RemoveDevice = RemoveDevice;
        gis.StartIo = StartIo;
        gis.DeviceQueue = &pdx->dqWrite;
        RtlInitUnicodeString(&gis.DebugName, LDRIVERNAME);
        gis.Flags = GENERIC_SURPRISE_REMOVAL_OK;

        status = InitializeGenericExtension(pdx->pgx, &gis);
        if(!NT_SUCCESS(status)) {
            KdPrint((DRIVERNAME " - InitializeGenericExtension failed - %X\n", status));
            break;
        }

        // Clear the "initializing" flag so that we can get IRPs
        fdo->Flags &= ~DO_DEVICE_INITIALIZING;

        // Set up recovery thread
        pdx->RecoveryExit = FALSE;
        KeInitializeEvent(&pdx->RecoveryEvent, SynchronizationEvent, FALSE);

    } while (FALSE);

    if(!NT_SUCCESS(status)) 
    {

        if(pdx->PollingIrp)
        {
            IoFreeIrp(pdx->PollingIrp);

            pdx->PollingIrp = NULL;
        }

        if(pdx->operationsInterfaceName.Buffer)
        {
            RtlFreeUnicodeString(&pdx->operationsInterfaceName);
    
            pdx->operationsInterfaceName.Buffer = NULL;
        }

        if(pdx->inquiriesInterfaceName.Buffer)
        {
            RtlFreeUnicodeString(&pdx->inquiriesInterfaceName);
    
            pdx->inquiriesInterfaceName.Buffer = NULL;
        }

        if(pdx->LowerDeviceObject)
        {
            IoDetachDevice(pdx->LowerDeviceObject);

            pdx->LowerDeviceObject = NULL;
        }
        
        IoDeleteDevice(fdo);
    }

    return status;
}
예제 #28
0
파일: init.c 프로젝트: MelcherSt/dokany
NTSTATUS
DokanRegisterDeviceInterface(__in PDRIVER_OBJECT DriverObject,
                             __in PDEVICE_OBJECT DeviceObject,
                             __in PDokanDCB Dcb) {
  PDEVICE_OBJECT pnpDeviceObject = NULL;
  NTSTATUS status;

  status = IoReportDetectedDevice(DriverObject, InterfaceTypeUndefined, 0, 0,
                                  NULL, NULL, FALSE, &pnpDeviceObject);

  if (NT_SUCCESS(status)) {
    DDbgPrint("  IoReportDetectedDevice success\n");
  } else {
    DDbgPrint("  IoReportDetectedDevice failed: 0x%x\n", status);
    return status;
  }

  if (IoAttachDeviceToDeviceStack(pnpDeviceObject, DeviceObject) != NULL) {
    DDbgPrint("  IoAttachDeviceToDeviceStack success\n");
  } else {
    DDbgPrint("  IoAttachDeviceToDeviceStack failed\n");
  }

  status = IoRegisterDeviceInterface(pnpDeviceObject, &GUID_DEVINTERFACE_DISK,
                                     NULL, &Dcb->DiskDeviceInterfaceName);

  if (NT_SUCCESS(status)) {
    DDbgPrint("  IoRegisterDeviceInterface success: %wZ\n",
              &Dcb->DiskDeviceInterfaceName);
  } else {
    RtlInitUnicodeString(&Dcb->DiskDeviceInterfaceName, NULL);
    DDbgPrint("  IoRegisterDeviceInterface failed: 0x%x\n", status);
    return status;
  }

  status = IoSetDeviceInterfaceState(&Dcb->DiskDeviceInterfaceName, TRUE);

  if (NT_SUCCESS(status)) {
    DDbgPrint("  IoSetDeviceInterfaceState success\n");
  } else {
    DDbgPrint("  IoSetDeviceInterfaceState failed: 0x%x\n", status);
    return status;
  }

  status =
      IoRegisterDeviceInterface(pnpDeviceObject, &MOUNTDEV_MOUNTED_DEVICE_GUID,
                                NULL, &Dcb->MountedDeviceInterfaceName);

  if (NT_SUCCESS(status)) {
    DDbgPrint("  IoRegisterDeviceInterface success: %wZ\n",
              &Dcb->MountedDeviceInterfaceName);
  } else {
    DDbgPrint("  IoRegisterDeviceInterface failed: 0x%x\n", status);
    return status;
  }

  status = IoSetDeviceInterfaceState(&Dcb->MountedDeviceInterfaceName, TRUE);

  if (NT_SUCCESS(status)) {
    DDbgPrint("  IoSetDeviceInterfaceState success\n");
  } else {
    RtlInitUnicodeString(&Dcb->MountedDeviceInterfaceName, NULL);
    DDbgPrint("  IoSetDeviceInterfaceState failed: 0x%x\n", status);
    return status;
  }

  return status;
}
int FloppyStartDevice(int DeviceObject , int Irp ) 
{ int DeviceObject__DeviceExtension = __VERIFIER_nondet_int() ;
  int Irp__Tail__Overlay__CurrentStackLocation = __VERIFIER_nondet_int() ;
  int Irp__IoStatus__Status ;
  int disketteExtension__TargetObject = __VERIFIER_nondet_int() ;
  int disketteExtension__MaxTransferSize ;
  int disketteExtension__DriveType = __VERIFIER_nondet_int() ;
  int disketteExtension__PerpendicularMode ;
  int disketteExtension__DeviceUnit ;
  int disketteExtension__DriveOnValue ;
  int disketteExtension__UnderlyingPDO = __VERIFIER_nondet_int() ;
  int disketteExtension__InterfaceString = __VERIFIER_nondet_int() ;
  int disketteExtension__IsStarted ;
  int disketteExtension__HoldNewRequests ;
  int ntStatus ;
  int pnpStatus ;
  int doneEvent = __VERIFIER_nondet_int() ;
  int fdcInfo = __VERIFIER_nondet_int() ;
  int fdcInfo__BufferCount ;
  int fdcInfo__BufferSize ;
  int fdcInfo__MaxTransferSize = __VERIFIER_nondet_int() ;
  int fdcInfo__AcpiBios = __VERIFIER_nondet_int() ;
  int fdcInfo__AcpiFdiSupported = __VERIFIER_nondet_int() ;
  int fdcInfo__PeripheralNumber = __VERIFIER_nondet_int() ;
  int fdcInfo__BusType ;
  int fdcInfo__ControllerNumber = __VERIFIER_nondet_int() ;
  int fdcInfo__UnitNumber = __VERIFIER_nondet_int() ;
  int fdcInfo__BusNumber = __VERIFIER_nondet_int() ;
  int Dc ;
  int Fp ;
  int disketteExtension ;
  int irpSp ;
  int irpSp___0 ;
  int nextIrpSp ;
  int nextIrpSp__Control ;
  int irpSp___1 ;
  int irpSp__Control ;
  int irpSp__Context ;
  int InterfaceType ;
  int KUSER_SHARED_DATA__AlternativeArchitecture_NEC98x86 = __VERIFIER_nondet_int() ;
  long __cil_tmp42 ;
  int __cil_tmp43 ;
  int __cil_tmp44 ;
  int __cil_tmp45 ;
  int __cil_tmp46 ;
  int __cil_tmp47 ;
  int __cil_tmp48 ;
  int __cil_tmp49 ;

  {
  Dc = DiskController;
  Fp = FloppyDiskPeripheral;
  disketteExtension = DeviceObject__DeviceExtension;
  irpSp = Irp__Tail__Overlay__CurrentStackLocation;
  irpSp___0 = Irp__Tail__Overlay__CurrentStackLocation;
  nextIrpSp = Irp__Tail__Overlay__CurrentStackLocation - 1;
  nextIrpSp__Control = 0;
  if (s != NP) {
    {
    errorFn();
    }
  } else {
    if (compRegistered != 0) {
      {
      errorFn();
      }
    } else {
      compRegistered = 1;
    }
  }
  {
  irpSp___1 = Irp__Tail__Overlay__CurrentStackLocation - 1;
  irpSp__Context = doneEvent;
  irpSp__Control = 224;
  ntStatus = IofCallDriver(disketteExtension__TargetObject, Irp);
  }
  {
  __cil_tmp42 = (long )ntStatus;
  if (__cil_tmp42 == 259L) {
    {
    ntStatus = KeWaitForSingleObject(doneEvent, Executive, KernelMode, 0, 0);
    ntStatus = myStatus;
    }
  }
  }
  {
  fdcInfo__BufferCount = 0;
  fdcInfo__BufferSize = 0;
  __cil_tmp43 = 3080;
  __cil_tmp44 = 458752;
  __cil_tmp45 = 461832;
  __cil_tmp46 = 461835;
  ntStatus = FlFdcDeviceIo(disketteExtension__TargetObject, __cil_tmp46, fdcInfo);
  }
  if (ntStatus >= 0) {
    disketteExtension__MaxTransferSize = fdcInfo__MaxTransferSize;
    if (fdcInfo__AcpiBios) {
      if (fdcInfo__AcpiFdiSupported) {
        {
        ntStatus = FlAcpiConfigureFloppy(disketteExtension, fdcInfo);
        }
        if (disketteExtension__DriveType == 4) {
          //__cil_tmp47 = uninf1();
          //disketteExtension__PerpendicularMode |= __cil_tmp47;
        }
      } else {
        goto _L;
      }
    } else {
      _L: 
      if (disketteExtension__DriveType == 4) {
        //__cil_tmp48 = uninf1();
        //disketteExtension__PerpendicularMode |= __cil_tmp48;
      }
      InterfaceType = 0;
      {
      while (1) {
        while_0_continue: /* CIL Label */ ;

        if (InterfaceType >= MaximumInterfaceType) {
          goto while_1_break;
        }
        {
        fdcInfo__BusType = InterfaceType;
        ntStatus = IoQueryDeviceDescription(fdcInfo__BusType, fdcInfo__BusNumber,
                                            Dc, fdcInfo__ControllerNumber, Fp, fdcInfo__PeripheralNumber,
                                            FlConfigCallBack, disketteExtension);
        }
        if (ntStatus >= 0) {
          goto while_1_break;
        }
        InterfaceType ++;
      }
      while_0_break: /* CIL Label */ ;
      }
      while_1_break: ;
    }
    if (ntStatus >= 0) {
      if (KUSER_SHARED_DATA__AlternativeArchitecture_NEC98x86 != 0) {
        disketteExtension__DeviceUnit = fdcInfo__UnitNumber;
        //disketteExtension__DriveOnValue = fdcInfo__UnitNumber;
      } else {
        disketteExtension__DeviceUnit = fdcInfo__PeripheralNumber;
        //__cil_tmp49 = 16 << fdcInfo__PeripheralNumber;
        //disketteExtension__DriveOnValue = fdcInfo__PeripheralNumber | __cil_tmp49;
      }
      {
      pnpStatus = IoRegisterDeviceInterface(disketteExtension__UnderlyingPDO, MOUNTDEV_MOUNTED_DEVICE_GUID,
                                            0, disketteExtension__InterfaceString);
      }
      if (pnpStatus >= 0) {
        {
        pnpStatus = IoSetDeviceInterfaceState(disketteExtension__InterfaceString,
                                              1);
        }
      }
      disketteExtension__IsStarted = 1;
      disketteExtension__HoldNewRequests = 0;
    }
  }
  {
  Irp__IoStatus__Status = ntStatus;
  myStatus = ntStatus;
  IofCompleteRequest(Irp, 0);
  }
  return (ntStatus);
}
}
예제 #30
0
파일: pnp.c 프로젝트: kcrazy/winekit
NTSTATUS
Serenum_AddDevice(IN PDRIVER_OBJECT DriverObject,
                  IN PDEVICE_OBJECT BusPhysicalDeviceObject)
/*++
Routine Description.
    A bus has been found.  Attach our FDO to it.
    Allocate any required resources.  Set things up.  And be prepared for the
    first ``start device.''

Arguments:
    BusPhysicalDeviceObject - Device object representing the bus.  That to which
        we attach a new FDO.

    DriverObject - This very self referenced driver.

--*/
{
    NTSTATUS status;
    PDEVICE_OBJECT deviceObject;
    PFDO_DEVICE_DATA pDeviceData;
    HANDLE keyHandle;
    ULONG actualLength;

    PAGED_CODE();

    Serenum_KdPrint_Def(SER_DBG_PNP_TRACE, ("Add Device: 0x%x\n",
                                            BusPhysicalDeviceObject));
    //
    // Create our FDO
    //

    status = IoCreateDevice(DriverObject, sizeof(FDO_DEVICE_DATA), NULL,
                            FILE_DEVICE_BUS_EXTENDER, 0, TRUE, &deviceObject);

    if (NT_SUCCESS(status)) {
        pDeviceData = (PFDO_DEVICE_DATA)deviceObject->DeviceExtension;
        RtlFillMemory (pDeviceData, sizeof (FDO_DEVICE_DATA), 0);

        pDeviceData->IsFDO = TRUE;
        pDeviceData->DebugLevel = SER_DEFAULT_DEBUG_OUTPUT_LEVEL;
        pDeviceData->Self = deviceObject;
        pDeviceData->AttachedPDO = NULL;
        pDeviceData->NumPDOs = 0;
        pDeviceData->DeviceState = PowerDeviceD0;
        pDeviceData->SystemState = PowerSystemWorking;
        pDeviceData->PDOForcedRemove = FALSE;

        pDeviceData->SystemWake=PowerSystemUnspecified;
        pDeviceData->DeviceWake=PowerDeviceUnspecified;

        pDeviceData->Removed = FALSE;

        //
        // Set the PDO for use with PlugPlay functions
        //

        pDeviceData->UnderlyingPDO = BusPhysicalDeviceObject;


        //
        // Attach our filter driver to the device stack.
        // the return value of IoAttachDeviceToDeviceStack is the top of the
        // attachment chain.  This is where all the IRPs should be routed.
        //
        // Our filter will send IRPs to the top of the stack and use the PDO
        // for all PlugPlay functions.
        //

        pDeviceData->TopOfStack
            = IoAttachDeviceToDeviceStack(deviceObject, BusPhysicalDeviceObject);

        if (!pDeviceData->TopOfStack) {
            Serenum_KdPrint(pDeviceData, SER_DBG_PNP_ERROR,
                            ("AddDevice: IoAttach failed (%x)", status));
            IoDeleteDevice(deviceObject);
            return STATUS_UNSUCCESSFUL;
        }

        //
        // Set the type of IO we do
        //

        if (pDeviceData->TopOfStack->Flags & DO_BUFFERED_IO) {
            deviceObject->Flags |= DO_BUFFERED_IO;
        } else if (pDeviceData->TopOfStack->Flags & DO_DIRECT_IO) {
            deviceObject->Flags |= DO_DIRECT_IO;
        }

        //
        // Bias outstanding request to 1 so that we can look for a
        // transition to zero when processing the remove device PlugPlay IRP.
        //

        pDeviceData->OutstandingIO = 1;

        KeInitializeEvent(&pDeviceData->RemoveEvent, SynchronizationEvent,
                          FALSE);
        KeInitializeSemaphore(&pDeviceData->CreateSemaphore, 1, 1);
        KeInitializeSpinLock(&pDeviceData->EnumerationLock);



        //
        // Tell the PlugPlay system that this device will need an interface
        // device class shingle.
        //
        // It may be that the driver cannot hang the shingle until it starts
        // the device itself, so that it can query some of its properties.
        // (Aka the shingles guid (or ref string) is based on the properties
        // of the device.)
        //

        status = IoRegisterDeviceInterface(BusPhysicalDeviceObject,
                                           (LPGUID)&GUID_SERENUM_BUS_ENUMERATOR,
                                           NULL,
                                           &pDeviceData->DevClassAssocName);

        if (!NT_SUCCESS(status)) {
            Serenum_KdPrint(pDeviceData, SER_DBG_PNP_ERROR,
                            ("AddDevice: IoRegisterDCA failed (%x)", status));
            IoDetachDevice(pDeviceData->TopOfStack);
            IoDeleteDevice(deviceObject);
            return status;
        }

        //
        // If for any reason you need to save values in a safe location that
        // clients of this DeviceClassAssociate might be interested in reading
        // here is the time to do so, with the function
        // IoOpenDeviceClassRegistryKey
        // the symbolic link name used is was returned in
        // pDeviceData->DevClassAssocName (the same name which is returned by
        // IoGetDeviceClassAssociations and the SetupAPI equivs.
        //

#if DBG
        {
            PWCHAR deviceName = NULL;
            ULONG nameLength = 0;

            status = IoGetDeviceProperty(BusPhysicalDeviceObject,
                                         DevicePropertyPhysicalDeviceObjectName, 0,
                                         NULL, &nameLength);

            if ((nameLength != 0) && (status == STATUS_BUFFER_TOO_SMALL)) {
                deviceName = ExAllocatePool(NonPagedPool, nameLength);

                if (NULL == deviceName) {
                    goto someDebugStuffExit;
                }

                IoGetDeviceProperty(BusPhysicalDeviceObject,
                                    DevicePropertyPhysicalDeviceObjectName,
                                    nameLength, deviceName, &nameLength);

                Serenum_KdPrint(pDeviceData, SER_DBG_PNP_TRACE,
                                ("AddDevice: %x to %x->%x (%ws) \n", deviceObject,
                                 pDeviceData->TopOfStack, BusPhysicalDeviceObject,
                                 deviceName));
            }

someDebugStuffExit:
            ;
            if (deviceName != NULL) {
                ExFreePool(deviceName);
            }
        }
#endif // DBG

        //
        // Turn on the shingle and point it to the given device object.
        //
        status = IoSetDeviceInterfaceState(&pDeviceData->DevClassAssocName,
                                           TRUE);

        if (!NT_SUCCESS(status)) {
            Serenum_KdPrint(pDeviceData, SER_DBG_PNP_ERROR,
                            ("AddDevice: IoSetDeviceClass failed (%x)", status));
            return status;
        }

        //
        // Open the registry and read in our settings
        //

        status = IoOpenDeviceRegistryKey(pDeviceData->UnderlyingPDO,
                                         PLUGPLAY_REGKEY_DEVICE,
                                         STANDARD_RIGHTS_READ, &keyHandle);

        if (status == STATUS_SUCCESS) {
            status
                = Serenum_GetRegistryKeyValue(keyHandle, L"SkipEnumerations",
                                              sizeof(L"SkipEnumerations"),
                                              &pDeviceData->SkipEnumerations,
                                              sizeof(pDeviceData->SkipEnumerations),
                                              &actualLength);

            if ((status != STATUS_SUCCESS)
                    || (actualLength != sizeof(pDeviceData->SkipEnumerations))) {
                pDeviceData->SkipEnumerations = 0;
                status = STATUS_SUCCESS;

            }

            ZwClose(keyHandle);
        }
    }

    if (NT_SUCCESS(status)) {
        deviceObject->Flags |= DO_POWER_PAGABLE;
        deviceObject->Flags &= ~DO_DEVICE_INITIALIZING;
    }

    return status;
}