2 * PROJECT: ReactOS Kernel
3 * COPYRIGHT: GPL - See COPYING in the top level directory
4 * FILE: ntoskrnl/io/pnpmgr/pnpmgr.c
5 * PURPOSE: Initializes the PnP manager
6 * PROGRAMMERS: Casper S. Hornstrup (chorns@users.sourceforge.net)
7 * Copyright 2007 Hervé Poussineau (hpoussin@reactos.org)
10 /* INCLUDES ******************************************************************/
16 /* GLOBALS *******************************************************************/
18 PDEVICE_NODE IopRootDeviceNode
;
19 KSPIN_LOCK IopDeviceTreeLock
;
20 ERESOURCE PpRegistryDeviceResource
;
21 KGUARDED_MUTEX PpDeviceReferenceTableLock
;
22 RTL_AVL_TABLE PpDeviceReferenceTable
;
24 extern ERESOURCE IopDriverLoadResource
;
25 extern ULONG ExpInitializationPhase
;
26 extern BOOLEAN ExpInTextModeSetup
;
27 extern BOOLEAN PnpSystemInit
;
29 #define MAX_DEVICE_ID_LEN 200
30 #define MAX_SEPARATORS_INSTANCEID 0
31 #define MAX_SEPARATORS_DEVICEID 1
33 /* DATA **********************************************************************/
35 PDRIVER_OBJECT IopRootDriverObject
;
36 PIO_BUS_TYPE_GUID_LIST PnpBusTypeGuidList
= NULL
;
37 LIST_ENTRY IopDeviceActionRequestList
;
38 WORK_QUEUE_ITEM IopDeviceActionWorkItem
;
39 BOOLEAN IopDeviceActionInProgress
;
40 KSPIN_LOCK IopDeviceActionLock
;
42 typedef struct _DEVICE_ACTION_DATA
44 LIST_ENTRY RequestListEntry
;
45 PDEVICE_OBJECT DeviceObject
;
46 DEVICE_RELATION_TYPE Type
;
47 } DEVICE_ACTION_DATA
, *PDEVICE_ACTION_DATA
;
49 /* FUNCTIONS *****************************************************************/
52 IopCreateDeviceKeyPath(IN PCUNICODE_STRING RegistryPath
,
53 IN ULONG CreateOptions
,
57 IopCancelPrepareDeviceForRemoval(PDEVICE_OBJECT DeviceObject
);
60 IopPrepareDeviceForRemoval(PDEVICE_OBJECT DeviceObject
, BOOLEAN Force
);
63 IopGetDeviceObjectFromDeviceInstance(PUNICODE_STRING DeviceInstance
);
67 IopGetDeviceNode(PDEVICE_OBJECT DeviceObject
)
69 return ((PEXTENDED_DEVOBJ_EXTENSION
)DeviceObject
->DeviceObjectExtension
)->DeviceNode
;
73 IopFixupDeviceId(PWCHAR String
)
75 SIZE_T Length
= wcslen(String
), i
;
77 for (i
= 0; i
< Length
; i
++)
79 if (String
[i
] == L
'\\')
86 IopInstallCriticalDevice(PDEVICE_NODE DeviceNode
)
89 HANDLE CriticalDeviceKey
, InstanceKey
;
90 OBJECT_ATTRIBUTES ObjectAttributes
;
91 UNICODE_STRING CriticalDeviceKeyU
= RTL_CONSTANT_STRING(L
"\\Registry\\Machine\\System\\CurrentControlSet\\Control\\CriticalDeviceDatabase");
92 UNICODE_STRING CompatibleIdU
= RTL_CONSTANT_STRING(L
"CompatibleIDs");
93 UNICODE_STRING HardwareIdU
= RTL_CONSTANT_STRING(L
"HardwareID");
94 UNICODE_STRING ServiceU
= RTL_CONSTANT_STRING(L
"Service");
95 UNICODE_STRING ClassGuidU
= RTL_CONSTANT_STRING(L
"ClassGUID");
96 PKEY_VALUE_PARTIAL_INFORMATION PartialInfo
;
97 ULONG HidLength
= 0, CidLength
= 0, BufferLength
;
98 PWCHAR IdBuffer
, OriginalIdBuffer
;
100 /* Open the device instance key */
101 Status
= IopCreateDeviceKeyPath(&DeviceNode
->InstancePath
, REG_OPTION_NON_VOLATILE
, &InstanceKey
);
102 if (Status
!= STATUS_SUCCESS
)
105 Status
= ZwQueryValueKey(InstanceKey
,
107 KeyValuePartialInformation
,
111 if (Status
!= STATUS_BUFFER_OVERFLOW
&& Status
!= STATUS_BUFFER_TOO_SMALL
)
113 ZwClose(InstanceKey
);
117 Status
= ZwQueryValueKey(InstanceKey
,
119 KeyValuePartialInformation
,
123 if (Status
!= STATUS_BUFFER_OVERFLOW
&& Status
!= STATUS_BUFFER_TOO_SMALL
)
128 BufferLength
= HidLength
+ CidLength
;
129 BufferLength
-= (((CidLength
!= 0) ? 2 : 1) * FIELD_OFFSET(KEY_VALUE_PARTIAL_INFORMATION
, Data
));
131 /* Allocate a buffer to hold data from both */
132 OriginalIdBuffer
= IdBuffer
= ExAllocatePool(PagedPool
, BufferLength
);
135 ZwClose(InstanceKey
);
139 /* Compute the buffer size */
140 if (HidLength
> CidLength
)
141 BufferLength
= HidLength
;
143 BufferLength
= CidLength
;
145 PartialInfo
= ExAllocatePool(PagedPool
, BufferLength
);
148 ZwClose(InstanceKey
);
149 ExFreePool(OriginalIdBuffer
);
153 Status
= ZwQueryValueKey(InstanceKey
,
155 KeyValuePartialInformation
,
159 if (Status
!= STATUS_SUCCESS
)
161 ExFreePool(PartialInfo
);
162 ExFreePool(OriginalIdBuffer
);
163 ZwClose(InstanceKey
);
167 /* Copy in HID info first (without 2nd terminating NULL if CID is present) */
168 HidLength
= PartialInfo
->DataLength
- ((CidLength
!= 0) ? sizeof(WCHAR
) : 0);
169 RtlCopyMemory(IdBuffer
, PartialInfo
->Data
, HidLength
);
173 Status
= ZwQueryValueKey(InstanceKey
,
175 KeyValuePartialInformation
,
179 if (Status
!= STATUS_SUCCESS
)
181 ExFreePool(PartialInfo
);
182 ExFreePool(OriginalIdBuffer
);
183 ZwClose(InstanceKey
);
188 CidLength
= PartialInfo
->DataLength
;
189 RtlCopyMemory(((PUCHAR
)IdBuffer
) + HidLength
, PartialInfo
->Data
, CidLength
);
192 /* Free our temp buffer */
193 ExFreePool(PartialInfo
);
195 InitializeObjectAttributes(&ObjectAttributes
,
197 OBJ_KERNEL_HANDLE
| OBJ_CASE_INSENSITIVE
,
200 Status
= ZwOpenKey(&CriticalDeviceKey
,
201 KEY_ENUMERATE_SUB_KEYS
,
203 if (!NT_SUCCESS(Status
))
205 /* The critical device database doesn't exist because
206 * we're probably in 1st stage setup, but it's ok */
207 ExFreePool(OriginalIdBuffer
);
208 ZwClose(InstanceKey
);
214 USHORT StringLength
= (USHORT
)wcslen(IdBuffer
) + 1, Index
;
216 IopFixupDeviceId(IdBuffer
);
218 /* Look through all subkeys for a match */
219 for (Index
= 0; TRUE
; Index
++)
222 PKEY_BASIC_INFORMATION BasicInfo
;
224 Status
= ZwEnumerateKey(CriticalDeviceKey
,
230 if (Status
== STATUS_NO_MORE_ENTRIES
)
232 else if (Status
== STATUS_BUFFER_OVERFLOW
|| Status
== STATUS_BUFFER_TOO_SMALL
)
234 UNICODE_STRING ChildIdNameU
, RegKeyNameU
;
236 BasicInfo
= ExAllocatePool(PagedPool
, NeededLength
);
240 ExFreePool(OriginalIdBuffer
);
241 ZwClose(CriticalDeviceKey
);
242 ZwClose(InstanceKey
);
246 Status
= ZwEnumerateKey(CriticalDeviceKey
,
252 if (Status
!= STATUS_SUCCESS
)
254 /* This shouldn't happen */
255 ExFreePool(BasicInfo
);
259 ChildIdNameU
.Buffer
= IdBuffer
;
260 ChildIdNameU
.MaximumLength
= ChildIdNameU
.Length
= (StringLength
- 1) * sizeof(WCHAR
);
261 RegKeyNameU
.Buffer
= BasicInfo
->Name
;
262 RegKeyNameU
.MaximumLength
= RegKeyNameU
.Length
= (USHORT
)BasicInfo
->NameLength
;
264 if (RtlEqualUnicodeString(&ChildIdNameU
, &RegKeyNameU
, TRUE
))
266 HANDLE ChildKeyHandle
;
268 InitializeObjectAttributes(&ObjectAttributes
,
270 OBJ_KERNEL_HANDLE
| OBJ_CASE_INSENSITIVE
,
274 Status
= ZwOpenKey(&ChildKeyHandle
,
277 if (Status
!= STATUS_SUCCESS
)
279 ExFreePool(BasicInfo
);
283 /* Check if there's already a driver installed */
284 Status
= ZwQueryValueKey(InstanceKey
,
286 KeyValuePartialInformation
,
290 if (Status
== STATUS_BUFFER_OVERFLOW
|| Status
== STATUS_BUFFER_TOO_SMALL
)
292 ExFreePool(BasicInfo
);
296 Status
= ZwQueryValueKey(ChildKeyHandle
,
298 KeyValuePartialInformation
,
302 if (Status
!= STATUS_BUFFER_OVERFLOW
&& Status
!= STATUS_BUFFER_TOO_SMALL
)
304 ExFreePool(BasicInfo
);
308 PartialInfo
= ExAllocatePool(PagedPool
, NeededLength
);
311 ExFreePool(OriginalIdBuffer
);
312 ExFreePool(BasicInfo
);
313 ZwClose(InstanceKey
);
314 ZwClose(ChildKeyHandle
);
315 ZwClose(CriticalDeviceKey
);
319 /* Read ClassGUID entry in the CDDB */
320 Status
= ZwQueryValueKey(ChildKeyHandle
,
322 KeyValuePartialInformation
,
326 if (Status
!= STATUS_SUCCESS
)
328 ExFreePool(BasicInfo
);
332 /* Write it to the ENUM key */
333 Status
= ZwSetValueKey(InstanceKey
,
338 PartialInfo
->DataLength
);
339 if (Status
!= STATUS_SUCCESS
)
341 ExFreePool(BasicInfo
);
342 ExFreePool(PartialInfo
);
343 ZwClose(ChildKeyHandle
);
347 Status
= ZwQueryValueKey(ChildKeyHandle
,
349 KeyValuePartialInformation
,
353 if (Status
== STATUS_BUFFER_OVERFLOW
|| Status
== STATUS_BUFFER_TOO_SMALL
)
355 ExFreePool(PartialInfo
);
356 PartialInfo
= ExAllocatePool(PagedPool
, NeededLength
);
359 ExFreePool(OriginalIdBuffer
);
360 ExFreePool(BasicInfo
);
361 ZwClose(InstanceKey
);
362 ZwClose(ChildKeyHandle
);
363 ZwClose(CriticalDeviceKey
);
367 /* Read the service entry from the CDDB */
368 Status
= ZwQueryValueKey(ChildKeyHandle
,
370 KeyValuePartialInformation
,
374 if (Status
!= STATUS_SUCCESS
)
376 ExFreePool(BasicInfo
);
377 ExFreePool(PartialInfo
);
378 ZwClose(ChildKeyHandle
);
382 /* Write it to the ENUM key */
383 Status
= ZwSetValueKey(InstanceKey
,
388 PartialInfo
->DataLength
);
389 if (Status
!= STATUS_SUCCESS
)
391 ExFreePool(BasicInfo
);
392 ExFreePool(PartialInfo
);
393 ZwClose(ChildKeyHandle
);
397 DPRINT("Installed service '%S' for critical device '%wZ'\n", PartialInfo
->Data
, &ChildIdNameU
);
401 DPRINT1("Installed NULL service for critical device '%wZ'\n", &ChildIdNameU
);
404 ExFreePool(OriginalIdBuffer
);
405 ExFreePool(PartialInfo
);
406 ExFreePool(BasicInfo
);
407 ZwClose(InstanceKey
);
408 ZwClose(ChildKeyHandle
);
409 ZwClose(CriticalDeviceKey
);
415 ExFreePool(BasicInfo
);
419 /* Umm, not sure what happened here */
424 /* Advance to the next ID */
425 IdBuffer
+= StringLength
;
428 ExFreePool(OriginalIdBuffer
);
429 ZwClose(InstanceKey
);
430 ZwClose(CriticalDeviceKey
);
435 IopInitializeDevice(PDEVICE_NODE DeviceNode
,
436 PDRIVER_OBJECT DriverObject
)
443 /* Special case for bus driven devices */
444 DeviceNode
->Flags
|= DNF_ADDED
;
445 return STATUS_SUCCESS
;
448 if (!DriverObject
->DriverExtension
->AddDevice
)
450 DeviceNode
->Flags
|= DNF_LEGACY_DRIVER
;
453 if (DeviceNode
->Flags
& DNF_LEGACY_DRIVER
)
455 DeviceNode
->Flags
|= (DNF_ADDED
| DNF_STARTED
);
456 return STATUS_SUCCESS
;
459 /* This is a Plug and Play driver */
460 DPRINT("Plug and Play driver found\n");
461 ASSERT(DeviceNode
->PhysicalDeviceObject
);
463 DPRINT("Calling %wZ->AddDevice(%wZ)\n",
464 &DriverObject
->DriverName
,
465 &DeviceNode
->InstancePath
);
466 Status
= DriverObject
->DriverExtension
->AddDevice(
467 DriverObject
, DeviceNode
->PhysicalDeviceObject
);
468 if (!NT_SUCCESS(Status
))
470 DPRINT1("%wZ->AddDevice(%wZ) failed with status 0x%x\n",
471 &DriverObject
->DriverName
,
472 &DeviceNode
->InstancePath
,
474 IopDeviceNodeSetFlag(DeviceNode
, DNF_DISABLED
);
475 DeviceNode
->Problem
= CM_PROB_FAILED_ADD
;
479 Fdo
= IoGetAttachedDeviceReference(DeviceNode
->PhysicalDeviceObject
);
481 /* Check if we have a ACPI device (needed for power management) */
482 if (Fdo
->DeviceType
== FILE_DEVICE_ACPI
)
484 static BOOLEAN SystemPowerDeviceNodeCreated
= FALSE
;
486 /* There can be only one system power device */
487 if (!SystemPowerDeviceNodeCreated
)
489 PopSystemPowerDeviceNode
= DeviceNode
;
490 ObReferenceObject(PopSystemPowerDeviceNode
->PhysicalDeviceObject
);
491 SystemPowerDeviceNodeCreated
= TRUE
;
495 ObDereferenceObject(Fdo
);
497 IopDeviceNodeSetFlag(DeviceNode
, DNF_ADDED
);
499 return STATUS_SUCCESS
;
505 IopSendEject(IN PDEVICE_OBJECT DeviceObject
)
507 IO_STACK_LOCATION Stack
;
510 RtlZeroMemory(&Stack
, sizeof(IO_STACK_LOCATION
));
511 Stack
.MajorFunction
= IRP_MJ_PNP
;
512 Stack
.MinorFunction
= IRP_MN_EJECT
;
514 return IopSynchronousCall(DeviceObject
, &Stack
, &Dummy
);
520 IopSendSurpriseRemoval(IN PDEVICE_OBJECT DeviceObject
)
522 IO_STACK_LOCATION Stack
;
525 RtlZeroMemory(&Stack
, sizeof(IO_STACK_LOCATION
));
526 Stack
.MajorFunction
= IRP_MJ_PNP
;
527 Stack
.MinorFunction
= IRP_MN_SURPRISE_REMOVAL
;
529 /* Drivers should never fail a IRP_MN_SURPRISE_REMOVAL request */
530 IopSynchronousCall(DeviceObject
, &Stack
, &Dummy
);
536 IopQueryRemoveDevice(IN PDEVICE_OBJECT DeviceObject
)
538 PDEVICE_NODE DeviceNode
= IopGetDeviceNode(DeviceObject
);
539 IO_STACK_LOCATION Stack
;
545 IopQueueTargetDeviceEvent(&GUID_DEVICE_REMOVE_PENDING
,
546 &DeviceNode
->InstancePath
);
548 RtlZeroMemory(&Stack
, sizeof(IO_STACK_LOCATION
));
549 Stack
.MajorFunction
= IRP_MJ_PNP
;
550 Stack
.MinorFunction
= IRP_MN_QUERY_REMOVE_DEVICE
;
552 Status
= IopSynchronousCall(DeviceObject
, &Stack
, &Dummy
);
554 IopNotifyPlugPlayNotification(DeviceObject
,
555 EventCategoryTargetDeviceChange
,
556 &GUID_TARGET_DEVICE_QUERY_REMOVE
,
560 if (!NT_SUCCESS(Status
))
562 DPRINT1("Removal vetoed by %wZ\n", &DeviceNode
->InstancePath
);
563 IopQueueTargetDeviceEvent(&GUID_DEVICE_REMOVAL_VETOED
,
564 &DeviceNode
->InstancePath
);
573 IopQueryStopDevice(IN PDEVICE_OBJECT DeviceObject
)
575 IO_STACK_LOCATION Stack
;
578 RtlZeroMemory(&Stack
, sizeof(IO_STACK_LOCATION
));
579 Stack
.MajorFunction
= IRP_MJ_PNP
;
580 Stack
.MinorFunction
= IRP_MN_QUERY_STOP_DEVICE
;
582 return IopSynchronousCall(DeviceObject
, &Stack
, &Dummy
);
588 IopSendRemoveDevice(IN PDEVICE_OBJECT DeviceObject
)
590 IO_STACK_LOCATION Stack
;
592 PDEVICE_NODE DeviceNode
= IopGetDeviceNode(DeviceObject
);
594 /* Drop all our state for this device in case it isn't really going away */
595 DeviceNode
->Flags
&= DNF_ENUMERATED
| DNF_PROCESSED
;
597 RtlZeroMemory(&Stack
, sizeof(IO_STACK_LOCATION
));
598 Stack
.MajorFunction
= IRP_MJ_PNP
;
599 Stack
.MinorFunction
= IRP_MN_REMOVE_DEVICE
;
601 /* Drivers should never fail a IRP_MN_REMOVE_DEVICE request */
602 IopSynchronousCall(DeviceObject
, &Stack
, &Dummy
);
604 IopNotifyPlugPlayNotification(DeviceObject
,
605 EventCategoryTargetDeviceChange
,
606 &GUID_TARGET_DEVICE_REMOVE_COMPLETE
,
609 ObDereferenceObject(DeviceObject
);
615 IopCancelRemoveDevice(IN PDEVICE_OBJECT DeviceObject
)
617 IO_STACK_LOCATION Stack
;
620 RtlZeroMemory(&Stack
, sizeof(IO_STACK_LOCATION
));
621 Stack
.MajorFunction
= IRP_MJ_PNP
;
622 Stack
.MinorFunction
= IRP_MN_CANCEL_REMOVE_DEVICE
;
624 /* Drivers should never fail a IRP_MN_CANCEL_REMOVE_DEVICE request */
625 IopSynchronousCall(DeviceObject
, &Stack
, &Dummy
);
627 IopNotifyPlugPlayNotification(DeviceObject
,
628 EventCategoryTargetDeviceChange
,
629 &GUID_TARGET_DEVICE_REMOVE_CANCELLED
,
637 IopSendStopDevice(IN PDEVICE_OBJECT DeviceObject
)
639 IO_STACK_LOCATION Stack
;
642 RtlZeroMemory(&Stack
, sizeof(IO_STACK_LOCATION
));
643 Stack
.MajorFunction
= IRP_MJ_PNP
;
644 Stack
.MinorFunction
= IRP_MN_STOP_DEVICE
;
646 /* Drivers should never fail a IRP_MN_STOP_DEVICE request */
647 IopSynchronousCall(DeviceObject
, &Stack
, &Dummy
);
652 IopStartDevice2(IN PDEVICE_OBJECT DeviceObject
)
654 IO_STACK_LOCATION Stack
;
655 PDEVICE_NODE DeviceNode
;
658 DEVICE_CAPABILITIES DeviceCapabilities
;
660 /* Get the device node */
661 DeviceNode
= IopGetDeviceNode(DeviceObject
);
663 ASSERT(!(DeviceNode
->Flags
& DNF_DISABLED
));
665 /* Build the I/O stack location */
666 RtlZeroMemory(&Stack
, sizeof(IO_STACK_LOCATION
));
667 Stack
.MajorFunction
= IRP_MJ_PNP
;
668 Stack
.MinorFunction
= IRP_MN_START_DEVICE
;
670 Stack
.Parameters
.StartDevice
.AllocatedResources
=
671 DeviceNode
->ResourceList
;
672 Stack
.Parameters
.StartDevice
.AllocatedResourcesTranslated
=
673 DeviceNode
->ResourceListTranslated
;
676 Status
= IopSynchronousCall(DeviceObject
, &Stack
, &Dummy
);
677 if (!NT_SUCCESS(Status
))
679 /* Send an IRP_MN_REMOVE_DEVICE request */
680 IopRemoveDevice(DeviceNode
);
682 /* Set the appropriate flag */
683 DeviceNode
->Flags
|= DNF_START_FAILED
;
684 DeviceNode
->Problem
= CM_PROB_FAILED_START
;
686 DPRINT1("Warning: PnP Start failed (%wZ) [Status: 0x%x]\n", &DeviceNode
->InstancePath
, Status
);
690 DPRINT("Sending IRP_MN_QUERY_CAPABILITIES to device stack (after start)\n");
692 Status
= IopQueryDeviceCapabilities(DeviceNode
, &DeviceCapabilities
);
693 if (!NT_SUCCESS(Status
))
695 DPRINT("IopInitiatePnpIrp() failed (Status 0x%08lx)\n", Status
);
698 /* Invalidate device state so IRP_MN_QUERY_PNP_DEVICE_STATE is sent */
699 IoInvalidateDeviceState(DeviceObject
);
701 /* Otherwise, mark us as started */
702 DeviceNode
->Flags
|= DNF_STARTED
;
703 DeviceNode
->Flags
&= ~DNF_STOPPED
;
705 /* We now need enumeration */
706 DeviceNode
->Flags
|= DNF_NEED_ENUMERATION_ONLY
;
711 IopStartAndEnumerateDevice(IN PDEVICE_NODE DeviceNode
)
713 PDEVICE_OBJECT DeviceObject
;
718 ASSERT((DeviceNode
->Flags
& DNF_ADDED
));
719 ASSERT((DeviceNode
->Flags
& (DNF_RESOURCE_ASSIGNED
|
720 DNF_RESOURCE_REPORTED
|
721 DNF_NO_RESOURCE_REQUIRED
)));
723 /* Get the device object */
724 DeviceObject
= DeviceNode
->PhysicalDeviceObject
;
726 /* Check if we're not started yet */
727 if (!(DeviceNode
->Flags
& DNF_STARTED
))
730 IopStartDevice2(DeviceObject
);
733 /* Do we need to query IDs? This happens in the case of manual reporting */
735 if (DeviceNode
->Flags
& DNF_NEED_QUERY_IDS
)
737 DPRINT1("Warning: Device node has DNF_NEED_QUERY_IDS\n");
738 /* And that case shouldn't happen yet */
743 /* Make sure we're started, and check if we need enumeration */
744 if ((DeviceNode
->Flags
& DNF_STARTED
) &&
745 (DeviceNode
->Flags
& DNF_NEED_ENUMERATION_ONLY
))
748 IoSynchronousInvalidateDeviceRelations(DeviceObject
, BusRelations
);
749 Status
= STATUS_SUCCESS
;
754 Status
= STATUS_SUCCESS
;
763 PDEVICE_NODE DeviceNode
)
767 DPRINT("Stopping device: %wZ\n", &DeviceNode
->InstancePath
);
769 Status
= IopQueryStopDevice(DeviceNode
->PhysicalDeviceObject
);
770 if (NT_SUCCESS(Status
))
772 IopSendStopDevice(DeviceNode
->PhysicalDeviceObject
);
774 DeviceNode
->Flags
&= ~(DNF_STARTED
| DNF_START_REQUEST_PENDING
);
775 DeviceNode
->Flags
|= DNF_STOPPED
;
777 return STATUS_SUCCESS
;
785 PDEVICE_NODE DeviceNode
)
788 HANDLE InstanceHandle
= NULL
, ControlHandle
= NULL
;
789 UNICODE_STRING KeyName
, ValueString
;
790 OBJECT_ATTRIBUTES ObjectAttributes
;
792 if (DeviceNode
->Flags
& DNF_DISABLED
)
793 return STATUS_SUCCESS
;
795 Status
= IopAssignDeviceResources(DeviceNode
);
796 if (!NT_SUCCESS(Status
))
800 IopStartAndEnumerateDevice(DeviceNode
);
802 /* FIX: Should be done in new device instance code */
803 Status
= IopCreateDeviceKeyPath(&DeviceNode
->InstancePath
, REG_OPTION_NON_VOLATILE
, &InstanceHandle
);
804 if (!NT_SUCCESS(Status
))
807 /* FIX: Should be done in IoXxxPrepareDriverLoading */
809 RtlInitUnicodeString(&KeyName
, L
"Control");
810 InitializeObjectAttributes(&ObjectAttributes
,
812 OBJ_CASE_INSENSITIVE
| OBJ_KERNEL_HANDLE
,
815 Status
= ZwCreateKey(&ControlHandle
, KEY_SET_VALUE
, &ObjectAttributes
, 0, NULL
, REG_OPTION_VOLATILE
, NULL
);
816 if (!NT_SUCCESS(Status
))
819 RtlInitUnicodeString(&KeyName
, L
"ActiveService");
820 ValueString
= DeviceNode
->ServiceName
;
821 if (!ValueString
.Buffer
)
822 RtlInitUnicodeString(&ValueString
, L
"");
823 Status
= ZwSetValueKey(ControlHandle
, &KeyName
, 0, REG_SZ
, ValueString
.Buffer
, ValueString
.Length
+ sizeof(UNICODE_NULL
));
827 if (ControlHandle
!= NULL
)
828 ZwClose(ControlHandle
);
830 if (InstanceHandle
!= NULL
)
831 ZwClose(InstanceHandle
);
838 IopQueryDeviceCapabilities(PDEVICE_NODE DeviceNode
,
839 PDEVICE_CAPABILITIES DeviceCaps
)
841 IO_STATUS_BLOCK StatusBlock
;
842 IO_STACK_LOCATION Stack
;
845 UNICODE_STRING ValueName
;
847 /* Set up the Header */
848 RtlZeroMemory(DeviceCaps
, sizeof(DEVICE_CAPABILITIES
));
849 DeviceCaps
->Size
= sizeof(DEVICE_CAPABILITIES
);
850 DeviceCaps
->Version
= 1;
851 DeviceCaps
->Address
= -1;
852 DeviceCaps
->UINumber
= -1;
854 /* Set up the Stack */
855 RtlZeroMemory(&Stack
, sizeof(IO_STACK_LOCATION
));
856 Stack
.Parameters
.DeviceCapabilities
.Capabilities
= DeviceCaps
;
859 Status
= IopInitiatePnpIrp(DeviceNode
->PhysicalDeviceObject
,
861 IRP_MN_QUERY_CAPABILITIES
,
863 if (!NT_SUCCESS(Status
))
865 if (Status
!= STATUS_NOT_SUPPORTED
)
867 DPRINT1("IRP_MN_QUERY_CAPABILITIES failed with status 0x%lx\n", Status
);
872 DeviceNode
->CapabilityFlags
= *(PULONG
)((ULONG_PTR
)&DeviceCaps
->Version
+ sizeof(DeviceCaps
->Version
));
874 if (DeviceCaps
->NoDisplayInUI
)
875 DeviceNode
->UserFlags
|= DNUF_DONT_SHOW_IN_UI
;
877 DeviceNode
->UserFlags
&= ~DNUF_DONT_SHOW_IN_UI
;
879 Status
= IopCreateDeviceKeyPath(&DeviceNode
->InstancePath
, REG_OPTION_NON_VOLATILE
, &InstanceKey
);
880 if (NT_SUCCESS(Status
))
882 /* Set 'Capabilities' value */
883 RtlInitUnicodeString(&ValueName
, L
"Capabilities");
884 Status
= ZwSetValueKey(InstanceKey
,
888 &DeviceNode
->CapabilityFlags
,
891 /* Set 'UINumber' value */
892 if (DeviceCaps
->UINumber
!= MAXULONG
)
894 RtlInitUnicodeString(&ValueName
, L
"UINumber");
895 Status
= ZwSetValueKey(InstanceKey
,
899 &DeviceCaps
->UINumber
,
903 ZwClose(InstanceKey
);
912 IopDeviceActionWorker(
915 PLIST_ENTRY ListEntry
;
916 PDEVICE_ACTION_DATA Data
;
919 KeAcquireSpinLock(&IopDeviceActionLock
, &OldIrql
);
920 while (!IsListEmpty(&IopDeviceActionRequestList
))
922 ListEntry
= RemoveHeadList(&IopDeviceActionRequestList
);
923 KeReleaseSpinLock(&IopDeviceActionLock
, OldIrql
);
924 Data
= CONTAINING_RECORD(ListEntry
,
928 IoSynchronousInvalidateDeviceRelations(Data
->DeviceObject
,
931 ObDereferenceObject(Data
->DeviceObject
);
932 ExFreePoolWithTag(Data
, TAG_IO
);
933 KeAcquireSpinLock(&IopDeviceActionLock
, &OldIrql
);
935 IopDeviceActionInProgress
= FALSE
;
936 KeReleaseSpinLock(&IopDeviceActionLock
, OldIrql
);
940 IopGetSystemPowerDeviceObject(PDEVICE_OBJECT
*DeviceObject
)
944 if (PopSystemPowerDeviceNode
)
946 KeAcquireSpinLock(&IopDeviceTreeLock
, &OldIrql
);
947 *DeviceObject
= PopSystemPowerDeviceNode
->PhysicalDeviceObject
;
948 KeReleaseSpinLock(&IopDeviceTreeLock
, OldIrql
);
950 return STATUS_SUCCESS
;
953 return STATUS_UNSUCCESSFUL
;
958 IopGetBusTypeGuidIndex(LPGUID BusTypeGuid
)
960 USHORT i
= 0, FoundIndex
= 0xFFFF;
964 /* Acquire the lock */
965 ExAcquireFastMutex(&PnpBusTypeGuidList
->Lock
);
967 /* Loop all entries */
968 while (i
< PnpBusTypeGuidList
->GuidCount
)
970 /* Try to find a match */
971 if (RtlCompareMemory(BusTypeGuid
,
972 &PnpBusTypeGuidList
->Guids
[i
],
973 sizeof(GUID
)) == sizeof(GUID
))
982 /* Check if we have to grow the list */
983 if (PnpBusTypeGuidList
->GuidCount
)
985 /* Calculate the new size */
986 NewSize
= sizeof(IO_BUS_TYPE_GUID_LIST
) +
987 (sizeof(GUID
) * PnpBusTypeGuidList
->GuidCount
);
989 /* Allocate the new copy */
990 NewList
= ExAllocatePool(PagedPool
, NewSize
);
994 ExFreePool(PnpBusTypeGuidList
);
998 /* Now copy them, decrease the size too */
999 NewSize
-= sizeof(GUID
);
1000 RtlCopyMemory(NewList
, PnpBusTypeGuidList
, NewSize
);
1002 /* Free the old list */
1003 ExFreePool(PnpBusTypeGuidList
);
1005 /* Use the new buffer */
1006 PnpBusTypeGuidList
= NewList
;
1009 /* Copy the new GUID */
1010 RtlCopyMemory(&PnpBusTypeGuidList
->Guids
[PnpBusTypeGuidList
->GuidCount
],
1014 /* The new entry is the index */
1015 FoundIndex
= (USHORT
)PnpBusTypeGuidList
->GuidCount
;
1016 PnpBusTypeGuidList
->GuidCount
++;
1019 ExReleaseFastMutex(&PnpBusTypeGuidList
->Lock
);
1025 * Creates a device node
1028 * ParentNode = Pointer to parent device node
1029 * PhysicalDeviceObject = Pointer to PDO for device object. Pass NULL
1030 * to have the root device node create one
1031 * (eg. for legacy drivers)
1032 * DeviceNode = Pointer to storage for created device node
1038 IopCreateDeviceNode(PDEVICE_NODE ParentNode
,
1039 PDEVICE_OBJECT PhysicalDeviceObject
,
1040 PUNICODE_STRING ServiceName
,
1041 PDEVICE_NODE
*DeviceNode
)
1046 UNICODE_STRING FullServiceName
;
1047 UNICODE_STRING LegacyPrefix
= RTL_CONSTANT_STRING(L
"LEGACY_");
1048 UNICODE_STRING UnknownDeviceName
= RTL_CONSTANT_STRING(L
"UNKNOWN");
1049 UNICODE_STRING KeyName
, ClassName
;
1050 PUNICODE_STRING ServiceName1
;
1052 UNICODE_STRING ClassGUID
;
1053 HANDLE InstanceHandle
;
1055 DPRINT("ParentNode 0x%p PhysicalDeviceObject 0x%p ServiceName %wZ\n",
1056 ParentNode
, PhysicalDeviceObject
, ServiceName
);
1058 Node
= ExAllocatePoolWithTag(NonPagedPool
, sizeof(DEVICE_NODE
), TAG_IO_DEVNODE
);
1061 return STATUS_INSUFFICIENT_RESOURCES
;
1064 RtlZeroMemory(Node
, sizeof(DEVICE_NODE
));
1067 ServiceName1
= &UnknownDeviceName
;
1069 ServiceName1
= ServiceName
;
1071 if (!PhysicalDeviceObject
)
1073 FullServiceName
.MaximumLength
= LegacyPrefix
.Length
+ ServiceName1
->Length
+ sizeof(UNICODE_NULL
);
1074 FullServiceName
.Length
= 0;
1075 FullServiceName
.Buffer
= ExAllocatePool(PagedPool
, FullServiceName
.MaximumLength
);
1076 if (!FullServiceName
.Buffer
)
1078 ExFreePoolWithTag(Node
, TAG_IO_DEVNODE
);
1079 return STATUS_INSUFFICIENT_RESOURCES
;
1082 RtlAppendUnicodeStringToString(&FullServiceName
, &LegacyPrefix
);
1083 RtlAppendUnicodeStringToString(&FullServiceName
, ServiceName1
);
1084 RtlUpcaseUnicodeString(&FullServiceName
, &FullServiceName
, FALSE
);
1086 Status
= PnpRootCreateDevice(&FullServiceName
, NULL
, &PhysicalDeviceObject
, &Node
->InstancePath
);
1087 if (!NT_SUCCESS(Status
))
1089 DPRINT1("PnpRootCreateDevice() failed with status 0x%08X\n", Status
);
1090 ExFreePool(FullServiceName
.Buffer
);
1091 ExFreePoolWithTag(Node
, TAG_IO_DEVNODE
);
1095 /* Create the device key for legacy drivers */
1096 Status
= IopCreateDeviceKeyPath(&Node
->InstancePath
, REG_OPTION_VOLATILE
, &InstanceHandle
);
1097 if (!NT_SUCCESS(Status
))
1099 ExFreePool(FullServiceName
.Buffer
);
1100 ExFreePoolWithTag(Node
, TAG_IO_DEVNODE
);
1104 Node
->ServiceName
.MaximumLength
= ServiceName1
->Length
+ sizeof(UNICODE_NULL
);
1105 Node
->ServiceName
.Length
= 0;
1106 Node
->ServiceName
.Buffer
= ExAllocatePool(PagedPool
, Node
->ServiceName
.MaximumLength
);
1107 if (!Node
->ServiceName
.Buffer
)
1109 ZwClose(InstanceHandle
);
1110 ExFreePool(FullServiceName
.Buffer
);
1111 ExFreePoolWithTag(Node
, TAG_IO_DEVNODE
);
1115 RtlCopyUnicodeString(&Node
->ServiceName
, ServiceName1
);
1119 RtlInitUnicodeString(&KeyName
, L
"Service");
1120 Status
= ZwSetValueKey(InstanceHandle
, &KeyName
, 0, REG_SZ
, ServiceName
->Buffer
, ServiceName
->Length
+ sizeof(UNICODE_NULL
));
1123 if (NT_SUCCESS(Status
))
1125 RtlInitUnicodeString(&KeyName
, L
"Legacy");
1127 Status
= ZwSetValueKey(InstanceHandle
, &KeyName
, 0, REG_DWORD
, &LegacyValue
, sizeof(LegacyValue
));
1129 RtlInitUnicodeString(&KeyName
, L
"ConfigFlags");
1131 ZwSetValueKey(InstanceHandle
, &KeyName
, 0, REG_DWORD
, &LegacyValue
, sizeof(LegacyValue
));
1133 if (NT_SUCCESS(Status
))
1135 RtlInitUnicodeString(&KeyName
, L
"Class");
1136 RtlInitUnicodeString(&ClassName
, L
"LegacyDriver");
1137 Status
= ZwSetValueKey(InstanceHandle
, &KeyName
, 0, REG_SZ
, ClassName
.Buffer
, ClassName
.Length
+ sizeof(UNICODE_NULL
));
1138 if (NT_SUCCESS(Status
))
1140 RtlInitUnicodeString(&KeyName
, L
"ClassGUID");
1141 RtlInitUnicodeString(&ClassGUID
, L
"{8ECC055D-047F-11D1-A537-0000F8753ED1}");
1142 Status
= ZwSetValueKey(InstanceHandle
, &KeyName
, 0, REG_SZ
, ClassGUID
.Buffer
, ClassGUID
.Length
+ sizeof(UNICODE_NULL
));
1143 if (NT_SUCCESS(Status
))
1145 // FIXME: Retrieve the real "description" by looking at the "DisplayName" string
1146 // of the corresponding CurrentControlSet\Services\xxx entry for this driver.
1147 RtlInitUnicodeString(&KeyName
, L
"DeviceDesc");
1148 Status
= ZwSetValueKey(InstanceHandle
, &KeyName
, 0, REG_SZ
, ServiceName1
->Buffer
, ServiceName1
->Length
+ sizeof(UNICODE_NULL
));
1154 ZwClose(InstanceHandle
);
1155 ExFreePool(FullServiceName
.Buffer
);
1157 if (!NT_SUCCESS(Status
))
1159 ExFreePool(Node
->ServiceName
.Buffer
);
1160 ExFreePoolWithTag(Node
, TAG_IO_DEVNODE
);
1164 IopDeviceNodeSetFlag(Node
, DNF_LEGACY_DRIVER
);
1165 IopDeviceNodeSetFlag(Node
, DNF_PROCESSED
);
1166 IopDeviceNodeSetFlag(Node
, DNF_ADDED
);
1167 IopDeviceNodeSetFlag(Node
, DNF_STARTED
);
1170 Node
->PhysicalDeviceObject
= PhysicalDeviceObject
;
1172 ((PEXTENDED_DEVOBJ_EXTENSION
)PhysicalDeviceObject
->DeviceObjectExtension
)->DeviceNode
= Node
;
1176 KeAcquireSpinLock(&IopDeviceTreeLock
, &OldIrql
);
1177 Node
->Parent
= ParentNode
;
1178 Node
->Sibling
= NULL
;
1179 if (ParentNode
->LastChild
== NULL
)
1181 ParentNode
->Child
= Node
;
1182 ParentNode
->LastChild
= Node
;
1186 ParentNode
->LastChild
->Sibling
= Node
;
1187 ParentNode
->LastChild
= Node
;
1189 KeReleaseSpinLock(&IopDeviceTreeLock
, OldIrql
);
1190 Node
->Level
= ParentNode
->Level
+ 1;
1193 PhysicalDeviceObject
->Flags
&= ~DO_DEVICE_INITIALIZING
;
1197 return STATUS_SUCCESS
;
1201 IopFreeDeviceNode(PDEVICE_NODE DeviceNode
)
1204 PDEVICE_NODE PrevSibling
= NULL
;
1206 /* All children must be deleted before a parent is deleted */
1207 ASSERT(!DeviceNode
->Child
);
1208 ASSERT(DeviceNode
->PhysicalDeviceObject
);
1210 KeAcquireSpinLock(&IopDeviceTreeLock
, &OldIrql
);
1212 /* Get previous sibling */
1213 if (DeviceNode
->Parent
&& DeviceNode
->Parent
->Child
!= DeviceNode
)
1215 PrevSibling
= DeviceNode
->Parent
->Child
;
1216 while (PrevSibling
->Sibling
!= DeviceNode
)
1217 PrevSibling
= PrevSibling
->Sibling
;
1220 /* Unlink from parent if it exists */
1221 if (DeviceNode
->Parent
)
1223 if (DeviceNode
->Parent
->LastChild
== DeviceNode
)
1225 DeviceNode
->Parent
->LastChild
= PrevSibling
;
1227 PrevSibling
->Sibling
= NULL
;
1229 if (DeviceNode
->Parent
->Child
== DeviceNode
)
1230 DeviceNode
->Parent
->Child
= DeviceNode
->Sibling
;
1233 /* Unlink from sibling list */
1235 PrevSibling
->Sibling
= DeviceNode
->Sibling
;
1237 KeReleaseSpinLock(&IopDeviceTreeLock
, OldIrql
);
1239 RtlFreeUnicodeString(&DeviceNode
->InstancePath
);
1241 RtlFreeUnicodeString(&DeviceNode
->ServiceName
);
1243 if (DeviceNode
->ResourceList
)
1245 ExFreePool(DeviceNode
->ResourceList
);
1248 if (DeviceNode
->ResourceListTranslated
)
1250 ExFreePool(DeviceNode
->ResourceListTranslated
);
1253 if (DeviceNode
->ResourceRequirements
)
1255 ExFreePool(DeviceNode
->ResourceRequirements
);
1258 if (DeviceNode
->BootResources
)
1260 ExFreePool(DeviceNode
->BootResources
);
1263 ((PEXTENDED_DEVOBJ_EXTENSION
)DeviceNode
->PhysicalDeviceObject
->DeviceObjectExtension
)->DeviceNode
= NULL
;
1264 ExFreePoolWithTag(DeviceNode
, TAG_IO_DEVNODE
);
1266 return STATUS_SUCCESS
;
1271 IopSynchronousCall(IN PDEVICE_OBJECT DeviceObject
,
1272 IN PIO_STACK_LOCATION IoStackLocation
,
1273 OUT PVOID
*Information
)
1276 PIO_STACK_LOCATION IrpStack
;
1277 IO_STATUS_BLOCK IoStatusBlock
;
1280 PDEVICE_OBJECT TopDeviceObject
;
1283 /* Call the top of the device stack */
1284 TopDeviceObject
= IoGetAttachedDeviceReference(DeviceObject
);
1286 /* Allocate an IRP */
1287 Irp
= IoAllocateIrp(TopDeviceObject
->StackSize
, FALSE
);
1288 if (!Irp
) return STATUS_INSUFFICIENT_RESOURCES
;
1290 /* Initialize to failure */
1291 Irp
->IoStatus
.Status
= IoStatusBlock
.Status
= STATUS_NOT_SUPPORTED
;
1292 Irp
->IoStatus
.Information
= IoStatusBlock
.Information
= 0;
1294 /* Special case for IRP_MN_FILTER_RESOURCE_REQUIREMENTS */
1295 if (IoStackLocation
->MinorFunction
== IRP_MN_FILTER_RESOURCE_REQUIREMENTS
)
1297 /* Copy the resource requirements list into the IOSB */
1298 Irp
->IoStatus
.Information
=
1299 IoStatusBlock
.Information
= (ULONG_PTR
)IoStackLocation
->Parameters
.FilterResourceRequirements
.IoResourceRequirementList
;
1302 /* Initialize the event */
1303 KeInitializeEvent(&Event
, SynchronizationEvent
, FALSE
);
1306 Irp
->UserIosb
= &IoStatusBlock
;
1307 Irp
->UserEvent
= &Event
;
1310 Irp
->Tail
.Overlay
.Thread
= PsGetCurrentThread();
1311 IoQueueThreadIrp(Irp
);
1313 /* Copy-in the stack */
1314 IrpStack
= IoGetNextIrpStackLocation(Irp
);
1315 *IrpStack
= *IoStackLocation
;
1317 /* Call the driver */
1318 Status
= IoCallDriver(TopDeviceObject
, Irp
);
1319 if (Status
== STATUS_PENDING
)
1322 KeWaitForSingleObject(&Event
,
1327 Status
= IoStatusBlock
.Status
;
1330 /* Remove the reference */
1331 ObDereferenceObject(TopDeviceObject
);
1333 /* Return the information */
1334 *Information
= (PVOID
)IoStatusBlock
.Information
;
1340 IopInitiatePnpIrp(IN PDEVICE_OBJECT DeviceObject
,
1341 IN OUT PIO_STATUS_BLOCK IoStatusBlock
,
1342 IN UCHAR MinorFunction
,
1343 IN PIO_STACK_LOCATION Stack OPTIONAL
)
1345 IO_STACK_LOCATION IoStackLocation
;
1347 /* Fill out the stack information */
1348 RtlZeroMemory(&IoStackLocation
, sizeof(IO_STACK_LOCATION
));
1349 IoStackLocation
.MajorFunction
= IRP_MJ_PNP
;
1350 IoStackLocation
.MinorFunction
= MinorFunction
;
1354 RtlCopyMemory(&IoStackLocation
.Parameters
,
1356 sizeof(Stack
->Parameters
));
1359 /* Do the PnP call */
1360 IoStatusBlock
->Status
= IopSynchronousCall(DeviceObject
,
1362 (PVOID
)&IoStatusBlock
->Information
);
1363 return IoStatusBlock
->Status
;
1367 IopTraverseDeviceTreeNode(PDEVICETREE_TRAVERSE_CONTEXT Context
)
1369 PDEVICE_NODE ParentDeviceNode
;
1370 PDEVICE_NODE ChildDeviceNode
;
1373 /* Copy context data so we don't overwrite it in subsequent calls to this function */
1374 ParentDeviceNode
= Context
->DeviceNode
;
1376 /* Call the action routine */
1377 Status
= (Context
->Action
)(ParentDeviceNode
, Context
->Context
);
1378 if (!NT_SUCCESS(Status
))
1383 /* Traversal of all children nodes */
1384 for (ChildDeviceNode
= ParentDeviceNode
->Child
;
1385 ChildDeviceNode
!= NULL
;
1386 ChildDeviceNode
= ChildDeviceNode
->Sibling
)
1388 /* Pass the current device node to the action routine */
1389 Context
->DeviceNode
= ChildDeviceNode
;
1391 Status
= IopTraverseDeviceTreeNode(Context
);
1392 if (!NT_SUCCESS(Status
))
1403 IopTraverseDeviceTree(PDEVICETREE_TRAVERSE_CONTEXT Context
)
1407 DPRINT("Context 0x%p\n", Context
);
1409 DPRINT("IopTraverseDeviceTree(DeviceNode 0x%p FirstDeviceNode 0x%p Action %p Context 0x%p)\n",
1410 Context
->DeviceNode
, Context
->FirstDeviceNode
, Context
->Action
, Context
->Context
);
1412 /* Start from the specified device node */
1413 Context
->DeviceNode
= Context
->FirstDeviceNode
;
1415 /* Recursively traverse the device tree */
1416 Status
= IopTraverseDeviceTreeNode(Context
);
1417 if (Status
== STATUS_UNSUCCESSFUL
)
1419 /* The action routine just wanted to terminate the traversal with status
1420 code STATUS_SUCCESS */
1421 Status
= STATUS_SUCCESS
;
1429 * IopCreateDeviceKeyPath
1431 * Creates a registry key
1435 * Name of the key to be created.
1437 * Handle to the newly created key
1440 * This method can create nested trees, so parent of RegistryPath can
1441 * be not existant, and will be created if needed.
1445 IopCreateDeviceKeyPath(IN PCUNICODE_STRING RegistryPath
,
1446 IN ULONG CreateOptions
,
1449 UNICODE_STRING EnumU
= RTL_CONSTANT_STRING(ENUM_ROOT
);
1450 HANDLE hParent
= NULL
, hKey
;
1451 OBJECT_ATTRIBUTES ObjectAttributes
;
1452 UNICODE_STRING KeyName
;
1453 PCWSTR Current
, Last
;
1457 /* Assume failure */
1460 /* Create a volatile device tree in 1st stage so we have a clean slate
1461 * for enumeration using the correct HAL (chosen in 1st stage setup) */
1462 if (ExpInTextModeSetup
) CreateOptions
|= REG_OPTION_VOLATILE
;
1464 /* Open root key for device instances */
1465 Status
= IopOpenRegistryKeyEx(&hParent
, NULL
, &EnumU
, KEY_CREATE_SUB_KEY
);
1466 if (!NT_SUCCESS(Status
))
1468 DPRINT1("ZwOpenKey('%wZ') failed with status 0x%08lx\n", &EnumU
, Status
);
1472 Current
= KeyName
.Buffer
= RegistryPath
->Buffer
;
1473 Last
= &RegistryPath
->Buffer
[RegistryPath
->Length
/ sizeof(WCHAR
)];
1475 /* Go up to the end of the string */
1476 while (Current
<= Last
)
1478 if (Current
!= Last
&& *Current
!= L
'\\')
1480 /* Not the end of the string and not a separator */
1485 /* Prepare relative key name */
1486 Length
= (USHORT
)((ULONG_PTR
)Current
- (ULONG_PTR
)KeyName
.Buffer
);
1487 KeyName
.MaximumLength
= KeyName
.Length
= Length
;
1488 DPRINT("Create '%wZ'\n", &KeyName
);
1491 InitializeObjectAttributes(&ObjectAttributes
,
1493 OBJ_CASE_INSENSITIVE
| OBJ_KERNEL_HANDLE
,
1496 Status
= ZwCreateKey(&hKey
,
1497 Current
== Last
? KEY_ALL_ACCESS
: KEY_CREATE_SUB_KEY
,
1504 /* Close parent key handle, we don't need it anymore */
1508 /* Key opening/creating failed? */
1509 if (!NT_SUCCESS(Status
))
1511 DPRINT1("ZwCreateKey('%wZ') failed with status 0x%08lx\n", &KeyName
, Status
);
1515 /* Check if it is the end of the string */
1516 if (Current
== Last
)
1518 /* Yes, return success */
1520 return STATUS_SUCCESS
;
1523 /* Start with this new parent key */
1526 KeyName
.Buffer
= (PWSTR
)Current
;
1529 return STATUS_UNSUCCESSFUL
;
1533 IopSetDeviceInstanceData(HANDLE InstanceKey
,
1534 PDEVICE_NODE DeviceNode
)
1536 OBJECT_ATTRIBUTES ObjectAttributes
;
1537 UNICODE_STRING KeyName
;
1542 HANDLE ControlHandle
;
1544 DPRINT("IopSetDeviceInstanceData() called\n");
1546 /* Create the 'LogConf' key */
1547 RtlInitUnicodeString(&KeyName
, L
"LogConf");
1548 InitializeObjectAttributes(&ObjectAttributes
,
1550 OBJ_CASE_INSENSITIVE
| OBJ_KERNEL_HANDLE
,
1553 Status
= ZwCreateKey(&LogConfKey
,
1558 REG_OPTION_VOLATILE
,
1560 if (NT_SUCCESS(Status
))
1562 /* Set 'BootConfig' value */
1563 if (DeviceNode
->BootResources
!= NULL
)
1565 ResCount
= DeviceNode
->BootResources
->Count
;
1568 RtlInitUnicodeString(&KeyName
, L
"BootConfig");
1569 Status
= ZwSetValueKey(LogConfKey
,
1573 DeviceNode
->BootResources
,
1574 PnpDetermineResourceListSize(DeviceNode
->BootResources
));
1578 /* Set 'BasicConfigVector' value */
1579 if (DeviceNode
->ResourceRequirements
!= NULL
&&
1580 DeviceNode
->ResourceRequirements
->ListSize
!= 0)
1582 RtlInitUnicodeString(&KeyName
, L
"BasicConfigVector");
1583 Status
= ZwSetValueKey(LogConfKey
,
1586 REG_RESOURCE_REQUIREMENTS_LIST
,
1587 DeviceNode
->ResourceRequirements
,
1588 DeviceNode
->ResourceRequirements
->ListSize
);
1591 ZwClose(LogConfKey
);
1594 /* Set the 'ConfigFlags' value */
1595 RtlInitUnicodeString(&KeyName
, L
"ConfigFlags");
1596 Status
= ZwQueryValueKey(InstanceKey
,
1598 KeyValueBasicInformation
,
1602 if (Status
== STATUS_OBJECT_NAME_NOT_FOUND
)
1604 /* Write the default value */
1605 ULONG DefaultConfigFlags
= 0;
1606 Status
= ZwSetValueKey(InstanceKey
,
1610 &DefaultConfigFlags
,
1611 sizeof(DefaultConfigFlags
));
1614 /* Create the 'Control' key */
1615 RtlInitUnicodeString(&KeyName
, L
"Control");
1616 InitializeObjectAttributes(&ObjectAttributes
,
1618 OBJ_CASE_INSENSITIVE
| OBJ_KERNEL_HANDLE
,
1621 Status
= ZwCreateKey(&ControlHandle
, 0, &ObjectAttributes
, 0, NULL
, REG_OPTION_VOLATILE
, NULL
);
1623 if (NT_SUCCESS(Status
))
1624 ZwClose(ControlHandle
);
1626 DPRINT("IopSetDeviceInstanceData() done\n");
1632 * IopGetParentIdPrefix
1634 * Retrieve (or create) a string which identifies a device.
1638 * Pointer to device node.
1640 * Pointer to the string where is returned the parent node identifier
1643 * If the return code is STATUS_SUCCESS, the ParentIdPrefix string is
1644 * valid and its Buffer field is NULL-terminated. The caller needs to
1645 * to free the string with RtlFreeUnicodeString when it is no longer
1650 IopGetParentIdPrefix(PDEVICE_NODE DeviceNode
,
1651 PUNICODE_STRING ParentIdPrefix
)
1653 const UNICODE_STRING EnumKeyPath
= RTL_CONSTANT_STRING(L
"\\Registry\\Machine\\System\\CurrentControlSet\\Enum\\");
1654 ULONG KeyNameBufferLength
;
1655 PKEY_VALUE_PARTIAL_INFORMATION ParentIdPrefixInformation
= NULL
;
1656 UNICODE_STRING KeyName
= {0, 0, NULL
};
1657 UNICODE_STRING KeyValue
;
1658 UNICODE_STRING ValueName
;
1663 /* HACK: As long as some devices have a NULL device
1664 * instance path, the following test is required :(
1666 if (DeviceNode
->Parent
->InstancePath
.Length
== 0)
1668 DPRINT1("Parent of %wZ has NULL Instance path, please report!\n",
1669 &DeviceNode
->InstancePath
);
1670 return STATUS_UNSUCCESSFUL
;
1673 /* 1. Try to retrieve ParentIdPrefix from registry */
1674 KeyNameBufferLength
= FIELD_OFFSET(KEY_VALUE_PARTIAL_INFORMATION
, Data
[0]) + MAX_PATH
* sizeof(WCHAR
);
1675 ParentIdPrefixInformation
= ExAllocatePoolWithTag(PagedPool
,
1676 KeyNameBufferLength
+ sizeof(UNICODE_NULL
),
1678 if (!ParentIdPrefixInformation
)
1680 return STATUS_INSUFFICIENT_RESOURCES
;
1684 KeyName
.MaximumLength
= EnumKeyPath
.Length
+
1685 DeviceNode
->Parent
->InstancePath
.Length
+
1686 sizeof(UNICODE_NULL
);
1687 KeyName
.Buffer
= ExAllocatePoolWithTag(PagedPool
,
1688 KeyName
.MaximumLength
,
1690 if (!KeyName
.Buffer
)
1692 Status
= STATUS_INSUFFICIENT_RESOURCES
;
1696 RtlCopyUnicodeString(&KeyName
, &EnumKeyPath
);
1697 RtlAppendUnicodeStringToString(&KeyName
, &DeviceNode
->Parent
->InstancePath
);
1699 Status
= IopOpenRegistryKeyEx(&hKey
, NULL
, &KeyName
, KEY_QUERY_VALUE
| KEY_SET_VALUE
);
1700 if (!NT_SUCCESS(Status
))
1704 RtlInitUnicodeString(&ValueName
, L
"ParentIdPrefix");
1705 Status
= ZwQueryValueKey(hKey
,
1707 KeyValuePartialInformation
,
1708 ParentIdPrefixInformation
,
1709 KeyNameBufferLength
,
1710 &KeyNameBufferLength
);
1711 if (NT_SUCCESS(Status
))
1713 if (ParentIdPrefixInformation
->Type
!= REG_SZ
)
1715 Status
= STATUS_UNSUCCESSFUL
;
1719 KeyValue
.MaximumLength
= (USHORT
)ParentIdPrefixInformation
->DataLength
;
1720 KeyValue
.Length
= KeyValue
.MaximumLength
- sizeof(UNICODE_NULL
);
1721 KeyValue
.Buffer
= (PWSTR
)ParentIdPrefixInformation
->Data
;
1722 ASSERT(KeyValue
.Buffer
[KeyValue
.Length
/ sizeof(WCHAR
)] == UNICODE_NULL
);
1726 if (Status
!= STATUS_OBJECT_NAME_NOT_FOUND
)
1728 /* FIXME how do we get here and why is ParentIdPrefixInformation valid? */
1729 KeyValue
.MaximumLength
= (USHORT
)ParentIdPrefixInformation
->DataLength
;
1730 KeyValue
.Length
= KeyValue
.MaximumLength
- sizeof(UNICODE_NULL
);
1731 KeyValue
.Buffer
= (PWSTR
)ParentIdPrefixInformation
->Data
;
1732 ASSERT(KeyValue
.Buffer
[KeyValue
.Length
/ sizeof(WCHAR
)] == UNICODE_NULL
);
1736 /* 2. Create the ParentIdPrefix value */
1737 crc32
= RtlComputeCrc32(0,
1738 (PUCHAR
)DeviceNode
->Parent
->InstancePath
.Buffer
,
1739 DeviceNode
->Parent
->InstancePath
.Length
);
1741 RtlStringCbPrintfW((PWSTR
)ParentIdPrefixInformation
,
1742 KeyNameBufferLength
,
1744 DeviceNode
->Parent
->Level
,
1746 RtlInitUnicodeString(&KeyValue
, (PWSTR
)ParentIdPrefixInformation
);
1748 /* 3. Try to write the ParentIdPrefix to registry */
1749 Status
= ZwSetValueKey(hKey
,
1754 ((ULONG
)wcslen(KeyValue
.Buffer
) + 1) * sizeof(WCHAR
));
1757 if (NT_SUCCESS(Status
))
1759 /* Duplicate the string to return it */
1760 Status
= RtlDuplicateUnicodeString(RTL_DUPLICATE_UNICODE_STRING_NULL_TERMINATE
,
1764 ExFreePoolWithTag(ParentIdPrefixInformation
, TAG_IO
);
1765 RtlFreeUnicodeString(&KeyName
);
1777 _In_ BUS_QUERY_ID_TYPE QueryType
)
1782 ULONG SeparatorsCount
= 0;
1783 PWCHAR PtrPrevChar
= NULL
;
1784 ULONG MaxSeparators
;
1791 case BusQueryDeviceID
:
1792 MaxSeparators
= MAX_SEPARATORS_DEVICEID
;
1795 case BusQueryInstanceID
:
1796 MaxSeparators
= MAX_SEPARATORS_INSTANCEID
;
1800 case BusQueryHardwareIDs
:
1801 case BusQueryCompatibleIDs
:
1802 MaxSeparators
= MAX_SEPARATORS_DEVICEID
;
1807 DPRINT1("IopValidateID: Not handled QueryType - %x\n", QueryType
);
1811 StringEnd
= Id
+ MAX_DEVICE_ID_LEN
;
1813 for (PtrChar
= Id
; PtrChar
< StringEnd
; PtrChar
++)
1817 if (Char
== UNICODE_NULL
)
1819 if (!IsMultiSz
|| (PtrPrevChar
&& PtrChar
== PtrPrevChar
+ 1))
1821 if (MaxSeparators
== SeparatorsCount
|| IsMultiSz
)
1826 DPRINT1("IopValidateID: SeparatorsCount - %lu, MaxSeparators - %lu\n",
1827 SeparatorsCount
, MaxSeparators
);
1831 StringEnd
= PtrChar
+ MAX_DEVICE_ID_LEN
+ 1;
1832 PtrPrevChar
= PtrChar
;
1833 SeparatorsCount
= 0;
1835 else if (Char
< ' ' || Char
> 0x7F || Char
== ',')
1837 DPRINT1("IopValidateID: Invalid character - %04X\n", Char
);
1840 else if (Char
== ' ')
1844 else if (Char
== '\\')
1848 if (SeparatorsCount
> MaxSeparators
)
1850 DPRINT1("IopValidateID: SeparatorsCount - %lu, MaxSeparators - %lu\n",
1851 SeparatorsCount
, MaxSeparators
);
1857 DPRINT1("IopValidateID: Not terminated ID\n");
1865 IopQueryHardwareIds(PDEVICE_NODE DeviceNode
,
1868 IO_STACK_LOCATION Stack
;
1869 IO_STATUS_BLOCK IoStatusBlock
;
1871 UNICODE_STRING ValueName
;
1873 ULONG Length
, TotalLength
;
1876 DPRINT("Sending IRP_MN_QUERY_ID.BusQueryHardwareIDs to device stack\n");
1878 RtlZeroMemory(&Stack
, sizeof(Stack
));
1879 Stack
.Parameters
.QueryId
.IdType
= BusQueryHardwareIDs
;
1880 Status
= IopInitiatePnpIrp(DeviceNode
->PhysicalDeviceObject
,
1884 if (NT_SUCCESS(Status
))
1886 IsValidID
= IopValidateID((PWCHAR
)IoStatusBlock
.Information
, BusQueryHardwareIDs
);
1890 DPRINT1("Invalid HardwareIDs. DeviceNode - %p\n", DeviceNode
);
1895 Ptr
= (PWSTR
)IoStatusBlock
.Information
;
1896 DPRINT("Hardware IDs:\n");
1899 DPRINT(" %S\n", Ptr
);
1900 Length
= (ULONG
)wcslen(Ptr
) + 1;
1903 TotalLength
+= Length
;
1905 DPRINT("TotalLength: %hu\n", TotalLength
);
1908 RtlInitUnicodeString(&ValueName
, L
"HardwareID");
1909 Status
= ZwSetValueKey(InstanceKey
,
1913 (PVOID
)IoStatusBlock
.Information
,
1914 (TotalLength
+ 1) * sizeof(WCHAR
));
1915 if (!NT_SUCCESS(Status
))
1917 DPRINT1("ZwSetValueKey() failed (Status %lx)\n", Status
);
1922 DPRINT("IopInitiatePnpIrp() failed (Status %x)\n", Status
);
1929 IopQueryCompatibleIds(PDEVICE_NODE DeviceNode
,
1932 IO_STACK_LOCATION Stack
;
1933 IO_STATUS_BLOCK IoStatusBlock
;
1935 UNICODE_STRING ValueName
;
1937 ULONG Length
, TotalLength
;
1940 DPRINT("Sending IRP_MN_QUERY_ID.BusQueryCompatibleIDs to device stack\n");
1942 RtlZeroMemory(&Stack
, sizeof(Stack
));
1943 Stack
.Parameters
.QueryId
.IdType
= BusQueryCompatibleIDs
;
1944 Status
= IopInitiatePnpIrp(
1945 DeviceNode
->PhysicalDeviceObject
,
1949 if (NT_SUCCESS(Status
) && IoStatusBlock
.Information
)
1951 IsValidID
= IopValidateID((PWCHAR
)IoStatusBlock
.Information
, BusQueryCompatibleIDs
);
1955 DPRINT1("Invalid CompatibleIDs. DeviceNode - %p\n", DeviceNode
);
1960 Ptr
= (PWSTR
)IoStatusBlock
.Information
;
1961 DPRINT("Compatible IDs:\n");
1964 DPRINT(" %S\n", Ptr
);
1965 Length
= (ULONG
)wcslen(Ptr
) + 1;
1968 TotalLength
+= Length
;
1970 DPRINT("TotalLength: %hu\n", TotalLength
);
1973 RtlInitUnicodeString(&ValueName
, L
"CompatibleIDs");
1974 Status
= ZwSetValueKey(InstanceKey
,
1978 (PVOID
)IoStatusBlock
.Information
,
1979 (TotalLength
+ 1) * sizeof(WCHAR
));
1980 if (!NT_SUCCESS(Status
))
1982 DPRINT1("ZwSetValueKey() failed (Status %lx) or no Compatible ID returned\n", Status
);
1987 DPRINT("IopInitiatePnpIrp() failed (Status %x)\n", Status
);
1994 IopCreateDeviceInstancePath(
1995 _In_ PDEVICE_NODE DeviceNode
,
1996 _Out_ PUNICODE_STRING InstancePath
)
1998 IO_STATUS_BLOCK IoStatusBlock
;
1999 UNICODE_STRING DeviceId
;
2000 UNICODE_STRING InstanceId
;
2001 IO_STACK_LOCATION Stack
;
2003 UNICODE_STRING ParentIdPrefix
= { 0, 0, NULL
};
2004 DEVICE_CAPABILITIES DeviceCapabilities
;
2007 DPRINT("Sending IRP_MN_QUERY_ID.BusQueryDeviceID to device stack\n");
2009 Stack
.Parameters
.QueryId
.IdType
= BusQueryDeviceID
;
2010 Status
= IopInitiatePnpIrp(DeviceNode
->PhysicalDeviceObject
,
2014 if (!NT_SUCCESS(Status
))
2016 DPRINT1("IopInitiatePnpIrp(BusQueryDeviceID) failed (Status %x)\n", Status
);
2020 IsValidID
= IopValidateID((PWCHAR
)IoStatusBlock
.Information
, BusQueryDeviceID
);
2024 DPRINT1("Invalid DeviceID. DeviceNode - %p\n", DeviceNode
);
2027 /* Save the device id string */
2028 RtlInitUnicodeString(&DeviceId
, (PWSTR
)IoStatusBlock
.Information
);
2030 DPRINT("Sending IRP_MN_QUERY_CAPABILITIES to device stack (after enumeration)\n");
2032 Status
= IopQueryDeviceCapabilities(DeviceNode
, &DeviceCapabilities
);
2033 if (!NT_SUCCESS(Status
))
2035 DPRINT1("IopQueryDeviceCapabilities() failed (Status 0x%08lx)\n", Status
);
2036 RtlFreeUnicodeString(&DeviceId
);
2040 /* This bit is only check after enumeration */
2041 if (DeviceCapabilities
.HardwareDisabled
)
2043 /* FIXME: Cleanup device */
2044 DeviceNode
->Flags
|= DNF_DISABLED
;
2045 RtlFreeUnicodeString(&DeviceId
);
2046 return STATUS_PLUGPLAY_NO_DEVICE
;
2050 DeviceNode
->Flags
&= ~DNF_DISABLED
;
2053 if (!DeviceCapabilities
.UniqueID
)
2055 /* Device has not a unique ID. We need to prepend parent bus unique identifier */
2056 DPRINT("Instance ID is not unique\n");
2057 Status
= IopGetParentIdPrefix(DeviceNode
, &ParentIdPrefix
);
2058 if (!NT_SUCCESS(Status
))
2060 DPRINT1("IopGetParentIdPrefix() failed (Status 0x%08lx)\n", Status
);
2061 RtlFreeUnicodeString(&DeviceId
);
2066 DPRINT("Sending IRP_MN_QUERY_ID.BusQueryInstanceID to device stack\n");
2068 Stack
.Parameters
.QueryId
.IdType
= BusQueryInstanceID
;
2069 Status
= IopInitiatePnpIrp(DeviceNode
->PhysicalDeviceObject
,
2073 if (!NT_SUCCESS(Status
))
2075 DPRINT("IopInitiatePnpIrp(BusQueryInstanceID) failed (Status %lx)\n", Status
);
2076 ASSERT(IoStatusBlock
.Information
== 0);
2079 if (IoStatusBlock
.Information
)
2081 IsValidID
= IopValidateID((PWCHAR
)IoStatusBlock
.Information
, BusQueryInstanceID
);
2085 DPRINT1("Invalid InstanceID. DeviceNode - %p\n", DeviceNode
);
2089 RtlInitUnicodeString(&InstanceId
,
2090 (PWSTR
)IoStatusBlock
.Information
);
2092 InstancePath
->Length
= 0;
2093 InstancePath
->MaximumLength
= DeviceId
.Length
+ sizeof(WCHAR
) +
2094 ParentIdPrefix
.Length
+
2096 sizeof(UNICODE_NULL
);
2097 if (ParentIdPrefix
.Length
&& InstanceId
.Length
)
2099 InstancePath
->MaximumLength
+= sizeof(WCHAR
);
2102 InstancePath
->Buffer
= ExAllocatePoolWithTag(PagedPool
,
2103 InstancePath
->MaximumLength
,
2105 if (!InstancePath
->Buffer
)
2107 RtlFreeUnicodeString(&InstanceId
);
2108 RtlFreeUnicodeString(&ParentIdPrefix
);
2109 RtlFreeUnicodeString(&DeviceId
);
2110 return STATUS_INSUFFICIENT_RESOURCES
;
2113 /* Start with the device id */
2114 RtlCopyUnicodeString(InstancePath
, &DeviceId
);
2115 RtlAppendUnicodeToString(InstancePath
, L
"\\");
2117 /* Add information from parent bus device to InstancePath */
2118 RtlAppendUnicodeStringToString(InstancePath
, &ParentIdPrefix
);
2119 if (ParentIdPrefix
.Length
&& InstanceId
.Length
)
2121 RtlAppendUnicodeToString(InstancePath
, L
"&");
2124 /* Finally, add the id returned by the driver stack */
2125 RtlAppendUnicodeStringToString(InstancePath
, &InstanceId
);
2128 * FIXME: Check for valid characters, if there is invalid characters
2132 RtlFreeUnicodeString(&InstanceId
);
2133 RtlFreeUnicodeString(&DeviceId
);
2134 RtlFreeUnicodeString(&ParentIdPrefix
);
2136 return STATUS_SUCCESS
;
2140 * IopActionInterrogateDeviceStack
2142 * Retrieve information for all (direct) child nodes of a parent node.
2146 * Pointer to device node.
2148 * Pointer to parent node to retrieve child node information for.
2151 * Any errors that occur are logged instead so that all child services have a chance
2152 * of being interrogated.
2156 IopActionInterrogateDeviceStack(PDEVICE_NODE DeviceNode
,
2159 IO_STATUS_BLOCK IoStatusBlock
;
2160 PWSTR DeviceDescription
;
2161 PWSTR LocationInformation
;
2162 PDEVICE_NODE ParentDeviceNode
;
2163 IO_STACK_LOCATION Stack
;
2165 ULONG RequiredLength
;
2167 HANDLE InstanceKey
= NULL
;
2168 UNICODE_STRING ValueName
;
2169 UNICODE_STRING InstancePathU
;
2170 PDEVICE_OBJECT OldDeviceObject
;
2172 DPRINT("IopActionInterrogateDeviceStack(%p, %p)\n", DeviceNode
, Context
);
2173 DPRINT("PDO 0x%p\n", DeviceNode
->PhysicalDeviceObject
);
2175 ParentDeviceNode
= (PDEVICE_NODE
)Context
;
2178 * We are called for the parent too, but we don't need to do special
2179 * handling for this node
2181 if (DeviceNode
== ParentDeviceNode
)
2183 DPRINT("Success\n");
2184 return STATUS_SUCCESS
;
2188 * Make sure this device node is a direct child of the parent device node
2189 * that is given as an argument
2191 if (DeviceNode
->Parent
!= ParentDeviceNode
)
2193 DPRINT("Skipping 2+ level child\n");
2194 return STATUS_SUCCESS
;
2197 /* Skip processing if it was already completed before */
2198 if (DeviceNode
->Flags
& DNF_PROCESSED
)
2201 return STATUS_SUCCESS
;
2205 Status
= ZwQueryDefaultLocale(FALSE
, &LocaleId
);
2206 if (!NT_SUCCESS(Status
))
2208 DPRINT1("ZwQueryDefaultLocale() failed with status 0x%lx\n", Status
);
2213 * FIXME: For critical errors, cleanup and disable device, but always
2214 * return STATUS_SUCCESS.
2217 Status
= IopCreateDeviceInstancePath(DeviceNode
, &InstancePathU
);
2218 if (!NT_SUCCESS(Status
))
2220 if (Status
!= STATUS_PLUGPLAY_NO_DEVICE
)
2222 DPRINT1("IopCreateDeviceInstancePath() failed with status 0x%lx\n", Status
);
2225 /* We have to return success otherwise we abort the traverse operation */
2226 return STATUS_SUCCESS
;
2229 /* Verify that this is not a duplicate */
2230 OldDeviceObject
= IopGetDeviceObjectFromDeviceInstance(&InstancePathU
);
2231 if (OldDeviceObject
!= NULL
)
2233 PDEVICE_NODE OldDeviceNode
= IopGetDeviceNode(OldDeviceObject
);
2235 DPRINT1("Duplicate device instance '%wZ'\n", &InstancePathU
);
2236 DPRINT1("Current instance parent: '%wZ'\n", &DeviceNode
->Parent
->InstancePath
);
2237 DPRINT1("Old instance parent: '%wZ'\n", &OldDeviceNode
->Parent
->InstancePath
);
2239 KeBugCheckEx(PNP_DETECTED_FATAL_ERROR
,
2241 (ULONG_PTR
)DeviceNode
->PhysicalDeviceObject
,
2242 (ULONG_PTR
)OldDeviceObject
,
2246 DeviceNode
->InstancePath
= InstancePathU
;
2248 DPRINT("InstancePath is %S\n", DeviceNode
->InstancePath
.Buffer
);
2251 * Create registry key for the instance id, if it doesn't exist yet
2253 Status
= IopCreateDeviceKeyPath(&DeviceNode
->InstancePath
, REG_OPTION_NON_VOLATILE
, &InstanceKey
);
2254 if (!NT_SUCCESS(Status
))
2256 DPRINT1("Failed to create the instance key! (Status %lx)\n", Status
);
2258 /* We have to return success otherwise we abort the traverse operation */
2259 return STATUS_SUCCESS
;
2262 IopQueryHardwareIds(DeviceNode
, InstanceKey
);
2264 IopQueryCompatibleIds(DeviceNode
, InstanceKey
);
2266 DPRINT("Sending IRP_MN_QUERY_DEVICE_TEXT.DeviceTextDescription to device stack\n");
2268 Stack
.Parameters
.QueryDeviceText
.DeviceTextType
= DeviceTextDescription
;
2269 Stack
.Parameters
.QueryDeviceText
.LocaleId
= LocaleId
;
2270 Status
= IopInitiatePnpIrp(DeviceNode
->PhysicalDeviceObject
,
2272 IRP_MN_QUERY_DEVICE_TEXT
,
2274 DeviceDescription
= NT_SUCCESS(Status
) ? (PWSTR
)IoStatusBlock
.Information
2276 /* This key is mandatory, so even if the Irp fails, we still write it */
2277 RtlInitUnicodeString(&ValueName
, L
"DeviceDesc");
2278 if (ZwQueryValueKey(InstanceKey
, &ValueName
, KeyValueBasicInformation
, NULL
, 0, &RequiredLength
) == STATUS_OBJECT_NAME_NOT_FOUND
)
2280 if (DeviceDescription
&&
2281 *DeviceDescription
!= UNICODE_NULL
)
2283 /* This key is overriden when a driver is installed. Don't write the
2284 * new description if another one already exists */
2285 Status
= ZwSetValueKey(InstanceKey
,
2290 ((ULONG
)wcslen(DeviceDescription
) + 1) * sizeof(WCHAR
));
2294 UNICODE_STRING DeviceDesc
= RTL_CONSTANT_STRING(L
"Unknown device");
2295 DPRINT("Driver didn't return DeviceDesc (Status 0x%08lx), so place unknown device there\n", Status
);
2297 Status
= ZwSetValueKey(InstanceKey
,
2302 DeviceDesc
.MaximumLength
);
2303 if (!NT_SUCCESS(Status
))
2305 DPRINT1("ZwSetValueKey() failed (Status 0x%lx)\n", Status
);
2311 if (DeviceDescription
)
2313 ExFreePoolWithTag(DeviceDescription
, 0);
2316 DPRINT("Sending IRP_MN_QUERY_DEVICE_TEXT.DeviceTextLocation to device stack\n");
2318 Stack
.Parameters
.QueryDeviceText
.DeviceTextType
= DeviceTextLocationInformation
;
2319 Stack
.Parameters
.QueryDeviceText
.LocaleId
= LocaleId
;
2320 Status
= IopInitiatePnpIrp(DeviceNode
->PhysicalDeviceObject
,
2322 IRP_MN_QUERY_DEVICE_TEXT
,
2324 if (NT_SUCCESS(Status
) && IoStatusBlock
.Information
)
2326 LocationInformation
= (PWSTR
)IoStatusBlock
.Information
;
2327 DPRINT("LocationInformation: %S\n", LocationInformation
);
2328 RtlInitUnicodeString(&ValueName
, L
"LocationInformation");
2329 Status
= ZwSetValueKey(InstanceKey
,
2333 LocationInformation
,
2334 ((ULONG
)wcslen(LocationInformation
) + 1) * sizeof(WCHAR
));
2335 if (!NT_SUCCESS(Status
))
2337 DPRINT1("ZwSetValueKey() failed (Status %lx)\n", Status
);
2340 ExFreePoolWithTag(LocationInformation
, 0);
2344 DPRINT("IopInitiatePnpIrp() failed (Status %x) or IoStatusBlock.Information=NULL\n", Status
);
2347 DPRINT("Sending IRP_MN_QUERY_BUS_INFORMATION to device stack\n");
2349 Status
= IopInitiatePnpIrp(DeviceNode
->PhysicalDeviceObject
,
2351 IRP_MN_QUERY_BUS_INFORMATION
,
2353 if (NT_SUCCESS(Status
) && IoStatusBlock
.Information
)
2355 PPNP_BUS_INFORMATION BusInformation
= (PPNP_BUS_INFORMATION
)IoStatusBlock
.Information
;
2357 DeviceNode
->ChildBusNumber
= BusInformation
->BusNumber
;
2358 DeviceNode
->ChildInterfaceType
= BusInformation
->LegacyBusType
;
2359 DeviceNode
->ChildBusTypeIndex
= IopGetBusTypeGuidIndex(&BusInformation
->BusTypeGuid
);
2360 ExFreePoolWithTag(BusInformation
, 0);
2364 DPRINT("IopInitiatePnpIrp() failed (Status %x) or IoStatusBlock.Information=NULL\n", Status
);
2366 DeviceNode
->ChildBusNumber
= 0xFFFFFFF0;
2367 DeviceNode
->ChildInterfaceType
= InterfaceTypeUndefined
;
2368 DeviceNode
->ChildBusTypeIndex
= -1;
2371 DPRINT("Sending IRP_MN_QUERY_RESOURCES to device stack\n");
2373 Status
= IopInitiatePnpIrp(DeviceNode
->PhysicalDeviceObject
,
2375 IRP_MN_QUERY_RESOURCES
,
2377 if (NT_SUCCESS(Status
) && IoStatusBlock
.Information
)
2379 DeviceNode
->BootResources
= (PCM_RESOURCE_LIST
)IoStatusBlock
.Information
;
2380 IopDeviceNodeSetFlag(DeviceNode
, DNF_HAS_BOOT_CONFIG
);
2384 DPRINT("IopInitiatePnpIrp() failed (Status %x) or IoStatusBlock.Information=NULL\n", Status
);
2385 DeviceNode
->BootResources
= NULL
;
2388 DPRINT("Sending IRP_MN_QUERY_RESOURCE_REQUIREMENTS to device stack\n");
2390 Status
= IopInitiatePnpIrp(DeviceNode
->PhysicalDeviceObject
,
2392 IRP_MN_QUERY_RESOURCE_REQUIREMENTS
,
2394 if (NT_SUCCESS(Status
))
2396 DeviceNode
->ResourceRequirements
= (PIO_RESOURCE_REQUIREMENTS_LIST
)IoStatusBlock
.Information
;
2400 DPRINT("IopInitiatePnpIrp() failed (Status %08lx)\n", Status
);
2401 DeviceNode
->ResourceRequirements
= NULL
;
2404 if (InstanceKey
!= NULL
)
2406 IopSetDeviceInstanceData(InstanceKey
, DeviceNode
);
2409 ZwClose(InstanceKey
);
2411 IopDeviceNodeSetFlag(DeviceNode
, DNF_PROCESSED
);
2413 if (!IopDeviceNodeHasFlag(DeviceNode
, DNF_LEGACY_DRIVER
))
2415 /* Report the device to the user-mode pnp manager */
2416 IopQueueTargetDeviceEvent(&GUID_DEVICE_ENUMERATED
,
2417 &DeviceNode
->InstancePath
);
2420 return STATUS_SUCCESS
;
2425 IopHandleDeviceRemoval(
2426 IN PDEVICE_NODE DeviceNode
,
2427 IN PDEVICE_RELATIONS DeviceRelations
)
2429 PDEVICE_NODE Child
= DeviceNode
->Child
, NextChild
;
2433 if (DeviceNode
== IopRootDeviceNode
)
2436 while (Child
!= NULL
)
2438 NextChild
= Child
->Sibling
;
2441 for (i
= 0; DeviceRelations
&& i
< DeviceRelations
->Count
; i
++)
2443 if (IopGetDeviceNode(DeviceRelations
->Objects
[i
]) == Child
)
2450 if (!Found
&& !(Child
->Flags
& DNF_WILL_BE_REMOVED
))
2452 /* Send removal IRPs to all of its children */
2453 IopPrepareDeviceForRemoval(Child
->PhysicalDeviceObject
, TRUE
);
2455 /* Send the surprise removal IRP */
2456 IopSendSurpriseRemoval(Child
->PhysicalDeviceObject
);
2458 /* Tell the user-mode PnP manager that a device was removed */
2459 IopQueueTargetDeviceEvent(&GUID_DEVICE_SURPRISE_REMOVAL
,
2460 &Child
->InstancePath
);
2462 /* Send the remove device IRP */
2463 IopSendRemoveDevice(Child
->PhysicalDeviceObject
);
2472 IN PDEVICE_OBJECT DeviceObject
)
2474 PDEVICE_NODE DeviceNode
= IopGetDeviceNode(DeviceObject
);
2475 DEVICETREE_TRAVERSE_CONTEXT Context
;
2476 PDEVICE_RELATIONS DeviceRelations
;
2477 PDEVICE_OBJECT ChildDeviceObject
;
2478 IO_STATUS_BLOCK IoStatusBlock
;
2479 PDEVICE_NODE ChildDeviceNode
;
2480 IO_STACK_LOCATION Stack
;
2484 DPRINT("DeviceObject 0x%p\n", DeviceObject
);
2486 if (DeviceNode
->Flags
& DNF_NEED_ENUMERATION_ONLY
)
2488 DeviceNode
->Flags
&= ~DNF_NEED_ENUMERATION_ONLY
;
2490 DPRINT("Sending GUID_DEVICE_ARRIVAL\n");
2491 IopQueueTargetDeviceEvent(&GUID_DEVICE_ARRIVAL
,
2492 &DeviceNode
->InstancePath
);
2495 DPRINT("Sending IRP_MN_QUERY_DEVICE_RELATIONS to device stack\n");
2497 Stack
.Parameters
.QueryDeviceRelations
.Type
= BusRelations
;
2499 Status
= IopInitiatePnpIrp(
2502 IRP_MN_QUERY_DEVICE_RELATIONS
,
2504 if (!NT_SUCCESS(Status
) || Status
== STATUS_PENDING
)
2506 DPRINT("IopInitiatePnpIrp() failed with status 0x%08lx\n", Status
);
2510 DeviceRelations
= (PDEVICE_RELATIONS
)IoStatusBlock
.Information
;
2513 * Send removal IRPs for devices that have disappeared
2514 * NOTE: This code handles the case where no relations are specified
2516 IopHandleDeviceRemoval(DeviceNode
, DeviceRelations
);
2518 /* Now we bail if nothing was returned */
2519 if (!DeviceRelations
)
2521 /* We're all done */
2522 DPRINT("No PDOs\n");
2523 return STATUS_SUCCESS
;
2526 DPRINT("Got %u PDOs\n", DeviceRelations
->Count
);
2529 * Create device nodes for all discovered devices
2531 for (i
= 0; i
< DeviceRelations
->Count
; i
++)
2533 ChildDeviceObject
= DeviceRelations
->Objects
[i
];
2534 ASSERT((ChildDeviceObject
->Flags
& DO_DEVICE_INITIALIZING
) == 0);
2536 ChildDeviceNode
= IopGetDeviceNode(ChildDeviceObject
);
2537 if (!ChildDeviceNode
)
2539 /* One doesn't exist, create it */
2540 Status
= IopCreateDeviceNode(
2545 if (NT_SUCCESS(Status
))
2547 /* Mark the node as enumerated */
2548 ChildDeviceNode
->Flags
|= DNF_ENUMERATED
;
2550 /* Mark the DO as bus enumerated */
2551 ChildDeviceObject
->Flags
|= DO_BUS_ENUMERATED_DEVICE
;
2555 /* Ignore this DO */
2556 DPRINT1("IopCreateDeviceNode() failed with status 0x%08x. Skipping PDO %u\n", Status
, i
);
2557 ObDereferenceObject(ChildDeviceObject
);
2562 /* Mark it as enumerated */
2563 ChildDeviceNode
->Flags
|= DNF_ENUMERATED
;
2564 ObDereferenceObject(ChildDeviceObject
);
2567 ExFreePool(DeviceRelations
);
2570 * Retrieve information about all discovered children from the bus driver
2572 IopInitDeviceTreeTraverseContext(
2575 IopActionInterrogateDeviceStack
,
2578 Status
= IopTraverseDeviceTree(&Context
);
2579 if (!NT_SUCCESS(Status
))
2581 DPRINT("IopTraverseDeviceTree() failed with status 0x%08lx\n", Status
);
2586 * Retrieve configuration from the registry for discovered children
2588 IopInitDeviceTreeTraverseContext(
2591 IopActionConfigureChildServices
,
2594 Status
= IopTraverseDeviceTree(&Context
);
2595 if (!NT_SUCCESS(Status
))
2597 DPRINT("IopTraverseDeviceTree() failed with status 0x%08lx\n", Status
);
2602 * Initialize services for discovered children.
2604 Status
= IopInitializePnpServices(DeviceNode
);
2605 if (!NT_SUCCESS(Status
))
2607 DPRINT("IopInitializePnpServices() failed with status 0x%08lx\n", Status
);
2611 DPRINT("IopEnumerateDevice() finished\n");
2612 return STATUS_SUCCESS
;
2617 * IopActionConfigureChildServices
2619 * Retrieve configuration for all (direct) child nodes of a parent node.
2623 * Pointer to device node.
2625 * Pointer to parent node to retrieve child node configuration for.
2628 * Any errors that occur are logged instead so that all child services have a chance of beeing
2633 IopActionConfigureChildServices(PDEVICE_NODE DeviceNode
,
2636 RTL_QUERY_REGISTRY_TABLE QueryTable
[3];
2637 PDEVICE_NODE ParentDeviceNode
;
2638 PUNICODE_STRING Service
;
2639 UNICODE_STRING ClassGUID
;
2641 DEVICE_CAPABILITIES DeviceCaps
;
2643 DPRINT("IopActionConfigureChildServices(%p, %p)\n", DeviceNode
, Context
);
2645 ParentDeviceNode
= (PDEVICE_NODE
)Context
;
2648 * We are called for the parent too, but we don't need to do special
2649 * handling for this node
2651 if (DeviceNode
== ParentDeviceNode
)
2653 DPRINT("Success\n");
2654 return STATUS_SUCCESS
;
2658 * Make sure this device node is a direct child of the parent device node
2659 * that is given as an argument
2662 if (DeviceNode
->Parent
!= ParentDeviceNode
)
2664 DPRINT("Skipping 2+ level child\n");
2665 return STATUS_SUCCESS
;
2668 if (!(DeviceNode
->Flags
& DNF_PROCESSED
))
2670 DPRINT1("Child not ready to be configured\n");
2671 return STATUS_SUCCESS
;
2674 if (!(DeviceNode
->Flags
& (DNF_DISABLED
| DNF_STARTED
| DNF_ADDED
)))
2676 WCHAR RegKeyBuffer
[MAX_PATH
];
2677 UNICODE_STRING RegKey
;
2679 /* Install the service for this if it's in the CDDB */
2680 IopInstallCriticalDevice(DeviceNode
);
2683 RegKey
.MaximumLength
= sizeof(RegKeyBuffer
);
2684 RegKey
.Buffer
= RegKeyBuffer
;
2687 * Retrieve configuration from Enum key
2690 Service
= &DeviceNode
->ServiceName
;
2692 RtlZeroMemory(QueryTable
, sizeof(QueryTable
));
2693 RtlInitUnicodeString(Service
, NULL
);
2694 RtlInitUnicodeString(&ClassGUID
, NULL
);
2696 QueryTable
[0].Name
= L
"Service";
2697 QueryTable
[0].Flags
= RTL_QUERY_REGISTRY_DIRECT
;
2698 QueryTable
[0].EntryContext
= Service
;
2700 QueryTable
[1].Name
= L
"ClassGUID";
2701 QueryTable
[1].Flags
= RTL_QUERY_REGISTRY_DIRECT
;
2702 QueryTable
[1].EntryContext
= &ClassGUID
;
2703 QueryTable
[1].DefaultType
= REG_SZ
;
2704 QueryTable
[1].DefaultData
= L
"";
2705 QueryTable
[1].DefaultLength
= 0;
2707 RtlAppendUnicodeToString(&RegKey
, L
"\\Registry\\Machine\\System\\CurrentControlSet\\Enum\\");
2708 RtlAppendUnicodeStringToString(&RegKey
, &DeviceNode
->InstancePath
);
2710 Status
= RtlQueryRegistryValues(RTL_REGISTRY_ABSOLUTE
,
2711 RegKey
.Buffer
, QueryTable
, NULL
, NULL
);
2713 if (!NT_SUCCESS(Status
))
2715 /* FIXME: Log the error */
2716 DPRINT("Could not retrieve configuration for device %wZ (Status 0x%08x)\n",
2717 &DeviceNode
->InstancePath
, Status
);
2718 IopDeviceNodeSetFlag(DeviceNode
, DNF_DISABLED
);
2719 return STATUS_SUCCESS
;
2722 if (Service
->Buffer
== NULL
)
2724 if (NT_SUCCESS(IopQueryDeviceCapabilities(DeviceNode
, &DeviceCaps
)) &&
2725 DeviceCaps
.RawDeviceOK
)
2727 DPRINT("%wZ is using parent bus driver (%wZ)\n", &DeviceNode
->InstancePath
, &ParentDeviceNode
->ServiceName
);
2728 RtlInitEmptyUnicodeString(&DeviceNode
->ServiceName
, NULL
, 0);
2730 else if (ClassGUID
.Length
!= 0)
2732 /* Device has a ClassGUID value, but no Service value.
2733 * Suppose it is using the NULL driver, so state the
2734 * device is started */
2735 DPRINT("%wZ is using NULL driver\n", &DeviceNode
->InstancePath
);
2736 IopDeviceNodeSetFlag(DeviceNode
, DNF_STARTED
);
2740 DeviceNode
->Problem
= CM_PROB_FAILED_INSTALL
;
2741 IopDeviceNodeSetFlag(DeviceNode
, DNF_DISABLED
);
2743 return STATUS_SUCCESS
;
2746 DPRINT("Got Service %S\n", Service
->Buffer
);
2749 return STATUS_SUCCESS
;
2753 * IopActionInitChildServices
2755 * Initialize the service for all (direct) child nodes of a parent node
2759 * Pointer to device node.
2761 * Pointer to parent node to initialize child node services for.
2764 * If the driver image for a service is not loaded and initialized
2765 * it is done here too. Any errors that occur are logged instead so
2766 * that all child services have a chance of being initialized.
2770 IopActionInitChildServices(PDEVICE_NODE DeviceNode
,
2773 PDEVICE_NODE ParentDeviceNode
;
2775 BOOLEAN BootDrivers
= !PnpSystemInit
;
2777 DPRINT("IopActionInitChildServices(%p, %p)\n", DeviceNode
, Context
);
2779 ParentDeviceNode
= Context
;
2782 * We are called for the parent too, but we don't need to do special
2783 * handling for this node
2785 if (DeviceNode
== ParentDeviceNode
)
2787 DPRINT("Success\n");
2788 return STATUS_SUCCESS
;
2792 * We don't want to check for a direct child because
2793 * this function is called during boot to reinitialize
2794 * devices with drivers that couldn't load yet due to
2795 * stage 0 limitations (ie can't load from disk yet).
2798 if (!(DeviceNode
->Flags
& DNF_PROCESSED
))
2800 DPRINT1("Child not ready to be added\n");
2801 return STATUS_SUCCESS
;
2804 if (IopDeviceNodeHasFlag(DeviceNode
, DNF_STARTED
) ||
2805 IopDeviceNodeHasFlag(DeviceNode
, DNF_ADDED
) ||
2806 IopDeviceNodeHasFlag(DeviceNode
, DNF_DISABLED
))
2807 return STATUS_SUCCESS
;
2809 if (DeviceNode
->ServiceName
.Buffer
== NULL
)
2811 /* We don't need to worry about loading the driver because we're
2812 * being driven in raw mode so our parent must be loaded to get here */
2813 Status
= IopInitializeDevice(DeviceNode
, NULL
);
2814 if (NT_SUCCESS(Status
))
2816 Status
= IopStartDevice(DeviceNode
);
2817 if (!NT_SUCCESS(Status
))
2819 DPRINT1("IopStartDevice(%wZ) failed with status 0x%08x\n",
2820 &DeviceNode
->InstancePath
, Status
);
2826 PLDR_DATA_TABLE_ENTRY ModuleObject
;
2827 PDRIVER_OBJECT DriverObject
;
2829 KeEnterCriticalRegion();
2830 ExAcquireResourceExclusiveLite(&IopDriverLoadResource
, TRUE
);
2831 /* Get existing DriverObject pointer (in case the driver has
2832 already been loaded and initialized) */
2833 Status
= IopGetDriverObject(
2835 &DeviceNode
->ServiceName
,
2838 if (!NT_SUCCESS(Status
))
2840 /* Driver is not initialized, try to load it */
2841 Status
= IopLoadServiceModule(&DeviceNode
->ServiceName
, &ModuleObject
);
2843 if (NT_SUCCESS(Status
) || Status
== STATUS_IMAGE_ALREADY_LOADED
)
2845 /* Initialize the driver */
2846 Status
= IopInitializeDriverModule(DeviceNode
, ModuleObject
,
2847 &DeviceNode
->ServiceName
, FALSE
, &DriverObject
);
2848 if (!NT_SUCCESS(Status
)) DeviceNode
->Problem
= CM_PROB_FAILED_DRIVER_ENTRY
;
2850 else if (Status
== STATUS_DRIVER_UNABLE_TO_LOAD
)
2852 DPRINT1("Service '%wZ' is disabled\n", &DeviceNode
->ServiceName
);
2853 DeviceNode
->Problem
= CM_PROB_DISABLED_SERVICE
;
2857 DPRINT("IopLoadServiceModule(%wZ) failed with status 0x%08x\n",
2858 &DeviceNode
->ServiceName
, Status
);
2859 if (!BootDrivers
) DeviceNode
->Problem
= CM_PROB_DRIVER_FAILED_LOAD
;
2862 ExReleaseResourceLite(&IopDriverLoadResource
);
2863 KeLeaveCriticalRegion();
2865 /* Driver is loaded and initialized at this point */
2866 if (NT_SUCCESS(Status
))
2868 /* Initialize the device, including all filters */
2869 Status
= PipCallDriverAddDevice(DeviceNode
, FALSE
, DriverObject
);
2871 /* Remove the extra reference */
2872 ObDereferenceObject(DriverObject
);
2877 * Don't disable when trying to load only boot drivers
2881 IopDeviceNodeSetFlag(DeviceNode
, DNF_DISABLED
);
2886 return STATUS_SUCCESS
;
2890 * IopInitializePnpServices
2892 * Initialize services for discovered children
2896 * Top device node to start initializing services.
2902 IopInitializePnpServices(IN PDEVICE_NODE DeviceNode
)
2904 DEVICETREE_TRAVERSE_CONTEXT Context
;
2906 DPRINT("IopInitializePnpServices(%p)\n", DeviceNode
);
2908 IopInitDeviceTreeTraverseContext(
2911 IopActionInitChildServices
,
2914 return IopTraverseDeviceTree(&Context
);
2917 static NTSTATUS INIT_FUNCTION
2918 IopEnumerateDetectedDevices(
2920 IN PUNICODE_STRING RelativePath OPTIONAL
,
2922 IN BOOLEAN EnumerateSubKeys
,
2923 IN PCM_FULL_RESOURCE_DESCRIPTOR ParentBootResources
,
2924 IN ULONG ParentBootResourcesLength
)
2926 UNICODE_STRING IdentifierU
= RTL_CONSTANT_STRING(L
"Identifier");
2927 UNICODE_STRING HardwareIDU
= RTL_CONSTANT_STRING(L
"HardwareID");
2928 UNICODE_STRING ConfigurationDataU
= RTL_CONSTANT_STRING(L
"Configuration Data");
2929 UNICODE_STRING BootConfigU
= RTL_CONSTANT_STRING(L
"BootConfig");
2930 UNICODE_STRING LogConfU
= RTL_CONSTANT_STRING(L
"LogConf");
2931 OBJECT_ATTRIBUTES ObjectAttributes
;
2932 HANDLE hDevicesKey
= NULL
;
2933 HANDLE hDeviceKey
= NULL
;
2934 HANDLE hLevel1Key
, hLevel2Key
= NULL
, hLogConf
;
2935 UNICODE_STRING Level2NameU
;
2936 WCHAR Level2Name
[5];
2937 ULONG IndexDevice
= 0;
2939 PKEY_BASIC_INFORMATION pDeviceInformation
= NULL
;
2940 ULONG DeviceInfoLength
= sizeof(KEY_BASIC_INFORMATION
) + 50 * sizeof(WCHAR
);
2941 PKEY_VALUE_PARTIAL_INFORMATION pValueInformation
= NULL
;
2942 ULONG ValueInfoLength
= sizeof(KEY_VALUE_PARTIAL_INFORMATION
) + 50 * sizeof(WCHAR
);
2943 UNICODE_STRING DeviceName
, ValueName
;
2945 PCM_FULL_RESOURCE_DESCRIPTOR BootResources
= NULL
;
2946 ULONG BootResourcesLength
;
2949 const UNICODE_STRING IdentifierSerial
= RTL_CONSTANT_STRING(L
"SerialController");
2950 UNICODE_STRING HardwareIdSerial
= RTL_CONSTANT_STRING(L
"*PNP0501\0");
2951 static ULONG DeviceIndexSerial
= 0;
2952 const UNICODE_STRING IdentifierKeyboard
= RTL_CONSTANT_STRING(L
"KeyboardController");
2953 UNICODE_STRING HardwareIdKeyboard
= RTL_CONSTANT_STRING(L
"*PNP0303\0");
2954 static ULONG DeviceIndexKeyboard
= 0;
2955 const UNICODE_STRING IdentifierMouse
= RTL_CONSTANT_STRING(L
"PointerController");
2956 UNICODE_STRING HardwareIdMouse
= RTL_CONSTANT_STRING(L
"*PNP0F13\0");
2957 static ULONG DeviceIndexMouse
= 0;
2958 const UNICODE_STRING IdentifierParallel
= RTL_CONSTANT_STRING(L
"ParallelController");
2959 UNICODE_STRING HardwareIdParallel
= RTL_CONSTANT_STRING(L
"*PNP0400\0");
2960 static ULONG DeviceIndexParallel
= 0;
2961 const UNICODE_STRING IdentifierFloppy
= RTL_CONSTANT_STRING(L
"FloppyDiskPeripheral");
2962 UNICODE_STRING HardwareIdFloppy
= RTL_CONSTANT_STRING(L
"*PNP0700\0");
2963 static ULONG DeviceIndexFloppy
= 0;
2964 UNICODE_STRING HardwareIdKey
;
2965 PUNICODE_STRING pHardwareId
;
2966 ULONG DeviceIndex
= 0;
2967 PUCHAR CmResourceList
;
2972 Status
= IopOpenRegistryKeyEx(&hDevicesKey
, hBaseKey
, RelativePath
, KEY_ENUMERATE_SUB_KEYS
);
2973 if (!NT_SUCCESS(Status
))
2975 DPRINT("ZwOpenKey() failed with status 0x%08lx\n", Status
);
2980 hDevicesKey
= hBaseKey
;
2982 pDeviceInformation
= ExAllocatePool(PagedPool
, DeviceInfoLength
);
2983 if (!pDeviceInformation
)
2985 DPRINT("ExAllocatePool() failed\n");
2986 Status
= STATUS_NO_MEMORY
;
2990 pValueInformation
= ExAllocatePool(PagedPool
, ValueInfoLength
);
2991 if (!pValueInformation
)
2993 DPRINT("ExAllocatePool() failed\n");
2994 Status
= STATUS_NO_MEMORY
;
3000 Status
= ZwEnumerateKey(hDevicesKey
, IndexDevice
, KeyBasicInformation
, pDeviceInformation
, DeviceInfoLength
, &RequiredSize
);
3001 if (Status
== STATUS_NO_MORE_ENTRIES
)
3003 else if (Status
== STATUS_BUFFER_OVERFLOW
|| Status
== STATUS_BUFFER_TOO_SMALL
)
3005 ExFreePool(pDeviceInformation
);
3006 DeviceInfoLength
= RequiredSize
;
3007 pDeviceInformation
= ExAllocatePool(PagedPool
, DeviceInfoLength
);
3008 if (!pDeviceInformation
)
3010 DPRINT("ExAllocatePool() failed\n");
3011 Status
= STATUS_NO_MEMORY
;
3014 Status
= ZwEnumerateKey(hDevicesKey
, IndexDevice
, KeyBasicInformation
, pDeviceInformation
, DeviceInfoLength
, &RequiredSize
);
3016 if (!NT_SUCCESS(Status
))
3018 DPRINT("ZwEnumerateKey() failed with status 0x%08lx\n", Status
);
3023 /* Open device key */
3024 DeviceName
.Length
= DeviceName
.MaximumLength
= (USHORT
)pDeviceInformation
->NameLength
;
3025 DeviceName
.Buffer
= pDeviceInformation
->Name
;
3027 Status
= IopOpenRegistryKeyEx(&hDeviceKey
, hDevicesKey
, &DeviceName
,
3028 KEY_QUERY_VALUE
+ (EnumerateSubKeys
? KEY_ENUMERATE_SUB_KEYS
: 0));
3029 if (!NT_SUCCESS(Status
))
3031 DPRINT("ZwOpenKey() failed with status 0x%08lx\n", Status
);
3035 /* Read boot resources, and add then to parent ones */
3036 Status
= ZwQueryValueKey(hDeviceKey
, &ConfigurationDataU
, KeyValuePartialInformation
, pValueInformation
, ValueInfoLength
, &RequiredSize
);
3037 if (Status
== STATUS_BUFFER_OVERFLOW
|| Status
== STATUS_BUFFER_TOO_SMALL
)
3039 ExFreePool(pValueInformation
);
3040 ValueInfoLength
= RequiredSize
;
3041 pValueInformation
= ExAllocatePool(PagedPool
, ValueInfoLength
);
3042 if (!pValueInformation
)
3044 DPRINT("ExAllocatePool() failed\n");
3045 ZwDeleteKey(hLevel2Key
);
3046 Status
= STATUS_NO_MEMORY
;
3049 Status
= ZwQueryValueKey(hDeviceKey
, &ConfigurationDataU
, KeyValuePartialInformation
, pValueInformation
, ValueInfoLength
, &RequiredSize
);
3051 if (Status
== STATUS_OBJECT_NAME_NOT_FOUND
)
3053 BootResources
= ParentBootResources
;
3054 BootResourcesLength
= ParentBootResourcesLength
;
3056 else if (!NT_SUCCESS(Status
))
3058 DPRINT("ZwQueryValueKey() failed with status 0x%08lx\n", Status
);
3061 else if (pValueInformation
->Type
!= REG_FULL_RESOURCE_DESCRIPTOR
)
3063 DPRINT("Wrong registry type: got 0x%lx, expected 0x%lx\n", pValueInformation
->Type
, REG_FULL_RESOURCE_DESCRIPTOR
);
3068 static const ULONG Header
= FIELD_OFFSET(CM_FULL_RESOURCE_DESCRIPTOR
, PartialResourceList
.PartialDescriptors
);
3070 /* Concatenate current resources and parent ones */
3071 if (ParentBootResourcesLength
== 0)
3072 BootResourcesLength
= pValueInformation
->DataLength
;
3074 BootResourcesLength
= ParentBootResourcesLength
3075 + pValueInformation
->DataLength
3077 BootResources
= ExAllocatePool(PagedPool
, BootResourcesLength
);
3080 DPRINT("ExAllocatePool() failed\n");
3083 if (ParentBootResourcesLength
< sizeof(CM_FULL_RESOURCE_DESCRIPTOR
))
3085 RtlCopyMemory(BootResources
, pValueInformation
->Data
, pValueInformation
->DataLength
);
3087 else if (ParentBootResources
->PartialResourceList
.PartialDescriptors
[ParentBootResources
->PartialResourceList
.Count
- 1].Type
== CmResourceTypeDeviceSpecific
)
3089 RtlCopyMemory(BootResources
, pValueInformation
->Data
, pValueInformation
->DataLength
);
3091 (PVOID
)((ULONG_PTR
)BootResources
+ pValueInformation
->DataLength
),
3092 (PVOID
)((ULONG_PTR
)ParentBootResources
+ Header
),
3093 ParentBootResourcesLength
- Header
);
3094 BootResources
->PartialResourceList
.Count
+= ParentBootResources
->PartialResourceList
.Count
;
3098 RtlCopyMemory(BootResources
, pValueInformation
->Data
, Header
);
3100 (PVOID
)((ULONG_PTR
)BootResources
+ Header
),
3101 (PVOID
)((ULONG_PTR
)ParentBootResources
+ Header
),
3102 ParentBootResourcesLength
- Header
);
3104 (PVOID
)((ULONG_PTR
)BootResources
+ ParentBootResourcesLength
),
3105 pValueInformation
->Data
+ Header
,
3106 pValueInformation
->DataLength
- Header
);
3107 BootResources
->PartialResourceList
.Count
+= ParentBootResources
->PartialResourceList
.Count
;
3111 if (EnumerateSubKeys
)
3116 Status
= ZwEnumerateKey(hDeviceKey
, IndexSubKey
, KeyBasicInformation
, pDeviceInformation
, DeviceInfoLength
, &RequiredSize
);
3117 if (Status
== STATUS_NO_MORE_ENTRIES
)
3119 else if (Status
== STATUS_BUFFER_OVERFLOW
|| Status
== STATUS_BUFFER_TOO_SMALL
)
3121 ExFreePool(pDeviceInformation
);
3122 DeviceInfoLength
= RequiredSize
;
3123 pDeviceInformation
= ExAllocatePool(PagedPool
, DeviceInfoLength
);
3124 if (!pDeviceInformation
)
3126 DPRINT("ExAllocatePool() failed\n");
3127 Status
= STATUS_NO_MEMORY
;
3130 Status
= ZwEnumerateKey(hDeviceKey
, IndexSubKey
, KeyBasicInformation
, pDeviceInformation
, DeviceInfoLength
, &RequiredSize
);
3132 if (!NT_SUCCESS(Status
))
3134 DPRINT("ZwEnumerateKey() failed with status 0x%08lx\n", Status
);
3138 DeviceName
.Length
= DeviceName
.MaximumLength
= (USHORT
)pDeviceInformation
->NameLength
;
3139 DeviceName
.Buffer
= pDeviceInformation
->Name
;
3141 Status
= IopEnumerateDetectedDevices(
3147 BootResourcesLength
);
3148 if (!NT_SUCCESS(Status
))
3153 /* Read identifier */
3154 Status
= ZwQueryValueKey(hDeviceKey
, &IdentifierU
, KeyValuePartialInformation
, pValueInformation
, ValueInfoLength
, &RequiredSize
);
3155 if (Status
== STATUS_BUFFER_OVERFLOW
|| Status
== STATUS_BUFFER_TOO_SMALL
)
3157 ExFreePool(pValueInformation
);
3158 ValueInfoLength
= RequiredSize
;
3159 pValueInformation
= ExAllocatePool(PagedPool
, ValueInfoLength
);
3160 if (!pValueInformation
)
3162 DPRINT("ExAllocatePool() failed\n");
3163 Status
= STATUS_NO_MEMORY
;
3166 Status
= ZwQueryValueKey(hDeviceKey
, &IdentifierU
, KeyValuePartialInformation
, pValueInformation
, ValueInfoLength
, &RequiredSize
);
3168 if (!NT_SUCCESS(Status
))
3170 if (Status
!= STATUS_OBJECT_NAME_NOT_FOUND
)
3172 DPRINT("ZwQueryValueKey() failed with status 0x%08lx\n", Status
);
3175 ValueName
.Length
= ValueName
.MaximumLength
= 0;
3177 else if (pValueInformation
->Type
!= REG_SZ
)
3179 DPRINT("Wrong registry type: got 0x%lx, expected 0x%lx\n", pValueInformation
->Type
, REG_SZ
);
3184 /* Assign hardware id to this device */
3185 ValueName
.Length
= ValueName
.MaximumLength
= (USHORT
)pValueInformation
->DataLength
;
3186 ValueName
.Buffer
= (PWCHAR
)pValueInformation
->Data
;
3187 if (ValueName
.Length
>= sizeof(WCHAR
) && ValueName
.Buffer
[ValueName
.Length
/ sizeof(WCHAR
) - 1] == UNICODE_NULL
)
3188 ValueName
.Length
-= sizeof(WCHAR
);
3191 if (RelativePath
&& RtlCompareUnicodeString(RelativePath
, &IdentifierSerial
, FALSE
) == 0)
3193 pHardwareId
= &HardwareIdSerial
;
3194 DeviceIndex
= DeviceIndexSerial
++;
3196 else if (RelativePath
&& RtlCompareUnicodeString(RelativePath
, &IdentifierKeyboard
, FALSE
) == 0)
3198 pHardwareId
= &HardwareIdKeyboard
;
3199 DeviceIndex
= DeviceIndexKeyboard
++;
3201 else if (RelativePath
&& RtlCompareUnicodeString(RelativePath
, &IdentifierMouse
, FALSE
) == 0)
3203 pHardwareId
= &HardwareIdMouse
;
3204 DeviceIndex
= DeviceIndexMouse
++;
3206 else if (RelativePath
&& RtlCompareUnicodeString(RelativePath
, &IdentifierParallel
, FALSE
) == 0)
3208 pHardwareId
= &HardwareIdParallel
;
3209 DeviceIndex
= DeviceIndexParallel
++;
3211 else if (RelativePath
&& RtlCompareUnicodeString(RelativePath
, &IdentifierFloppy
, FALSE
) == 0)
3213 pHardwareId
= &HardwareIdFloppy
;
3214 DeviceIndex
= DeviceIndexFloppy
++;
3218 /* Unknown key path */
3219 DPRINT("Unknown key path '%wZ'\n", RelativePath
);
3223 /* Prepare hardware id key (hardware id value without final \0) */
3224 HardwareIdKey
= *pHardwareId
;
3225 HardwareIdKey
.Length
-= sizeof(UNICODE_NULL
);
3227 /* Add the detected device to Root key */
3228 InitializeObjectAttributes(&ObjectAttributes
, &HardwareIdKey
, OBJ_KERNEL_HANDLE
, hRootKey
, NULL
);
3229 Status
= ZwCreateKey(
3235 ExpInTextModeSetup
? REG_OPTION_VOLATILE
: 0,
3237 if (!NT_SUCCESS(Status
))
3239 DPRINT("ZwCreateKey() failed with status 0x%08lx\n", Status
);
3242 swprintf(Level2Name
, L
"%04lu", DeviceIndex
);
3243 RtlInitUnicodeString(&Level2NameU
, Level2Name
);
3244 InitializeObjectAttributes(&ObjectAttributes
, &Level2NameU
, OBJ_KERNEL_HANDLE
, hLevel1Key
, NULL
);
3245 Status
= ZwCreateKey(
3247 KEY_SET_VALUE
| KEY_CREATE_SUB_KEY
,
3251 ExpInTextModeSetup
? REG_OPTION_VOLATILE
: 0,
3253 ZwClose(hLevel1Key
);
3254 if (!NT_SUCCESS(Status
))
3256 DPRINT("ZwCreateKey() failed with status 0x%08lx\n", Status
);
3259 DPRINT("Found %wZ #%lu (%wZ)\n", &ValueName
, DeviceIndex
, &HardwareIdKey
);
3260 Status
= ZwSetValueKey(hLevel2Key
, &HardwareIDU
, 0, REG_MULTI_SZ
, pHardwareId
->Buffer
, pHardwareId
->MaximumLength
);
3261 if (!NT_SUCCESS(Status
))
3263 DPRINT("ZwSetValueKey() failed with status 0x%08lx\n", Status
);
3264 ZwDeleteKey(hLevel2Key
);
3267 /* Create 'LogConf' subkey */
3268 InitializeObjectAttributes(&ObjectAttributes
, &LogConfU
, OBJ_KERNEL_HANDLE
, hLevel2Key
, NULL
);
3269 Status
= ZwCreateKey(
3275 REG_OPTION_VOLATILE
,
3277 if (!NT_SUCCESS(Status
))
3279 DPRINT("ZwCreateKey() failed with status 0x%08lx\n", Status
);
3280 ZwDeleteKey(hLevel2Key
);
3283 if (BootResourcesLength
>= sizeof(CM_FULL_RESOURCE_DESCRIPTOR
))
3285 CmResourceList
= ExAllocatePool(PagedPool
, BootResourcesLength
+ sizeof(ULONG
));
3286 if (!CmResourceList
)
3289 ZwDeleteKey(hLevel2Key
);
3293 /* Add the list count (1st member of CM_RESOURCE_LIST) */
3295 RtlCopyMemory(CmResourceList
,
3299 /* Now add the actual list (2nd member of CM_RESOURCE_LIST) */
3300 RtlCopyMemory(CmResourceList
+ sizeof(ULONG
),
3302 BootResourcesLength
);
3304 /* Save boot resources to 'LogConf\BootConfig' */
3305 Status
= ZwSetValueKey(hLogConf
, &BootConfigU
, 0, REG_RESOURCE_LIST
, CmResourceList
, BootResourcesLength
+ sizeof(ULONG
));
3306 if (!NT_SUCCESS(Status
))
3308 DPRINT("ZwSetValueKey() failed with status 0x%08lx\n", Status
);
3310 ZwDeleteKey(hLevel2Key
);
3317 if (BootResources
&& BootResources
!= ParentBootResources
)
3319 ExFreePool(BootResources
);
3320 BootResources
= NULL
;
3324 ZwClose(hLevel2Key
);
3329 ZwClose(hDeviceKey
);
3334 Status
= STATUS_SUCCESS
;
3337 if (hDevicesKey
&& hDevicesKey
!= hBaseKey
)
3338 ZwClose(hDevicesKey
);
3340 ZwClose(hDeviceKey
);
3341 if (pDeviceInformation
)
3342 ExFreePool(pDeviceInformation
);
3343 if (pValueInformation
)
3344 ExFreePool(pValueInformation
);
3348 static BOOLEAN INIT_FUNCTION
3349 IopIsFirmwareMapperDisabled(VOID
)
3351 UNICODE_STRING KeyPathU
= RTL_CONSTANT_STRING(L
"\\Registry\\Machine\\SYSTEM\\CURRENTCONTROLSET\\Control\\Pnp");
3352 UNICODE_STRING KeyNameU
= RTL_CONSTANT_STRING(L
"DisableFirmwareMapper");
3353 OBJECT_ATTRIBUTES ObjectAttributes
;
3355 PKEY_VALUE_PARTIAL_INFORMATION KeyInformation
;
3356 ULONG DesiredLength
, Length
;
3360 InitializeObjectAttributes(&ObjectAttributes
, &KeyPathU
, OBJ_KERNEL_HANDLE
| OBJ_CASE_INSENSITIVE
, NULL
, NULL
);
3361 Status
= ZwOpenKey(&hPnpKey
, KEY_QUERY_VALUE
, &ObjectAttributes
);
3362 if (NT_SUCCESS(Status
))
3364 Status
= ZwQueryValueKey(hPnpKey
,
3366 KeyValuePartialInformation
,
3370 if ((Status
== STATUS_BUFFER_TOO_SMALL
) ||
3371 (Status
== STATUS_BUFFER_OVERFLOW
))
3373 Length
= DesiredLength
;
3374 KeyInformation
= ExAllocatePool(PagedPool
, Length
);
3377 Status
= ZwQueryValueKey(hPnpKey
,
3379 KeyValuePartialInformation
,
3383 if (NT_SUCCESS(Status
) && KeyInformation
->DataLength
== sizeof(ULONG
))
3385 KeyValue
= (ULONG
)(*KeyInformation
->Data
);
3389 DPRINT1("ZwQueryValueKey(%wZ%wZ) failed\n", &KeyPathU
, &KeyNameU
);
3392 ExFreePool(KeyInformation
);
3396 DPRINT1("Failed to allocate memory for registry query\n");
3401 DPRINT1("ZwQueryValueKey(%wZ%wZ) failed with status 0x%08lx\n", &KeyPathU
, &KeyNameU
, Status
);
3408 DPRINT1("ZwOpenKey(%wZ) failed with status 0x%08lx\n", &KeyPathU
, Status
);
3411 DPRINT("Firmware mapper is %s\n", KeyValue
!= 0 ? "disabled" : "enabled");
3413 return (KeyValue
!= 0) ? TRUE
: FALSE
;
3419 IopUpdateRootKey(VOID
)
3421 UNICODE_STRING EnumU
= RTL_CONSTANT_STRING(L
"\\Registry\\Machine\\SYSTEM\\CurrentControlSet\\Enum");
3422 UNICODE_STRING RootPathU
= RTL_CONSTANT_STRING(L
"Root");
3423 UNICODE_STRING MultiKeyPathU
= RTL_CONSTANT_STRING(L
"\\Registry\\Machine\\HARDWARE\\DESCRIPTION\\System\\MultifunctionAdapter");
3424 OBJECT_ATTRIBUTES ObjectAttributes
;
3425 HANDLE hEnum
, hRoot
;
3428 InitializeObjectAttributes(&ObjectAttributes
, &EnumU
, OBJ_KERNEL_HANDLE
| OBJ_CASE_INSENSITIVE
, NULL
, NULL
);
3429 Status
= ZwCreateKey(&hEnum
, KEY_CREATE_SUB_KEY
, &ObjectAttributes
, 0, NULL
, 0, NULL
);
3430 if (!NT_SUCCESS(Status
))
3432 DPRINT1("ZwCreateKey() failed with status 0x%08lx\n", Status
);
3436 InitializeObjectAttributes(&ObjectAttributes
, &RootPathU
, OBJ_KERNEL_HANDLE
| OBJ_CASE_INSENSITIVE
, hEnum
, NULL
);
3437 Status
= ZwCreateKey(&hRoot
, KEY_CREATE_SUB_KEY
, &ObjectAttributes
, 0, NULL
, 0, NULL
);
3439 if (!NT_SUCCESS(Status
))
3441 DPRINT1("ZwOpenKey() failed with status 0x%08lx\n", Status
);
3445 if (!IopIsFirmwareMapperDisabled())
3447 Status
= IopOpenRegistryKeyEx(&hEnum
, NULL
, &MultiKeyPathU
, KEY_ENUMERATE_SUB_KEYS
);
3448 if (!NT_SUCCESS(Status
))
3450 /* Nothing to do, don't return with an error status */
3451 DPRINT("ZwOpenKey() failed with status 0x%08lx\n", Status
);
3453 return STATUS_SUCCESS
;
3455 Status
= IopEnumerateDetectedDevices(
3466 /* Enumeration is disabled */
3467 Status
= STATUS_SUCCESS
;
3477 IopOpenRegistryKeyEx(PHANDLE KeyHandle
,
3479 PUNICODE_STRING Name
,
3480 ACCESS_MASK DesiredAccess
)
3482 OBJECT_ATTRIBUTES ObjectAttributes
;
3489 InitializeObjectAttributes(&ObjectAttributes
,
3491 OBJ_CASE_INSENSITIVE
| OBJ_KERNEL_HANDLE
,
3495 Status
= ZwOpenKey(KeyHandle
, DesiredAccess
, &ObjectAttributes
);
3502 IopCreateRegistryKeyEx(OUT PHANDLE Handle
,
3503 IN HANDLE RootHandle OPTIONAL
,
3504 IN PUNICODE_STRING KeyName
,
3505 IN ACCESS_MASK DesiredAccess
,
3506 IN ULONG CreateOptions
,
3507 OUT PULONG Disposition OPTIONAL
)
3509 OBJECT_ATTRIBUTES ObjectAttributes
;
3510 ULONG KeyDisposition
, RootHandleIndex
= 0, i
= 1, NestedCloseLevel
= 0;
3512 HANDLE HandleArray
[2];
3513 BOOLEAN Recursing
= TRUE
;
3515 UNICODE_STRING KeyString
;
3516 NTSTATUS Status
= STATUS_SUCCESS
;
3519 /* P1 is start, pp is end */
3520 p1
= KeyName
->Buffer
;
3521 pp
= (PVOID
)((ULONG_PTR
)p1
+ KeyName
->Length
);
3523 /* Create the target key */
3524 InitializeObjectAttributes(&ObjectAttributes
,
3526 OBJ_CASE_INSENSITIVE
| OBJ_KERNEL_HANDLE
,
3529 Status
= ZwCreateKey(&HandleArray
[i
],
3537 /* Now we check if this failed */
3538 if ((Status
== STATUS_OBJECT_NAME_NOT_FOUND
) && (RootHandle
))
3540 /* Target key failed, so we'll need to create its parent. Setup array */
3541 HandleArray
[0] = NULL
;
3542 HandleArray
[1] = RootHandle
;
3544 /* Keep recursing for each missing parent */
3547 /* And if we're deep enough, close the last handle */
3548 if (NestedCloseLevel
> 1) ZwClose(HandleArray
[RootHandleIndex
]);
3550 /* We're setup to ping-pong between the two handle array entries */
3551 RootHandleIndex
= i
;
3554 /* Clear the one we're attempting to open now */
3555 HandleArray
[i
] = NULL
;
3557 /* Process the parent key name */
3558 for (p
= p1
; ((p
< pp
) && (*p
!= OBJ_NAME_PATH_SEPARATOR
)); p
++);
3559 Length
= (USHORT
)(p
- p1
) * sizeof(WCHAR
);
3561 /* Is there a parent name? */
3564 /* Build the unicode string for it */
3565 KeyString
.Buffer
= p1
;
3566 KeyString
.Length
= KeyString
.MaximumLength
= Length
;
3568 /* Now try opening the parent */
3569 InitializeObjectAttributes(&ObjectAttributes
,
3571 OBJ_CASE_INSENSITIVE
| OBJ_KERNEL_HANDLE
,
3572 HandleArray
[RootHandleIndex
],
3574 Status
= ZwCreateKey(&HandleArray
[i
],
3581 if (NT_SUCCESS(Status
))
3583 /* It worked, we have one more handle */
3588 /* Parent key creation failed, abandon loop */
3595 /* We don't have a parent name, probably corrupted key name */
3596 Status
= STATUS_INVALID_PARAMETER
;
3601 /* Now see if there's more parents to create */
3603 if ((p
== pp
) || (p1
== pp
))
3605 /* We're done, hopefully successfully, so stop */
3610 /* Outer loop check for handle nesting that requires closing the top handle */
3611 if (NestedCloseLevel
> 1) ZwClose(HandleArray
[RootHandleIndex
]);
3614 /* Check if we broke out of the loop due to success */
3615 if (NT_SUCCESS(Status
))
3617 /* Return the target handle (we closed all the parent ones) and disposition */
3618 *Handle
= HandleArray
[i
];
3619 if (Disposition
) *Disposition
= KeyDisposition
;
3622 /* Return the success state */
3628 IopGetRegistryValue(IN HANDLE Handle
,
3630 OUT PKEY_VALUE_FULL_INFORMATION
*Information
)
3632 UNICODE_STRING ValueString
;
3634 PKEY_VALUE_FULL_INFORMATION FullInformation
;
3638 RtlInitUnicodeString(&ValueString
, ValueName
);
3640 Status
= ZwQueryValueKey(Handle
,
3642 KeyValueFullInformation
,
3646 if ((Status
!= STATUS_BUFFER_OVERFLOW
) &&
3647 (Status
!= STATUS_BUFFER_TOO_SMALL
))
3652 FullInformation
= ExAllocatePool(NonPagedPool
, Size
);
3653 if (!FullInformation
) return STATUS_INSUFFICIENT_RESOURCES
;
3655 Status
= ZwQueryValueKey(Handle
,
3657 KeyValueFullInformation
,
3661 if (!NT_SUCCESS(Status
))
3663 ExFreePool(FullInformation
);
3667 *Information
= FullInformation
;
3668 return STATUS_SUCCESS
;
3671 RTL_GENERIC_COMPARE_RESULTS
3673 PiCompareInstancePath(IN PRTL_AVL_TABLE Table
,
3674 IN PVOID FirstStruct
,
3675 IN PVOID SecondStruct
)
3683 // The allocation function is called by the generic table package whenever
3684 // it needs to allocate memory for the table.
3689 PiAllocateGenericTableEntry(IN PRTL_AVL_TABLE Table
,
3699 PiFreeGenericTableEntry(IN PRTL_AVL_TABLE Table
,
3708 PpInitializeDeviceReferenceTable(VOID
)
3710 /* Setup the guarded mutex and AVL table */
3711 KeInitializeGuardedMutex(&PpDeviceReferenceTableLock
);
3712 RtlInitializeGenericTableAvl(
3713 &PpDeviceReferenceTable
,
3714 (PRTL_AVL_COMPARE_ROUTINE
)PiCompareInstancePath
,
3715 (PRTL_AVL_ALLOCATE_ROUTINE
)PiAllocateGenericTableEntry
,
3716 (PRTL_AVL_FREE_ROUTINE
)PiFreeGenericTableEntry
,
3724 /* Initialize the resource when accessing device registry data */
3725 ExInitializeResourceLite(&PpRegistryDeviceResource
);
3727 /* Setup the device reference AVL table */
3728 PpInitializeDeviceReferenceTable();
3736 /* Check the initialization phase */
3737 switch (ExpInitializationPhase
)
3742 return PiInitPhase0();
3748 //return PiInitPhase1();
3752 /* Don't know any other phase! Bugcheck! */
3753 KeBugCheck(UNEXPECTED_INITIALIZATION_CALL
);
3758 LONG IopNumberDeviceNodes
;
3762 PipAllocateDeviceNode(IN PDEVICE_OBJECT PhysicalDeviceObject
)
3764 PDEVICE_NODE DeviceNode
;
3768 DeviceNode
= ExAllocatePoolWithTag(NonPagedPool
, sizeof(DEVICE_NODE
), TAG_IO_DEVNODE
);
3769 if (!DeviceNode
) return DeviceNode
;
3772 InterlockedIncrement(&IopNumberDeviceNodes
);
3775 RtlZeroMemory(DeviceNode
, sizeof(DEVICE_NODE
));
3776 DeviceNode
->InterfaceType
= InterfaceTypeUndefined
;
3777 DeviceNode
->BusNumber
= -1;
3778 DeviceNode
->ChildInterfaceType
= InterfaceTypeUndefined
;
3779 DeviceNode
->ChildBusNumber
= -1;
3780 DeviceNode
->ChildBusTypeIndex
= -1;
3781 // KeInitializeEvent(&DeviceNode->EnumerationMutex, SynchronizationEvent, TRUE);
3782 InitializeListHead(&DeviceNode
->DeviceArbiterList
);
3783 InitializeListHead(&DeviceNode
->DeviceTranslatorList
);
3784 InitializeListHead(&DeviceNode
->TargetDeviceNotify
);
3785 InitializeListHead(&DeviceNode
->DockInfo
.ListEntry
);
3786 InitializeListHead(&DeviceNode
->PendedSetInterfaceState
);
3788 /* Check if there is a PDO */
3789 if (PhysicalDeviceObject
)
3791 /* Link it and remove the init flag */
3792 DeviceNode
->PhysicalDeviceObject
= PhysicalDeviceObject
;
3793 ((PEXTENDED_DEVOBJ_EXTENSION
)PhysicalDeviceObject
->DeviceObjectExtension
)->DeviceNode
= DeviceNode
;
3794 PhysicalDeviceObject
->Flags
&= ~DO_DEVICE_INITIALIZING
;
3797 /* Return the node */
3801 /* PUBLIC FUNCTIONS **********************************************************/
3805 PnpBusTypeGuidGet(IN USHORT Index
,
3806 IN LPGUID BusTypeGuid
)
3808 NTSTATUS Status
= STATUS_SUCCESS
;
3810 /* Acquire the lock */
3811 ExAcquireFastMutex(&PnpBusTypeGuidList
->Lock
);
3814 if (Index
< PnpBusTypeGuidList
->GuidCount
)
3817 RtlCopyMemory(BusTypeGuid
, &PnpBusTypeGuidList
->Guids
[Index
], sizeof(GUID
));
3822 Status
= STATUS_OBJECT_NAME_NOT_FOUND
;
3825 /* Release lock and return status */
3826 ExReleaseFastMutex(&PnpBusTypeGuidList
->Lock
);
3832 PnpDeviceObjectToDeviceInstance(IN PDEVICE_OBJECT DeviceObject
,
3833 IN PHANDLE DeviceInstanceHandle
,
3834 IN ACCESS_MASK DesiredAccess
)
3838 PDEVICE_NODE DeviceNode
;
3839 UNICODE_STRING KeyName
= RTL_CONSTANT_STRING(L
"\\REGISTRY\\MACHINE\\SYSTEM\\CURRENTCONTROLSET\\ENUM");
3842 /* Open the enum key */
3843 Status
= IopOpenRegistryKeyEx(&KeyHandle
,
3847 if (!NT_SUCCESS(Status
)) return Status
;
3849 /* Make sure we have an instance path */
3850 DeviceNode
= IopGetDeviceNode(DeviceObject
);
3851 if ((DeviceNode
) && (DeviceNode
->InstancePath
.Length
))
3853 /* Get the instance key */
3854 Status
= IopOpenRegistryKeyEx(DeviceInstanceHandle
,
3856 &DeviceNode
->InstancePath
,
3862 Status
= STATUS_INVALID_DEVICE_REQUEST
;
3865 /* Close the handle and return status */
3872 PnpDetermineResourceListSize(IN PCM_RESOURCE_LIST ResourceList
)
3874 ULONG FinalSize
, PartialSize
, EntrySize
, i
, j
;
3875 PCM_FULL_RESOURCE_DESCRIPTOR FullDescriptor
;
3876 PCM_PARTIAL_RESOURCE_DESCRIPTOR PartialDescriptor
;
3878 /* If we don't have one, that's easy */
3879 if (!ResourceList
) return 0;
3881 /* Start with the minimum size possible */
3882 FinalSize
= FIELD_OFFSET(CM_RESOURCE_LIST
, List
);
3884 /* Loop each full descriptor */
3885 FullDescriptor
= ResourceList
->List
;
3886 for (i
= 0; i
< ResourceList
->Count
; i
++)
3888 /* Start with the minimum size possible */
3889 PartialSize
= FIELD_OFFSET(CM_FULL_RESOURCE_DESCRIPTOR
, PartialResourceList
) +
3890 FIELD_OFFSET(CM_PARTIAL_RESOURCE_LIST
, PartialDescriptors
);
3892 /* Loop each partial descriptor */
3893 PartialDescriptor
= FullDescriptor
->PartialResourceList
.PartialDescriptors
;
3894 for (j
= 0; j
< FullDescriptor
->PartialResourceList
.Count
; j
++)
3896 /* Start with the minimum size possible */
3897 EntrySize
= sizeof(CM_PARTIAL_RESOURCE_DESCRIPTOR
);
3899 /* Check if there is extra data */
3900 if (PartialDescriptor
->Type
== CmResourceTypeDeviceSpecific
)
3903 EntrySize
+= PartialDescriptor
->u
.DeviceSpecificData
.DataSize
;
3906 /* The size of partial descriptors is bigger */
3907 PartialSize
+= EntrySize
;
3909 /* Go to the next partial descriptor */
3910 PartialDescriptor
= (PVOID
)((ULONG_PTR
)PartialDescriptor
+ EntrySize
);
3913 /* The size of full descriptors is bigger */
3914 FinalSize
+= PartialSize
;
3916 /* Go to the next full descriptor */
3917 FullDescriptor
= (PVOID
)((ULONG_PTR
)FullDescriptor
+ PartialSize
);
3920 /* Return the final size */
3926 PiGetDeviceRegistryProperty(IN PDEVICE_OBJECT DeviceObject
,
3931 IN PULONG BufferLength
)
3934 HANDLE KeyHandle
, SubHandle
;
3935 UNICODE_STRING KeyString
;
3936 PKEY_VALUE_FULL_INFORMATION KeyValueInfo
= NULL
;
3940 /* Find the instance key */
3941 Status
= PnpDeviceObjectToDeviceInstance(DeviceObject
, &KeyHandle
, KEY_READ
);
3942 if (NT_SUCCESS(Status
))
3944 /* Check for name given by caller */
3948 RtlInitUnicodeString(&KeyString
, KeyName
);
3949 Status
= IopOpenRegistryKeyEx(&SubHandle
,
3953 if (NT_SUCCESS(Status
))
3955 /* And use this handle instead */
3957 KeyHandle
= SubHandle
;
3961 /* Check if sub-key handle succeeded (or no-op if no key name given) */
3962 if (NT_SUCCESS(Status
))
3964 /* Now get the size of the property */
3965 Status
= IopGetRegistryValue(KeyHandle
,
3974 /* Fail if any of the registry operations failed */
3975 if (!NT_SUCCESS(Status
)) return Status
;
3977 /* Check how much data we have to copy */
3978 Length
= KeyValueInfo
->DataLength
;
3979 if (*BufferLength
>= Length
)
3981 /* Check for a match in the value type */
3982 if (KeyValueInfo
->Type
== ValueType
)
3985 RtlCopyMemory(Buffer
,
3986 (PVOID
)((ULONG_PTR
)KeyValueInfo
+
3987 KeyValueInfo
->DataOffset
),
3992 /* Invalid registry property type, fail */
3993 Status
= STATUS_INVALID_PARAMETER_2
;
3998 /* Buffer is too small to hold data */
3999 Status
= STATUS_BUFFER_TOO_SMALL
;
4002 /* Return the required buffer length, free the buffer, and return status */
4003 *BufferLength
= Length
;
4004 ExFreePool(KeyValueInfo
);
4008 #define PIP_RETURN_DATA(x, y) {ReturnLength = x; Data = y; Status = STATUS_SUCCESS; break;}
4009 #define PIP_REGISTRY_DATA(x, y) {ValueName = x; ValueType = y; break;}
4010 #define PIP_UNIMPLEMENTED() {UNIMPLEMENTED_DBGBREAK(); break;}
4017 IoGetDeviceProperty(IN PDEVICE_OBJECT DeviceObject
,
4018 IN DEVICE_REGISTRY_PROPERTY DeviceProperty
,
4019 IN ULONG BufferLength
,
4020 OUT PVOID PropertyBuffer
,
4021 OUT PULONG ResultLength
)
4023 PDEVICE_NODE DeviceNode
= IopGetDeviceNode(DeviceObject
);
4024 DEVICE_CAPABILITIES DeviceCaps
;
4025 ULONG ReturnLength
= 0, Length
= 0, ValueType
;
4026 PWCHAR ValueName
= NULL
, EnumeratorNameEnd
, DeviceInstanceName
;
4028 NTSTATUS Status
= STATUS_BUFFER_TOO_SMALL
;
4030 POBJECT_NAME_INFORMATION ObjectNameInfo
= NULL
;
4031 BOOLEAN NullTerminate
= FALSE
;
4033 DPRINT("IoGetDeviceProperty(0x%p %d)\n", DeviceObject
, DeviceProperty
);
4035 /* Assume failure */
4038 /* Only PDOs can call this */
4039 if (!DeviceNode
) return STATUS_INVALID_DEVICE_REQUEST
;
4041 /* Handle all properties */
4042 switch (DeviceProperty
)
4044 case DevicePropertyBusTypeGuid
:
4046 /* Get the GUID from the internal cache */
4047 Status
= PnpBusTypeGuidGet(DeviceNode
->ChildBusTypeIndex
, &BusTypeGuid
);
4048 if (!NT_SUCCESS(Status
)) return Status
;
4050 /* This is the format of the returned data */
4051 PIP_RETURN_DATA(sizeof(GUID
), &BusTypeGuid
);
4053 case DevicePropertyLegacyBusType
:
4055 /* Validate correct interface type */
4056 if (DeviceNode
->ChildInterfaceType
== InterfaceTypeUndefined
)
4057 return STATUS_OBJECT_NAME_NOT_FOUND
;
4059 /* This is the format of the returned data */
4060 PIP_RETURN_DATA(sizeof(INTERFACE_TYPE
), &DeviceNode
->ChildInterfaceType
);
4062 case DevicePropertyBusNumber
:
4064 /* Validate correct bus number */
4065 if ((DeviceNode
->ChildBusNumber
& 0x80000000) == 0x80000000)
4066 return STATUS_OBJECT_NAME_NOT_FOUND
;
4068 /* This is the format of the returned data */
4069 PIP_RETURN_DATA(sizeof(ULONG
), &DeviceNode
->ChildBusNumber
);
4071 case DevicePropertyEnumeratorName
:
4073 /* Get the instance path */
4074 DeviceInstanceName
= DeviceNode
->InstancePath
.Buffer
;
4077 ASSERT((BufferLength
& 1) == 0);
4078 ASSERT(DeviceInstanceName
!= NULL
);
4080 /* Get the name from the path */
4081 EnumeratorNameEnd
= wcschr(DeviceInstanceName
, OBJ_NAME_PATH_SEPARATOR
);
4082 ASSERT(EnumeratorNameEnd
);
4084 /* This string needs to be NULL-terminated */
4085 NullTerminate
= TRUE
;
4087 /* This is the format of the returned data */
4088 PIP_RETURN_DATA((ULONG
)(EnumeratorNameEnd
- DeviceInstanceName
) * sizeof(WCHAR
),
4089 DeviceInstanceName
);
4091 case DevicePropertyAddress
:
4093 /* Query the device caps */
4094 Status
= IopQueryDeviceCapabilities(DeviceNode
, &DeviceCaps
);
4095 if (!NT_SUCCESS(Status
) || (DeviceCaps
.Address
== MAXULONG
))
4096 return STATUS_OBJECT_NAME_NOT_FOUND
;
4098 /* This is the format of the returned data */
4099 PIP_RETURN_DATA(sizeof(ULONG
), &DeviceCaps
.Address
);
4101 case DevicePropertyBootConfigurationTranslated
:
4103 /* Validate we have resources */
4104 if (!DeviceNode
->BootResources
)
4105 // if (!DeviceNode->BootResourcesTranslated) // FIXFIX: Need this field
4107 /* No resources will still fake success, but with 0 bytes */
4109 return STATUS_SUCCESS
;
4112 /* This is the format of the returned data */
4113 PIP_RETURN_DATA(PnpDetermineResourceListSize(DeviceNode
->BootResources
), // FIXFIX: Should use BootResourcesTranslated
4114 DeviceNode
->BootResources
); // FIXFIX: Should use BootResourcesTranslated
4116 case DevicePropertyPhysicalDeviceObjectName
:
4118 /* Sanity check for Unicode-sized string */
4119 ASSERT((BufferLength
& 1) == 0);
4121 /* Allocate name buffer */
4122 Length
= BufferLength
+ sizeof(OBJECT_NAME_INFORMATION
);
4123 ObjectNameInfo
= ExAllocatePool(PagedPool
, Length
);
4124 if (!ObjectNameInfo
) return STATUS_INSUFFICIENT_RESOURCES
;
4126 /* Query the PDO name */
4127 Status
= ObQueryNameString(DeviceObject
,
4131 if (Status
== STATUS_INFO_LENGTH_MISMATCH
)
4133 /* It's up to the caller to try again */
4134 Status
= STATUS_BUFFER_TOO_SMALL
;
4137 /* This string needs to be NULL-terminated */
4138 NullTerminate
= TRUE
;
4140 /* Return if successful */
4141 if (NT_SUCCESS(Status
)) PIP_RETURN_DATA(ObjectNameInfo
->Name
.Length
,
4142 ObjectNameInfo
->Name
.Buffer
);
4144 /* Let the caller know how big the name is */
4145 *ResultLength
-= sizeof(OBJECT_NAME_INFORMATION
);
4148 /* Handle the registry-based properties */
4149 case DevicePropertyUINumber
:
4150 PIP_REGISTRY_DATA(REGSTR_VAL_UI_NUMBER
, REG_DWORD
);
4151 case DevicePropertyLocationInformation
:
4152 PIP_REGISTRY_DATA(REGSTR_VAL_LOCATION_INFORMATION
, REG_SZ
);
4153 case DevicePropertyDeviceDescription
:
4154 PIP_REGISTRY_DATA(REGSTR_VAL_DEVDESC
, REG_SZ
);
4155 case DevicePropertyHardwareID
:
4156 PIP_REGISTRY_DATA(REGSTR_VAL_HARDWAREID
, REG_MULTI_SZ
);
4157 case DevicePropertyCompatibleIDs
:
4158 PIP_REGISTRY_DATA(REGSTR_VAL_COMPATIBLEIDS
, REG_MULTI_SZ
);
4159 case DevicePropertyBootConfiguration
:
4160 PIP_REGISTRY_DATA(REGSTR_VAL_BOOTCONFIG
, REG_RESOURCE_LIST
);
4161 case DevicePropertyClassName
:
4162 PIP_REGISTRY_DATA(REGSTR_VAL_CLASS
, REG_SZ
);
4163 case DevicePropertyClassGuid
:
4164 PIP_REGISTRY_DATA(REGSTR_VAL_CLASSGUID
, REG_SZ
);
4165 case DevicePropertyDriverKeyName
:
4166 PIP_REGISTRY_DATA(REGSTR_VAL_DRIVER
, REG_SZ
);
4167 case DevicePropertyManufacturer
:
4168 PIP_REGISTRY_DATA(REGSTR_VAL_MFG
, REG_SZ
);
4169 case DevicePropertyFriendlyName
:
4170 PIP_REGISTRY_DATA(REGSTR_VAL_FRIENDLYNAME
, REG_SZ
);
4171 case DevicePropertyContainerID
:
4172 //PIP_REGISTRY_DATA(REGSTR_VAL_CONTAINERID, REG_SZ); // Win7
4173 PIP_UNIMPLEMENTED();
4174 case DevicePropertyRemovalPolicy
:
4175 PIP_UNIMPLEMENTED();
4177 case DevicePropertyInstallState
:
4178 PIP_REGISTRY_DATA(REGSTR_VAL_CONFIGFLAGS
, REG_DWORD
);
4180 case DevicePropertyResourceRequirements
:
4181 PIP_UNIMPLEMENTED();
4182 case DevicePropertyAllocatedResources
:
4183 PIP_UNIMPLEMENTED();
4185 return STATUS_INVALID_PARAMETER_2
;
4188 /* Having a registry value name implies registry data */
4191 /* We know up-front how much data to expect */
4192 *ResultLength
= BufferLength
;
4194 /* Go get the data, use the LogConf subkey if necessary */
4195 Status
= PiGetDeviceRegistryProperty(DeviceObject
,
4199 DevicePropertyBootConfiguration
) ?
4204 else if (NT_SUCCESS(Status
))
4206 /* We know up-front how much data to expect, check the caller's buffer */
4207 *ResultLength
= ReturnLength
+ (NullTerminate
? sizeof(UNICODE_NULL
) : 0);
4208 if (*ResultLength
<= BufferLength
)
4210 /* Buffer is all good, copy the data */
4211 RtlCopyMemory(PropertyBuffer
, Data
, ReturnLength
);
4213 /* Check if we need to NULL-terminate the string */
4216 /* Terminate the string */
4217 ((PWCHAR
)PropertyBuffer
)[ReturnLength
/ sizeof(WCHAR
)] = UNICODE_NULL
;
4220 /* This is the success path */
4221 Status
= STATUS_SUCCESS
;
4226 Status
= STATUS_BUFFER_TOO_SMALL
;
4230 /* Free any allocation we may have made, and return the status code */
4231 if (ObjectNameInfo
) ExFreePool(ObjectNameInfo
);
4240 IoInvalidateDeviceState(IN PDEVICE_OBJECT PhysicalDeviceObject
)
4242 PDEVICE_NODE DeviceNode
= IopGetDeviceNode(PhysicalDeviceObject
);
4243 IO_STACK_LOCATION Stack
;
4246 IO_STATUS_BLOCK IoStatusBlock
;
4248 RtlZeroMemory(&Stack
, sizeof(IO_STACK_LOCATION
));
4249 Stack
.MajorFunction
= IRP_MJ_PNP
;
4250 Stack
.MinorFunction
= IRP_MN_QUERY_PNP_DEVICE_STATE
;
4252 Status
= IopSynchronousCall(PhysicalDeviceObject
, &Stack
, (PVOID
*)&PnPFlags
);
4253 if (!NT_SUCCESS(Status
))
4255 if (Status
!= STATUS_NOT_SUPPORTED
)
4257 DPRINT1("IRP_MN_QUERY_PNP_DEVICE_STATE failed with status 0x%lx\n", Status
);
4262 if (PnPFlags
& PNP_DEVICE_NOT_DISABLEABLE
)
4263 DeviceNode
->UserFlags
|= DNUF_NOT_DISABLEABLE
;
4265 DeviceNode
->UserFlags
&= ~DNUF_NOT_DISABLEABLE
;
4267 if (PnPFlags
& PNP_DEVICE_DONT_DISPLAY_IN_UI
)
4268 DeviceNode
->UserFlags
|= DNUF_DONT_SHOW_IN_UI
;
4270 DeviceNode
->UserFlags
&= ~DNUF_DONT_SHOW_IN_UI
;
4272 if ((PnPFlags
& PNP_DEVICE_REMOVED
) ||
4273 ((PnPFlags
& PNP_DEVICE_FAILED
) && !(PnPFlags
& PNP_DEVICE_RESOURCE_REQUIREMENTS_CHANGED
)))
4275 /* Flag it if it's failed */
4276 if (PnPFlags
& PNP_DEVICE_FAILED
) DeviceNode
->Problem
= CM_PROB_FAILED_POST_START
;
4278 /* Send removal IRPs to all of its children */
4279 IopPrepareDeviceForRemoval(PhysicalDeviceObject
, TRUE
);
4281 /* Send surprise removal */
4282 IopSendSurpriseRemoval(PhysicalDeviceObject
);
4284 /* Tell the user-mode PnP manager that a device was removed */
4285 IopQueueTargetDeviceEvent(&GUID_DEVICE_SURPRISE_REMOVAL
,
4286 &DeviceNode
->InstancePath
);
4288 IopSendRemoveDevice(PhysicalDeviceObject
);
4290 else if ((PnPFlags
& PNP_DEVICE_FAILED
) && (PnPFlags
& PNP_DEVICE_RESOURCE_REQUIREMENTS_CHANGED
))
4292 /* Stop for resource rebalance */
4293 Status
= IopStopDevice(DeviceNode
);
4294 if (!NT_SUCCESS(Status
))
4296 DPRINT1("Failed to stop device for rebalancing\n");
4298 /* Stop failed so don't rebalance */
4299 PnPFlags
&= ~PNP_DEVICE_RESOURCE_REQUIREMENTS_CHANGED
;
4303 /* Resource rebalance */
4304 if (PnPFlags
& PNP_DEVICE_RESOURCE_REQUIREMENTS_CHANGED
)
4306 DPRINT("Sending IRP_MN_QUERY_RESOURCES to device stack\n");
4308 Status
= IopInitiatePnpIrp(PhysicalDeviceObject
,
4310 IRP_MN_QUERY_RESOURCES
,
4312 if (NT_SUCCESS(Status
) && IoStatusBlock
.Information
)
4314 DeviceNode
->BootResources
=
4315 (PCM_RESOURCE_LIST
)IoStatusBlock
.Information
;
4316 IopDeviceNodeSetFlag(DeviceNode
, DNF_HAS_BOOT_CONFIG
);
4320 DPRINT("IopInitiatePnpIrp() failed (Status %x) or IoStatusBlock.Information=NULL\n", Status
);
4321 DeviceNode
->BootResources
= NULL
;
4324 DPRINT("Sending IRP_MN_QUERY_RESOURCE_REQUIREMENTS to device stack\n");
4326 Status
= IopInitiatePnpIrp(PhysicalDeviceObject
,
4328 IRP_MN_QUERY_RESOURCE_REQUIREMENTS
,
4330 if (NT_SUCCESS(Status
))
4332 DeviceNode
->ResourceRequirements
=
4333 (PIO_RESOURCE_REQUIREMENTS_LIST
)IoStatusBlock
.Information
;
4337 DPRINT("IopInitiatePnpIrp() failed (Status %08lx)\n", Status
);
4338 DeviceNode
->ResourceRequirements
= NULL
;
4341 /* IRP_MN_FILTER_RESOURCE_REQUIREMENTS is called indirectly by IopStartDevice */
4342 if (IopStartDevice(DeviceNode
) != STATUS_SUCCESS
)
4344 DPRINT1("Restart after resource rebalance failed\n");
4346 DeviceNode
->Flags
&= ~(DNF_STARTED
| DNF_START_REQUEST_PENDING
);
4347 DeviceNode
->Flags
|= DNF_START_FAILED
;
4349 IopRemoveDevice(DeviceNode
);
4355 * @name IoOpenDeviceRegistryKey
4357 * Open a registry key unique for a specified driver or device instance.
4359 * @param DeviceObject Device to get the registry key for.
4360 * @param DevInstKeyType Type of the key to return.
4361 * @param DesiredAccess Access mask (eg. KEY_READ | KEY_WRITE).
4362 * @param DevInstRegKey Handle to the opened registry key on
4363 * successful return.
4371 IoOpenDeviceRegistryKey(IN PDEVICE_OBJECT DeviceObject
,
4372 IN ULONG DevInstKeyType
,
4373 IN ACCESS_MASK DesiredAccess
,
4374 OUT PHANDLE DevInstRegKey
)
4376 static WCHAR RootKeyName
[] =
4377 L
"\\Registry\\Machine\\System\\CurrentControlSet\\";
4378 static WCHAR ProfileKeyName
[] =
4379 L
"Hardware Profiles\\Current\\System\\CurrentControlSet\\";
4380 static WCHAR ClassKeyName
[] = L
"Control\\Class\\";
4381 static WCHAR EnumKeyName
[] = L
"Enum\\";
4382 static WCHAR DeviceParametersKeyName
[] = L
"Device Parameters";
4383 ULONG KeyNameLength
;
4384 PWSTR KeyNameBuffer
;
4385 UNICODE_STRING KeyName
;
4386 ULONG DriverKeyLength
;
4387 OBJECT_ATTRIBUTES ObjectAttributes
;
4388 PDEVICE_NODE DeviceNode
= NULL
;
4391 DPRINT("IoOpenDeviceRegistryKey() called\n");
4393 if ((DevInstKeyType
& (PLUGPLAY_REGKEY_DEVICE
| PLUGPLAY_REGKEY_DRIVER
)) == 0)
4395 DPRINT1("IoOpenDeviceRegistryKey(): got wrong params, exiting... \n");
4396 return STATUS_INVALID_PARAMETER
;
4399 if (!IopIsValidPhysicalDeviceObject(DeviceObject
))
4400 return STATUS_INVALID_DEVICE_REQUEST
;
4401 DeviceNode
= IopGetDeviceNode(DeviceObject
);
4404 * Calculate the length of the base key name. This is the full
4405 * name for driver key or the name excluding "Device Parameters"
4406 * subkey for device key.
4409 KeyNameLength
= sizeof(RootKeyName
);
4410 if (DevInstKeyType
& PLUGPLAY_REGKEY_CURRENT_HWPROFILE
)
4411 KeyNameLength
+= sizeof(ProfileKeyName
) - sizeof(UNICODE_NULL
);
4412 if (DevInstKeyType
& PLUGPLAY_REGKEY_DRIVER
)
4414 KeyNameLength
+= sizeof(ClassKeyName
) - sizeof(UNICODE_NULL
);
4415 Status
= IoGetDeviceProperty(DeviceObject
, DevicePropertyDriverKeyName
,
4416 0, NULL
, &DriverKeyLength
);
4417 if (Status
!= STATUS_BUFFER_TOO_SMALL
)
4419 KeyNameLength
+= DriverKeyLength
;
4423 KeyNameLength
+= sizeof(EnumKeyName
) - sizeof(UNICODE_NULL
) +
4424 DeviceNode
->InstancePath
.Length
;
4428 * Now allocate the buffer for the key name...
4431 KeyNameBuffer
= ExAllocatePool(PagedPool
, KeyNameLength
);
4432 if (KeyNameBuffer
== NULL
)
4433 return STATUS_INSUFFICIENT_RESOURCES
;
4436 KeyName
.MaximumLength
= (USHORT
)KeyNameLength
;
4437 KeyName
.Buffer
= KeyNameBuffer
;
4440 * ...and build the key name.
4443 KeyName
.Length
+= sizeof(RootKeyName
) - sizeof(UNICODE_NULL
);
4444 RtlCopyMemory(KeyNameBuffer
, RootKeyName
, KeyName
.Length
);
4446 if (DevInstKeyType
& PLUGPLAY_REGKEY_CURRENT_HWPROFILE
)
4447 RtlAppendUnicodeToString(&KeyName
, ProfileKeyName
);
4449 if (DevInstKeyType
& PLUGPLAY_REGKEY_DRIVER
)
4451 RtlAppendUnicodeToString(&KeyName
, ClassKeyName
);
4452 Status
= IoGetDeviceProperty(DeviceObject
, DevicePropertyDriverKeyName
,
4453 DriverKeyLength
, KeyNameBuffer
+
4454 (KeyName
.Length
/ sizeof(WCHAR
)),
4456 if (!NT_SUCCESS(Status
))
4458 DPRINT1("Call to IoGetDeviceProperty() failed with Status 0x%08lx\n", Status
);
4459 ExFreePool(KeyNameBuffer
);
4462 KeyName
.Length
+= (USHORT
)DriverKeyLength
- sizeof(UNICODE_NULL
);
4466 RtlAppendUnicodeToString(&KeyName
, EnumKeyName
);
4467 Status
= RtlAppendUnicodeStringToString(&KeyName
, &DeviceNode
->InstancePath
);
4468 if (DeviceNode
->InstancePath
.Length
== 0)
4470 ExFreePool(KeyNameBuffer
);
4476 * Open the base key.
4478 Status
= IopOpenRegistryKeyEx(DevInstRegKey
, NULL
, &KeyName
, DesiredAccess
);
4479 if (!NT_SUCCESS(Status
))
4481 DPRINT1("IoOpenDeviceRegistryKey(%wZ): Base key doesn't exist, exiting... (Status 0x%08lx)\n", &KeyName
, Status
);
4482 ExFreePool(KeyNameBuffer
);
4485 ExFreePool(KeyNameBuffer
);
4488 * For driver key we're done now.
4491 if (DevInstKeyType
& PLUGPLAY_REGKEY_DRIVER
)
4495 * Let's go further. For device key we must open "Device Parameters"
4496 * subkey and create it if it doesn't exist yet.
4499 RtlInitUnicodeString(&KeyName
, DeviceParametersKeyName
);
4500 InitializeObjectAttributes(&ObjectAttributes
,
4502 OBJ_CASE_INSENSITIVE
| OBJ_KERNEL_HANDLE
,
4505 Status
= ZwCreateKey(DevInstRegKey
, DesiredAccess
, &ObjectAttributes
,
4506 0, NULL
, ExpInTextModeSetup
? REG_OPTION_VOLATILE
: 0, NULL
);
4507 ZwClose(ObjectAttributes
.RootDirectory
);
4514 IopQueryRemoveChildDevices(PDEVICE_NODE ParentDeviceNode
, BOOLEAN Force
)
4516 PDEVICE_NODE ChildDeviceNode
, NextDeviceNode
, FailedRemoveDevice
;
4520 KeAcquireSpinLock(&IopDeviceTreeLock
, &OldIrql
);
4521 ChildDeviceNode
= ParentDeviceNode
->Child
;
4522 while (ChildDeviceNode
!= NULL
)
4524 NextDeviceNode
= ChildDeviceNode
->Sibling
;
4525 KeReleaseSpinLock(&IopDeviceTreeLock
, OldIrql
);
4527 Status
= IopPrepareDeviceForRemoval(ChildDeviceNode
->PhysicalDeviceObject
, Force
);
4528 if (!NT_SUCCESS(Status
))
4530 FailedRemoveDevice
= ChildDeviceNode
;
4534 KeAcquireSpinLock(&IopDeviceTreeLock
, &OldIrql
);
4535 ChildDeviceNode
= NextDeviceNode
;
4537 KeReleaseSpinLock(&IopDeviceTreeLock
, OldIrql
);
4539 return STATUS_SUCCESS
;
4542 KeAcquireSpinLock(&IopDeviceTreeLock
, &OldIrql
);
4543 ChildDeviceNode
= ParentDeviceNode
->Child
;
4544 while (ChildDeviceNode
!= NULL
)
4546 NextDeviceNode
= ChildDeviceNode
->Sibling
;
4547 KeReleaseSpinLock(&IopDeviceTreeLock
, OldIrql
);
4549 IopCancelPrepareDeviceForRemoval(ChildDeviceNode
->PhysicalDeviceObject
);
4551 /* IRP_MN_CANCEL_REMOVE_DEVICE is also sent to the device
4552 * that failed the IRP_MN_QUERY_REMOVE_DEVICE request */
4553 if (ChildDeviceNode
== FailedRemoveDevice
)
4556 ChildDeviceNode
= NextDeviceNode
;
4558 KeAcquireSpinLock(&IopDeviceTreeLock
, &OldIrql
);
4560 KeReleaseSpinLock(&IopDeviceTreeLock
, OldIrql
);
4567 IopSendRemoveChildDevices(PDEVICE_NODE ParentDeviceNode
)
4569 PDEVICE_NODE ChildDeviceNode
, NextDeviceNode
;
4572 KeAcquireSpinLock(&IopDeviceTreeLock
, &OldIrql
);
4573 ChildDeviceNode
= ParentDeviceNode
->Child
;
4574 while (ChildDeviceNode
!= NULL
)
4576 NextDeviceNode
= ChildDeviceNode
->Sibling
;
4577 KeReleaseSpinLock(&IopDeviceTreeLock
, OldIrql
);
4579 IopSendRemoveDevice(ChildDeviceNode
->PhysicalDeviceObject
);
4581 ChildDeviceNode
= NextDeviceNode
;
4583 KeAcquireSpinLock(&IopDeviceTreeLock
, &OldIrql
);
4585 KeReleaseSpinLock(&IopDeviceTreeLock
, OldIrql
);
4590 IopCancelRemoveChildDevices(PDEVICE_NODE ParentDeviceNode
)
4592 PDEVICE_NODE ChildDeviceNode
, NextDeviceNode
;
4595 KeAcquireSpinLock(&IopDeviceTreeLock
, &OldIrql
);
4596 ChildDeviceNode
= ParentDeviceNode
->Child
;
4597 while (ChildDeviceNode
!= NULL
)
4599 NextDeviceNode
= ChildDeviceNode
->Sibling
;
4600 KeReleaseSpinLock(&IopDeviceTreeLock
, OldIrql
);
4602 IopCancelPrepareDeviceForRemoval(ChildDeviceNode
->PhysicalDeviceObject
);
4604 ChildDeviceNode
= NextDeviceNode
;
4606 KeAcquireSpinLock(&IopDeviceTreeLock
, &OldIrql
);
4608 KeReleaseSpinLock(&IopDeviceTreeLock
, OldIrql
);
4613 IopQueryRemoveDeviceRelations(PDEVICE_RELATIONS DeviceRelations
, BOOLEAN Force
)
4615 /* This function DOES NOT dereference the device objects on SUCCESS
4616 * but it DOES dereference device objects on FAILURE */
4621 for (i
= 0; i
< DeviceRelations
->Count
; i
++)
4623 Status
= IopPrepareDeviceForRemoval(DeviceRelations
->Objects
[i
], Force
);
4624 if (!NT_SUCCESS(Status
))
4631 return STATUS_SUCCESS
;
4634 /* IRP_MN_CANCEL_REMOVE_DEVICE is also sent to the device
4635 * that failed the IRP_MN_QUERY_REMOVE_DEVICE request */
4636 for (i
= 0; i
<= j
; i
++)
4638 IopCancelPrepareDeviceForRemoval(DeviceRelations
->Objects
[i
]);
4639 ObDereferenceObject(DeviceRelations
->Objects
[i
]);
4640 DeviceRelations
->Objects
[i
] = NULL
;
4642 for (; i
< DeviceRelations
->Count
; i
++)
4644 ObDereferenceObject(DeviceRelations
->Objects
[i
]);
4645 DeviceRelations
->Objects
[i
] = NULL
;
4647 ExFreePool(DeviceRelations
);
4654 IopSendRemoveDeviceRelations(PDEVICE_RELATIONS DeviceRelations
)
4656 /* This function DOES dereference the device objects in all cases */
4660 for (i
= 0; i
< DeviceRelations
->Count
; i
++)
4662 IopSendRemoveDevice(DeviceRelations
->Objects
[i
]);
4663 DeviceRelations
->Objects
[i
] = NULL
;
4666 ExFreePool(DeviceRelations
);
4671 IopCancelRemoveDeviceRelations(PDEVICE_RELATIONS DeviceRelations
)
4673 /* This function DOES dereference the device objects in all cases */
4677 for (i
= 0; i
< DeviceRelations
->Count
; i
++)
4679 IopCancelPrepareDeviceForRemoval(DeviceRelations
->Objects
[i
]);
4680 ObDereferenceObject(DeviceRelations
->Objects
[i
]);
4681 DeviceRelations
->Objects
[i
] = NULL
;
4684 ExFreePool(DeviceRelations
);
4688 IopCancelPrepareDeviceForRemoval(PDEVICE_OBJECT DeviceObject
)
4690 IO_STACK_LOCATION Stack
;
4691 IO_STATUS_BLOCK IoStatusBlock
;
4692 PDEVICE_RELATIONS DeviceRelations
;
4695 IopCancelRemoveDevice(DeviceObject
);
4697 Stack
.Parameters
.QueryDeviceRelations
.Type
= RemovalRelations
;
4699 Status
= IopInitiatePnpIrp(DeviceObject
,
4701 IRP_MN_QUERY_DEVICE_RELATIONS
,
4703 if (!NT_SUCCESS(Status
))
4705 DPRINT("IopInitiatePnpIrp() failed with status 0x%08lx\n", Status
);
4706 DeviceRelations
= NULL
;
4710 DeviceRelations
= (PDEVICE_RELATIONS
)IoStatusBlock
.Information
;
4713 if (DeviceRelations
)
4714 IopCancelRemoveDeviceRelations(DeviceRelations
);
4718 IopPrepareDeviceForRemoval(IN PDEVICE_OBJECT DeviceObject
, BOOLEAN Force
)
4720 PDEVICE_NODE DeviceNode
= IopGetDeviceNode(DeviceObject
);
4721 IO_STACK_LOCATION Stack
;
4722 IO_STATUS_BLOCK IoStatusBlock
;
4723 PDEVICE_RELATIONS DeviceRelations
;
4726 if ((DeviceNode
->UserFlags
& DNUF_NOT_DISABLEABLE
) && !Force
)
4728 DPRINT1("Removal not allowed for %wZ\n", &DeviceNode
->InstancePath
);
4729 return STATUS_UNSUCCESSFUL
;
4732 if (!Force
&& IopQueryRemoveDevice(DeviceObject
) != STATUS_SUCCESS
)
4734 DPRINT1("Removal vetoed by failing the query remove request\n");
4736 IopCancelRemoveDevice(DeviceObject
);
4738 return STATUS_UNSUCCESSFUL
;
4741 Stack
.Parameters
.QueryDeviceRelations
.Type
= RemovalRelations
;
4743 Status
= IopInitiatePnpIrp(DeviceObject
,
4745 IRP_MN_QUERY_DEVICE_RELATIONS
,
4747 if (!NT_SUCCESS(Status
))
4749 DPRINT("IopInitiatePnpIrp() failed with status 0x%08lx\n", Status
);
4750 DeviceRelations
= NULL
;
4754 DeviceRelations
= (PDEVICE_RELATIONS
)IoStatusBlock
.Information
;
4757 if (DeviceRelations
)
4759 Status
= IopQueryRemoveDeviceRelations(DeviceRelations
, Force
);
4760 if (!NT_SUCCESS(Status
))
4764 Status
= IopQueryRemoveChildDevices(DeviceNode
, Force
);
4765 if (!NT_SUCCESS(Status
))
4767 if (DeviceRelations
)
4768 IopCancelRemoveDeviceRelations(DeviceRelations
);
4772 if (DeviceRelations
)
4773 IopSendRemoveDeviceRelations(DeviceRelations
);
4774 IopSendRemoveChildDevices(DeviceNode
);
4776 return STATUS_SUCCESS
;
4780 IopRemoveDevice(PDEVICE_NODE DeviceNode
)
4784 DPRINT("Removing device: %wZ\n", &DeviceNode
->InstancePath
);
4786 Status
= IopPrepareDeviceForRemoval(DeviceNode
->PhysicalDeviceObject
, FALSE
);
4787 if (NT_SUCCESS(Status
))
4789 IopSendRemoveDevice(DeviceNode
->PhysicalDeviceObject
);
4790 IopQueueTargetDeviceEvent(&GUID_DEVICE_SAFE_REMOVAL
,
4791 &DeviceNode
->InstancePath
);
4792 return STATUS_SUCCESS
;
4803 IoRequestDeviceEject(IN PDEVICE_OBJECT PhysicalDeviceObject
)
4805 PDEVICE_NODE DeviceNode
= IopGetDeviceNode(PhysicalDeviceObject
);
4806 PDEVICE_RELATIONS DeviceRelations
;
4807 IO_STATUS_BLOCK IoStatusBlock
;
4808 IO_STACK_LOCATION Stack
;
4809 DEVICE_CAPABILITIES Capabilities
;
4812 IopQueueTargetDeviceEvent(&GUID_DEVICE_KERNEL_INITIATED_EJECT
,
4813 &DeviceNode
->InstancePath
);
4815 if (IopQueryDeviceCapabilities(DeviceNode
, &Capabilities
) != STATUS_SUCCESS
)
4820 Stack
.Parameters
.QueryDeviceRelations
.Type
= EjectionRelations
;
4822 Status
= IopInitiatePnpIrp(PhysicalDeviceObject
,
4824 IRP_MN_QUERY_DEVICE_RELATIONS
,
4826 if (!NT_SUCCESS(Status
))
4828 DPRINT("IopInitiatePnpIrp() failed with status 0x%08lx\n", Status
);
4829 DeviceRelations
= NULL
;
4833 DeviceRelations
= (PDEVICE_RELATIONS
)IoStatusBlock
.Information
;
4836 if (DeviceRelations
)
4838 Status
= IopQueryRemoveDeviceRelations(DeviceRelations
, FALSE
);
4839 if (!NT_SUCCESS(Status
))
4843 Status
= IopQueryRemoveChildDevices(DeviceNode
, FALSE
);
4844 if (!NT_SUCCESS(Status
))
4846 if (DeviceRelations
)
4847 IopCancelRemoveDeviceRelations(DeviceRelations
);
4851 if (IopPrepareDeviceForRemoval(PhysicalDeviceObject
, FALSE
) != STATUS_SUCCESS
)
4853 if (DeviceRelations
)
4854 IopCancelRemoveDeviceRelations(DeviceRelations
);
4855 IopCancelRemoveChildDevices(DeviceNode
);
4859 if (DeviceRelations
)
4860 IopSendRemoveDeviceRelations(DeviceRelations
);
4861 IopSendRemoveChildDevices(DeviceNode
);
4863 DeviceNode
->Problem
= CM_PROB_HELD_FOR_EJECT
;
4864 if (Capabilities
.EjectSupported
)
4866 if (IopSendEject(PhysicalDeviceObject
) != STATUS_SUCCESS
)
4873 DeviceNode
->Flags
|= DNF_DISABLED
;
4876 IopQueueTargetDeviceEvent(&GUID_DEVICE_EJECT
,
4877 &DeviceNode
->InstancePath
);
4882 IopQueueTargetDeviceEvent(&GUID_DEVICE_EJECT_VETOED
,
4883 &DeviceNode
->InstancePath
);
4891 IoInvalidateDeviceRelations(
4892 IN PDEVICE_OBJECT DeviceObject
,
4893 IN DEVICE_RELATION_TYPE Type
)
4895 PDEVICE_ACTION_DATA Data
;
4898 Data
= ExAllocatePoolWithTag(NonPagedPool
,
4899 sizeof(DEVICE_ACTION_DATA
),
4904 ObReferenceObject(DeviceObject
);
4905 Data
->DeviceObject
= DeviceObject
;
4908 KeAcquireSpinLock(&IopDeviceActionLock
, &OldIrql
);
4909 InsertTailList(&IopDeviceActionRequestList
, &Data
->RequestListEntry
);
4910 if (IopDeviceActionInProgress
)
4912 KeReleaseSpinLock(&IopDeviceActionLock
, OldIrql
);
4915 IopDeviceActionInProgress
= TRUE
;
4916 KeReleaseSpinLock(&IopDeviceActionLock
, OldIrql
);
4918 ExInitializeWorkItem(&IopDeviceActionWorkItem
,
4919 IopDeviceActionWorker
,
4921 ExQueueWorkItem(&IopDeviceActionWorkItem
,
4930 IoSynchronousInvalidateDeviceRelations(
4931 IN PDEVICE_OBJECT DeviceObject
,
4932 IN DEVICE_RELATION_TYPE Type
)
4939 /* Enumerate the device */
4940 return IopEnumerateDevice(DeviceObject
);
4941 case PowerRelations
:
4942 /* Not handled yet */
4943 return STATUS_NOT_IMPLEMENTED
;
4944 case TargetDeviceRelation
:
4946 return STATUS_SUCCESS
;
4948 /* Ejection relations are not supported */
4949 return STATUS_NOT_SUPPORTED
;
4958 IoTranslateBusAddress(IN INTERFACE_TYPE InterfaceType
,
4960 IN PHYSICAL_ADDRESS BusAddress
,
4961 IN OUT PULONG AddressSpace
,
4962 OUT PPHYSICAL_ADDRESS TranslatedAddress
)
4964 /* FIXME: Notify the resource arbiter */
4966 return HalTranslateBusAddress(InterfaceType
,