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 IopDeviceRelationsRequestList
;
38 WORK_QUEUE_ITEM IopDeviceRelationsWorkItem
;
39 BOOLEAN IopDeviceRelationsRequestInProgress
;
40 KSPIN_LOCK IopDeviceRelationsSpinLock
;
42 typedef struct _INVALIDATE_DEVICE_RELATION_DATA
44 LIST_ENTRY RequestListEntry
;
45 PDEVICE_OBJECT DeviceObject
;
46 DEVICE_RELATION_TYPE Type
;
47 } INVALIDATE_DEVICE_RELATION_DATA
, *PINVALIDATE_DEVICE_RELATION_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
, 0, &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
;
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
, 0, &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 Status
= ZwSetValueKey(ControlHandle
, &KeyName
, 0, REG_SZ
, DeviceNode
->ServiceName
.Buffer
, DeviceNode
->ServiceName
.Length
);
824 if (ControlHandle
!= NULL
)
825 ZwClose(ControlHandle
);
827 if (InstanceHandle
!= NULL
)
828 ZwClose(InstanceHandle
);
835 IopQueryDeviceCapabilities(PDEVICE_NODE DeviceNode
,
836 PDEVICE_CAPABILITIES DeviceCaps
)
838 IO_STATUS_BLOCK StatusBlock
;
839 IO_STACK_LOCATION Stack
;
842 UNICODE_STRING ValueName
;
844 /* Set up the Header */
845 RtlZeroMemory(DeviceCaps
, sizeof(DEVICE_CAPABILITIES
));
846 DeviceCaps
->Size
= sizeof(DEVICE_CAPABILITIES
);
847 DeviceCaps
->Version
= 1;
848 DeviceCaps
->Address
= -1;
849 DeviceCaps
->UINumber
= -1;
851 /* Set up the Stack */
852 RtlZeroMemory(&Stack
, sizeof(IO_STACK_LOCATION
));
853 Stack
.Parameters
.DeviceCapabilities
.Capabilities
= DeviceCaps
;
856 Status
= IopInitiatePnpIrp(DeviceNode
->PhysicalDeviceObject
,
858 IRP_MN_QUERY_CAPABILITIES
,
860 if (!NT_SUCCESS(Status
))
862 if (Status
!= STATUS_NOT_SUPPORTED
)
864 DPRINT1("IRP_MN_QUERY_CAPABILITIES failed with status 0x%lx\n", Status
);
869 DeviceNode
->CapabilityFlags
= *(PULONG
)((ULONG_PTR
)&DeviceCaps
->Version
+ sizeof(DeviceCaps
->Version
));
871 if (DeviceCaps
->NoDisplayInUI
)
872 DeviceNode
->UserFlags
|= DNUF_DONT_SHOW_IN_UI
;
874 DeviceNode
->UserFlags
&= ~DNUF_DONT_SHOW_IN_UI
;
876 Status
= IopCreateDeviceKeyPath(&DeviceNode
->InstancePath
, 0, &InstanceKey
);
877 if (NT_SUCCESS(Status
))
879 /* Set 'Capabilities' value */
880 RtlInitUnicodeString(&ValueName
, L
"Capabilities");
881 Status
= ZwSetValueKey(InstanceKey
,
885 &DeviceNode
->CapabilityFlags
,
888 /* Set 'UINumber' value */
889 if (DeviceCaps
->UINumber
!= MAXULONG
)
891 RtlInitUnicodeString(&ValueName
, L
"UINumber");
892 Status
= ZwSetValueKey(InstanceKey
,
896 &DeviceCaps
->UINumber
,
900 ZwClose(InstanceKey
);
909 IopDeviceRelationsWorker(
912 PLIST_ENTRY ListEntry
;
913 PINVALIDATE_DEVICE_RELATION_DATA Data
;
916 KeAcquireSpinLock(&IopDeviceRelationsSpinLock
, &OldIrql
);
917 while (!IsListEmpty(&IopDeviceRelationsRequestList
))
919 ListEntry
= RemoveHeadList(&IopDeviceRelationsRequestList
);
920 KeReleaseSpinLock(&IopDeviceRelationsSpinLock
, OldIrql
);
921 Data
= CONTAINING_RECORD(ListEntry
,
922 INVALIDATE_DEVICE_RELATION_DATA
,
925 IoSynchronousInvalidateDeviceRelations(Data
->DeviceObject
,
928 ObDereferenceObject(Data
->DeviceObject
);
930 KeAcquireSpinLock(&IopDeviceRelationsSpinLock
, &OldIrql
);
932 IopDeviceRelationsRequestInProgress
= FALSE
;
933 KeReleaseSpinLock(&IopDeviceRelationsSpinLock
, OldIrql
);
937 IopGetSystemPowerDeviceObject(PDEVICE_OBJECT
*DeviceObject
)
941 if (PopSystemPowerDeviceNode
)
943 KeAcquireSpinLock(&IopDeviceTreeLock
, &OldIrql
);
944 *DeviceObject
= PopSystemPowerDeviceNode
->PhysicalDeviceObject
;
945 KeReleaseSpinLock(&IopDeviceTreeLock
, OldIrql
);
947 return STATUS_SUCCESS
;
950 return STATUS_UNSUCCESSFUL
;
955 IopGetBusTypeGuidIndex(LPGUID BusTypeGuid
)
957 USHORT i
= 0, FoundIndex
= 0xFFFF;
961 /* Acquire the lock */
962 ExAcquireFastMutex(&PnpBusTypeGuidList
->Lock
);
964 /* Loop all entries */
965 while (i
< PnpBusTypeGuidList
->GuidCount
)
967 /* Try to find a match */
968 if (RtlCompareMemory(BusTypeGuid
,
969 &PnpBusTypeGuidList
->Guids
[i
],
970 sizeof(GUID
)) == sizeof(GUID
))
979 /* Check if we have to grow the list */
980 if (PnpBusTypeGuidList
->GuidCount
)
982 /* Calculate the new size */
983 NewSize
= sizeof(IO_BUS_TYPE_GUID_LIST
) +
984 (sizeof(GUID
) * PnpBusTypeGuidList
->GuidCount
);
986 /* Allocate the new copy */
987 NewList
= ExAllocatePool(PagedPool
, NewSize
);
991 ExFreePool(PnpBusTypeGuidList
);
995 /* Now copy them, decrease the size too */
996 NewSize
-= sizeof(GUID
);
997 RtlCopyMemory(NewList
, PnpBusTypeGuidList
, NewSize
);
999 /* Free the old list */
1000 ExFreePool(PnpBusTypeGuidList
);
1002 /* Use the new buffer */
1003 PnpBusTypeGuidList
= NewList
;
1006 /* Copy the new GUID */
1007 RtlCopyMemory(&PnpBusTypeGuidList
->Guids
[PnpBusTypeGuidList
->GuidCount
],
1011 /* The new entry is the index */
1012 FoundIndex
= (USHORT
)PnpBusTypeGuidList
->GuidCount
;
1013 PnpBusTypeGuidList
->GuidCount
++;
1016 ExReleaseFastMutex(&PnpBusTypeGuidList
->Lock
);
1022 * Creates a device node
1025 * ParentNode = Pointer to parent device node
1026 * PhysicalDeviceObject = Pointer to PDO for device object. Pass NULL
1027 * to have the root device node create one
1028 * (eg. for legacy drivers)
1029 * DeviceNode = Pointer to storage for created device node
1035 IopCreateDeviceNode(PDEVICE_NODE ParentNode
,
1036 PDEVICE_OBJECT PhysicalDeviceObject
,
1037 PUNICODE_STRING ServiceName
,
1038 PDEVICE_NODE
*DeviceNode
)
1043 UNICODE_STRING FullServiceName
;
1044 UNICODE_STRING LegacyPrefix
= RTL_CONSTANT_STRING(L
"LEGACY_");
1045 UNICODE_STRING UnknownDeviceName
= RTL_CONSTANT_STRING(L
"UNKNOWN");
1046 UNICODE_STRING KeyName
, ClassName
;
1047 PUNICODE_STRING ServiceName1
;
1049 UNICODE_STRING ClassGUID
;
1050 HANDLE InstanceHandle
;
1052 DPRINT("ParentNode 0x%p PhysicalDeviceObject 0x%p ServiceName %wZ\n",
1053 ParentNode
, PhysicalDeviceObject
, ServiceName
);
1055 Node
= ExAllocatePoolWithTag(NonPagedPool
, sizeof(DEVICE_NODE
), TAG_IO_DEVNODE
);
1058 return STATUS_INSUFFICIENT_RESOURCES
;
1061 RtlZeroMemory(Node
, sizeof(DEVICE_NODE
));
1064 ServiceName1
= &UnknownDeviceName
;
1066 ServiceName1
= ServiceName
;
1068 if (!PhysicalDeviceObject
)
1070 FullServiceName
.MaximumLength
= LegacyPrefix
.Length
+ ServiceName1
->Length
;
1071 FullServiceName
.Length
= 0;
1072 FullServiceName
.Buffer
= ExAllocatePool(PagedPool
, FullServiceName
.MaximumLength
);
1073 if (!FullServiceName
.Buffer
)
1075 ExFreePoolWithTag(Node
, TAG_IO_DEVNODE
);
1076 return STATUS_INSUFFICIENT_RESOURCES
;
1079 RtlAppendUnicodeStringToString(&FullServiceName
, &LegacyPrefix
);
1080 RtlAppendUnicodeStringToString(&FullServiceName
, ServiceName1
);
1082 Status
= PnpRootCreateDevice(&FullServiceName
, NULL
, &PhysicalDeviceObject
, &Node
->InstancePath
);
1083 if (!NT_SUCCESS(Status
))
1085 DPRINT1("PnpRootCreateDevice() failed with status 0x%08X\n", Status
);
1086 ExFreePool(FullServiceName
.Buffer
);
1087 ExFreePoolWithTag(Node
, TAG_IO_DEVNODE
);
1091 /* Create the device key for legacy drivers */
1092 Status
= IopCreateDeviceKeyPath(&Node
->InstancePath
, REG_OPTION_VOLATILE
, &InstanceHandle
);
1093 if (!NT_SUCCESS(Status
))
1095 ExFreePool(FullServiceName
.Buffer
);
1096 ExFreePoolWithTag(Node
, TAG_IO_DEVNODE
);
1100 Node
->ServiceName
.Buffer
= ExAllocatePool(PagedPool
, ServiceName1
->Length
);
1101 if (!Node
->ServiceName
.Buffer
)
1103 ZwClose(InstanceHandle
);
1104 ExFreePool(FullServiceName
.Buffer
);
1105 ExFreePoolWithTag(Node
, TAG_IO_DEVNODE
);
1109 Node
->ServiceName
.MaximumLength
= ServiceName1
->Length
;
1110 Node
->ServiceName
.Length
= 0;
1112 RtlAppendUnicodeStringToString(&Node
->ServiceName
, ServiceName1
);
1116 RtlInitUnicodeString(&KeyName
, L
"Service");
1117 Status
= ZwSetValueKey(InstanceHandle
, &KeyName
, 0, REG_SZ
, ServiceName
->Buffer
, ServiceName
->Length
);
1120 if (NT_SUCCESS(Status
))
1122 RtlInitUnicodeString(&KeyName
, L
"Legacy");
1125 Status
= ZwSetValueKey(InstanceHandle
, &KeyName
, 0, REG_DWORD
, &LegacyValue
, sizeof(LegacyValue
));
1126 if (NT_SUCCESS(Status
))
1128 RtlInitUnicodeString(&KeyName
, L
"Class");
1130 RtlInitUnicodeString(&ClassName
, L
"LegacyDriver\0");
1131 Status
= ZwSetValueKey(InstanceHandle
, &KeyName
, 0, REG_SZ
, ClassName
.Buffer
, ClassName
.Length
+ sizeof(UNICODE_NULL
));
1132 if (NT_SUCCESS(Status
))
1134 RtlInitUnicodeString(&KeyName
, L
"ClassGUID");
1136 RtlInitUnicodeString(&ClassGUID
, L
"{8ECC055D-047F-11D1-A537-0000F8753ED1}\0");
1137 Status
= ZwSetValueKey(InstanceHandle
, &KeyName
, 0, REG_SZ
, ClassGUID
.Buffer
, ClassGUID
.Length
+ sizeof(UNICODE_NULL
));
1138 if (NT_SUCCESS(Status
))
1140 RtlInitUnicodeString(&KeyName
, L
"DeviceDesc");
1142 Status
= ZwSetValueKey(InstanceHandle
, &KeyName
, 0, REG_SZ
, ServiceName1
->Buffer
, ServiceName1
->Length
+ sizeof(UNICODE_NULL
));
1148 ZwClose(InstanceHandle
);
1149 ExFreePool(FullServiceName
.Buffer
);
1151 if (!NT_SUCCESS(Status
))
1153 ExFreePool(Node
->ServiceName
.Buffer
);
1154 ExFreePoolWithTag(Node
, TAG_IO_DEVNODE
);
1158 IopDeviceNodeSetFlag(Node
, DNF_LEGACY_DRIVER
);
1159 IopDeviceNodeSetFlag(Node
, DNF_PROCESSED
);
1160 IopDeviceNodeSetFlag(Node
, DNF_ADDED
);
1161 IopDeviceNodeSetFlag(Node
, DNF_STARTED
);
1164 Node
->PhysicalDeviceObject
= PhysicalDeviceObject
;
1166 ((PEXTENDED_DEVOBJ_EXTENSION
)PhysicalDeviceObject
->DeviceObjectExtension
)->DeviceNode
= Node
;
1170 KeAcquireSpinLock(&IopDeviceTreeLock
, &OldIrql
);
1171 Node
->Parent
= ParentNode
;
1172 Node
->Sibling
= NULL
;
1173 if (ParentNode
->LastChild
== NULL
)
1175 ParentNode
->Child
= Node
;
1176 ParentNode
->LastChild
= Node
;
1180 ParentNode
->LastChild
->Sibling
= Node
;
1181 ParentNode
->LastChild
= Node
;
1183 KeReleaseSpinLock(&IopDeviceTreeLock
, OldIrql
);
1184 Node
->Level
= ParentNode
->Level
+ 1;
1187 PhysicalDeviceObject
->Flags
&= ~DO_DEVICE_INITIALIZING
;
1191 return STATUS_SUCCESS
;
1195 IopFreeDeviceNode(PDEVICE_NODE DeviceNode
)
1198 PDEVICE_NODE PrevSibling
= NULL
;
1200 /* All children must be deleted before a parent is deleted */
1201 ASSERT(!DeviceNode
->Child
);
1202 ASSERT(DeviceNode
->PhysicalDeviceObject
);
1204 KeAcquireSpinLock(&IopDeviceTreeLock
, &OldIrql
);
1206 /* Get previous sibling */
1207 if (DeviceNode
->Parent
&& DeviceNode
->Parent
->Child
!= DeviceNode
)
1209 PrevSibling
= DeviceNode
->Parent
->Child
;
1210 while (PrevSibling
->Sibling
!= DeviceNode
)
1211 PrevSibling
= PrevSibling
->Sibling
;
1214 /* Unlink from parent if it exists */
1215 if (DeviceNode
->Parent
)
1217 if (DeviceNode
->Parent
->LastChild
== DeviceNode
)
1219 DeviceNode
->Parent
->LastChild
= PrevSibling
;
1221 PrevSibling
->Sibling
= NULL
;
1223 if (DeviceNode
->Parent
->Child
== DeviceNode
)
1224 DeviceNode
->Parent
->Child
= DeviceNode
->Sibling
;
1227 /* Unlink from sibling list */
1229 PrevSibling
->Sibling
= DeviceNode
->Sibling
;
1231 KeReleaseSpinLock(&IopDeviceTreeLock
, OldIrql
);
1233 RtlFreeUnicodeString(&DeviceNode
->InstancePath
);
1235 RtlFreeUnicodeString(&DeviceNode
->ServiceName
);
1237 if (DeviceNode
->ResourceList
)
1239 ExFreePool(DeviceNode
->ResourceList
);
1242 if (DeviceNode
->ResourceListTranslated
)
1244 ExFreePool(DeviceNode
->ResourceListTranslated
);
1247 if (DeviceNode
->ResourceRequirements
)
1249 ExFreePool(DeviceNode
->ResourceRequirements
);
1252 if (DeviceNode
->BootResources
)
1254 ExFreePool(DeviceNode
->BootResources
);
1257 ((PEXTENDED_DEVOBJ_EXTENSION
)DeviceNode
->PhysicalDeviceObject
->DeviceObjectExtension
)->DeviceNode
= NULL
;
1258 ExFreePoolWithTag(DeviceNode
, TAG_IO_DEVNODE
);
1260 return STATUS_SUCCESS
;
1265 IopSynchronousCall(IN PDEVICE_OBJECT DeviceObject
,
1266 IN PIO_STACK_LOCATION IoStackLocation
,
1267 OUT PVOID
*Information
)
1270 PIO_STACK_LOCATION IrpStack
;
1271 IO_STATUS_BLOCK IoStatusBlock
;
1274 PDEVICE_OBJECT TopDeviceObject
;
1277 /* Call the top of the device stack */
1278 TopDeviceObject
= IoGetAttachedDeviceReference(DeviceObject
);
1280 /* Allocate an IRP */
1281 Irp
= IoAllocateIrp(TopDeviceObject
->StackSize
, FALSE
);
1282 if (!Irp
) return STATUS_INSUFFICIENT_RESOURCES
;
1284 /* Initialize to failure */
1285 Irp
->IoStatus
.Status
= IoStatusBlock
.Status
= STATUS_NOT_SUPPORTED
;
1286 Irp
->IoStatus
.Information
= IoStatusBlock
.Information
= 0;
1288 /* Special case for IRP_MN_FILTER_RESOURCE_REQUIREMENTS */
1289 if (IoStackLocation
->MinorFunction
== IRP_MN_FILTER_RESOURCE_REQUIREMENTS
)
1291 /* Copy the resource requirements list into the IOSB */
1292 Irp
->IoStatus
.Information
=
1293 IoStatusBlock
.Information
= (ULONG_PTR
)IoStackLocation
->Parameters
.FilterResourceRequirements
.IoResourceRequirementList
;
1296 /* Initialize the event */
1297 KeInitializeEvent(&Event
, SynchronizationEvent
, FALSE
);
1300 Irp
->UserIosb
= &IoStatusBlock
;
1301 Irp
->UserEvent
= &Event
;
1304 Irp
->Tail
.Overlay
.Thread
= PsGetCurrentThread();
1305 IoQueueThreadIrp(Irp
);
1307 /* Copy-in the stack */
1308 IrpStack
= IoGetNextIrpStackLocation(Irp
);
1309 *IrpStack
= *IoStackLocation
;
1311 /* Call the driver */
1312 Status
= IoCallDriver(TopDeviceObject
, Irp
);
1313 if (Status
== STATUS_PENDING
)
1316 KeWaitForSingleObject(&Event
,
1321 Status
= IoStatusBlock
.Status
;
1324 /* Remove the reference */
1325 ObDereferenceObject(TopDeviceObject
);
1327 /* Return the information */
1328 *Information
= (PVOID
)IoStatusBlock
.Information
;
1334 IopInitiatePnpIrp(IN PDEVICE_OBJECT DeviceObject
,
1335 IN OUT PIO_STATUS_BLOCK IoStatusBlock
,
1336 IN UCHAR MinorFunction
,
1337 IN PIO_STACK_LOCATION Stack OPTIONAL
)
1339 IO_STACK_LOCATION IoStackLocation
;
1341 /* Fill out the stack information */
1342 RtlZeroMemory(&IoStackLocation
, sizeof(IO_STACK_LOCATION
));
1343 IoStackLocation
.MajorFunction
= IRP_MJ_PNP
;
1344 IoStackLocation
.MinorFunction
= MinorFunction
;
1348 RtlCopyMemory(&IoStackLocation
.Parameters
,
1350 sizeof(Stack
->Parameters
));
1353 /* Do the PnP call */
1354 IoStatusBlock
->Status
= IopSynchronousCall(DeviceObject
,
1356 (PVOID
)&IoStatusBlock
->Information
);
1357 return IoStatusBlock
->Status
;
1361 IopTraverseDeviceTreeNode(PDEVICETREE_TRAVERSE_CONTEXT Context
)
1363 PDEVICE_NODE ParentDeviceNode
;
1364 PDEVICE_NODE ChildDeviceNode
;
1367 /* Copy context data so we don't overwrite it in subsequent calls to this function */
1368 ParentDeviceNode
= Context
->DeviceNode
;
1370 /* Call the action routine */
1371 Status
= (Context
->Action
)(ParentDeviceNode
, Context
->Context
);
1372 if (!NT_SUCCESS(Status
))
1377 /* Traversal of all children nodes */
1378 for (ChildDeviceNode
= ParentDeviceNode
->Child
;
1379 ChildDeviceNode
!= NULL
;
1380 ChildDeviceNode
= ChildDeviceNode
->Sibling
)
1382 /* Pass the current device node to the action routine */
1383 Context
->DeviceNode
= ChildDeviceNode
;
1385 Status
= IopTraverseDeviceTreeNode(Context
);
1386 if (!NT_SUCCESS(Status
))
1397 IopTraverseDeviceTree(PDEVICETREE_TRAVERSE_CONTEXT Context
)
1401 DPRINT("Context 0x%p\n", Context
);
1403 DPRINT("IopTraverseDeviceTree(DeviceNode 0x%p FirstDeviceNode 0x%p Action %p Context 0x%p)\n",
1404 Context
->DeviceNode
, Context
->FirstDeviceNode
, Context
->Action
, Context
->Context
);
1406 /* Start from the specified device node */
1407 Context
->DeviceNode
= Context
->FirstDeviceNode
;
1409 /* Recursively traverse the device tree */
1410 Status
= IopTraverseDeviceTreeNode(Context
);
1411 if (Status
== STATUS_UNSUCCESSFUL
)
1413 /* The action routine just wanted to terminate the traversal with status
1414 code STATUS_SUCCESS */
1415 Status
= STATUS_SUCCESS
;
1423 * IopCreateDeviceKeyPath
1425 * Creates a registry key
1429 * Name of the key to be created.
1431 * Handle to the newly created key
1434 * This method can create nested trees, so parent of RegistryPath can
1435 * be not existant, and will be created if needed.
1439 IopCreateDeviceKeyPath(IN PCUNICODE_STRING RegistryPath
,
1440 IN ULONG CreateOptions
,
1443 UNICODE_STRING EnumU
= RTL_CONSTANT_STRING(ENUM_ROOT
);
1444 HANDLE hParent
= NULL
, hKey
;
1445 OBJECT_ATTRIBUTES ObjectAttributes
;
1446 UNICODE_STRING KeyName
;
1447 PCWSTR Current
, Last
;
1451 /* Assume failure */
1454 /* Create a volatile device tree in 1st stage so we have a clean slate
1455 * for enumeration using the correct HAL (chosen in 1st stage setup) */
1456 if (ExpInTextModeSetup
) CreateOptions
|= REG_OPTION_VOLATILE
;
1458 /* Open root key for device instances */
1459 Status
= IopOpenRegistryKeyEx(&hParent
, NULL
, &EnumU
, KEY_CREATE_SUB_KEY
);
1460 if (!NT_SUCCESS(Status
))
1462 DPRINT1("ZwOpenKey('%wZ') failed with status 0x%08lx\n", &EnumU
, Status
);
1466 Current
= KeyName
.Buffer
= RegistryPath
->Buffer
;
1467 Last
= &RegistryPath
->Buffer
[RegistryPath
->Length
/ sizeof(WCHAR
)];
1469 /* Go up to the end of the string */
1470 while (Current
<= Last
)
1472 if (Current
!= Last
&& *Current
!= L
'\\')
1474 /* Not the end of the string and not a separator */
1479 /* Prepare relative key name */
1480 Length
= (USHORT
)((ULONG_PTR
)Current
- (ULONG_PTR
)KeyName
.Buffer
);
1481 KeyName
.MaximumLength
= KeyName
.Length
= Length
;
1482 DPRINT("Create '%wZ'\n", &KeyName
);
1485 InitializeObjectAttributes(&ObjectAttributes
,
1487 OBJ_CASE_INSENSITIVE
| OBJ_KERNEL_HANDLE
,
1490 Status
= ZwCreateKey(&hKey
,
1491 Current
== Last
? KEY_ALL_ACCESS
: KEY_CREATE_SUB_KEY
,
1498 /* Close parent key handle, we don't need it anymore */
1502 /* Key opening/creating failed? */
1503 if (!NT_SUCCESS(Status
))
1505 DPRINT1("ZwCreateKey('%wZ') failed with status 0x%08lx\n", &KeyName
, Status
);
1509 /* Check if it is the end of the string */
1510 if (Current
== Last
)
1512 /* Yes, return success */
1514 return STATUS_SUCCESS
;
1517 /* Start with this new parent key */
1520 KeyName
.Buffer
= (PWSTR
)Current
;
1523 return STATUS_UNSUCCESSFUL
;
1527 IopSetDeviceInstanceData(HANDLE InstanceKey
,
1528 PDEVICE_NODE DeviceNode
)
1530 OBJECT_ATTRIBUTES ObjectAttributes
;
1531 UNICODE_STRING KeyName
;
1536 HANDLE ControlHandle
;
1538 DPRINT("IopSetDeviceInstanceData() called\n");
1540 /* Create the 'LogConf' key */
1541 RtlInitUnicodeString(&KeyName
, L
"LogConf");
1542 InitializeObjectAttributes(&ObjectAttributes
,
1544 OBJ_CASE_INSENSITIVE
| OBJ_KERNEL_HANDLE
,
1547 Status
= ZwCreateKey(&LogConfKey
,
1552 REG_OPTION_VOLATILE
,
1554 if (NT_SUCCESS(Status
))
1556 /* Set 'BootConfig' value */
1557 if (DeviceNode
->BootResources
!= NULL
)
1559 ResCount
= DeviceNode
->BootResources
->Count
;
1562 RtlInitUnicodeString(&KeyName
, L
"BootConfig");
1563 Status
= ZwSetValueKey(LogConfKey
,
1567 DeviceNode
->BootResources
,
1568 PnpDetermineResourceListSize(DeviceNode
->BootResources
));
1572 /* Set 'BasicConfigVector' value */
1573 if (DeviceNode
->ResourceRequirements
!= NULL
&&
1574 DeviceNode
->ResourceRequirements
->ListSize
!= 0)
1576 RtlInitUnicodeString(&KeyName
, L
"BasicConfigVector");
1577 Status
= ZwSetValueKey(LogConfKey
,
1580 REG_RESOURCE_REQUIREMENTS_LIST
,
1581 DeviceNode
->ResourceRequirements
,
1582 DeviceNode
->ResourceRequirements
->ListSize
);
1585 ZwClose(LogConfKey
);
1588 /* Set the 'ConfigFlags' value */
1589 RtlInitUnicodeString(&KeyName
, L
"ConfigFlags");
1590 Status
= ZwQueryValueKey(InstanceKey
,
1592 KeyValueBasicInformation
,
1596 if (Status
== STATUS_OBJECT_NAME_NOT_FOUND
)
1598 /* Write the default value */
1599 ULONG DefaultConfigFlags
= 0;
1600 Status
= ZwSetValueKey(InstanceKey
,
1604 &DefaultConfigFlags
,
1605 sizeof(DefaultConfigFlags
));
1608 /* Create the 'Control' key */
1609 RtlInitUnicodeString(&KeyName
, L
"Control");
1610 InitializeObjectAttributes(&ObjectAttributes
,
1612 OBJ_CASE_INSENSITIVE
| OBJ_KERNEL_HANDLE
,
1615 Status
= ZwCreateKey(&ControlHandle
, 0, &ObjectAttributes
, 0, NULL
, REG_OPTION_VOLATILE
, NULL
);
1617 if (NT_SUCCESS(Status
))
1618 ZwClose(ControlHandle
);
1620 DPRINT("IopSetDeviceInstanceData() done\n");
1626 * IopGetParentIdPrefix
1628 * Retrieve (or create) a string which identifies a device.
1632 * Pointer to device node.
1634 * Pointer to the string where is returned the parent node identifier
1637 * If the return code is STATUS_SUCCESS, the ParentIdPrefix string is
1638 * valid and its Buffer field is NULL-terminated. The caller needs to
1639 * to free the string with RtlFreeUnicodeString when it is no longer
1644 IopGetParentIdPrefix(PDEVICE_NODE DeviceNode
,
1645 PUNICODE_STRING ParentIdPrefix
)
1647 const UNICODE_STRING EnumKeyPath
= RTL_CONSTANT_STRING(L
"\\Registry\\Machine\\System\\CurrentControlSet\\Enum\\");
1648 ULONG KeyNameBufferLength
;
1649 PKEY_VALUE_PARTIAL_INFORMATION ParentIdPrefixInformation
= NULL
;
1650 UNICODE_STRING KeyName
= {0, 0, NULL
};
1651 UNICODE_STRING KeyValue
;
1652 UNICODE_STRING ValueName
;
1657 /* HACK: As long as some devices have a NULL device
1658 * instance path, the following test is required :(
1660 if (DeviceNode
->Parent
->InstancePath
.Length
== 0)
1662 DPRINT1("Parent of %wZ has NULL Instance path, please report!\n",
1663 &DeviceNode
->InstancePath
);
1664 return STATUS_UNSUCCESSFUL
;
1667 /* 1. Try to retrieve ParentIdPrefix from registry */
1668 KeyNameBufferLength
= FIELD_OFFSET(KEY_VALUE_PARTIAL_INFORMATION
, Data
[0]) + MAX_PATH
* sizeof(WCHAR
);
1669 ParentIdPrefixInformation
= ExAllocatePoolWithTag(PagedPool
,
1670 KeyNameBufferLength
+ sizeof(UNICODE_NULL
),
1672 if (!ParentIdPrefixInformation
)
1674 return STATUS_INSUFFICIENT_RESOURCES
;
1678 KeyName
.MaximumLength
= EnumKeyPath
.Length
+
1679 DeviceNode
->Parent
->InstancePath
.Length
+
1680 sizeof(UNICODE_NULL
);
1681 KeyName
.Buffer
= ExAllocatePoolWithTag(PagedPool
,
1682 KeyName
.MaximumLength
,
1684 if (!KeyName
.Buffer
)
1686 Status
= STATUS_INSUFFICIENT_RESOURCES
;
1690 RtlCopyUnicodeString(&KeyName
, &EnumKeyPath
);
1691 RtlAppendUnicodeStringToString(&KeyName
, &DeviceNode
->Parent
->InstancePath
);
1693 Status
= IopOpenRegistryKeyEx(&hKey
, NULL
, &KeyName
, KEY_QUERY_VALUE
| KEY_SET_VALUE
);
1694 if (!NT_SUCCESS(Status
))
1698 RtlInitUnicodeString(&ValueName
, L
"ParentIdPrefix");
1699 Status
= ZwQueryValueKey(hKey
,
1701 KeyValuePartialInformation
,
1702 ParentIdPrefixInformation
,
1703 KeyNameBufferLength
,
1704 &KeyNameBufferLength
);
1705 if (NT_SUCCESS(Status
))
1707 if (ParentIdPrefixInformation
->Type
!= REG_SZ
)
1709 Status
= STATUS_UNSUCCESSFUL
;
1713 KeyValue
.MaximumLength
= (USHORT
)ParentIdPrefixInformation
->DataLength
;
1714 KeyValue
.Length
= KeyValue
.MaximumLength
- sizeof(UNICODE_NULL
);
1715 KeyValue
.Buffer
= (PWSTR
)ParentIdPrefixInformation
->Data
;
1716 ASSERT(KeyValue
.Buffer
[KeyValue
.Length
/ sizeof(WCHAR
)] == UNICODE_NULL
);
1720 if (Status
!= STATUS_OBJECT_NAME_NOT_FOUND
)
1722 /* FIXME how do we get here and why is ParentIdPrefixInformation valid? */
1723 KeyValue
.MaximumLength
= (USHORT
)ParentIdPrefixInformation
->DataLength
;
1724 KeyValue
.Length
= KeyValue
.MaximumLength
- sizeof(UNICODE_NULL
);
1725 KeyValue
.Buffer
= (PWSTR
)ParentIdPrefixInformation
->Data
;
1726 ASSERT(KeyValue
.Buffer
[KeyValue
.Length
/ sizeof(WCHAR
)] == UNICODE_NULL
);
1730 /* 2. Create the ParentIdPrefix value */
1731 crc32
= RtlComputeCrc32(0,
1732 (PUCHAR
)DeviceNode
->Parent
->InstancePath
.Buffer
,
1733 DeviceNode
->Parent
->InstancePath
.Length
);
1735 RtlStringCbPrintfW((PWSTR
)ParentIdPrefixInformation
,
1736 KeyNameBufferLength
,
1738 DeviceNode
->Parent
->Level
,
1740 RtlInitUnicodeString(&KeyValue
, (PWSTR
)ParentIdPrefixInformation
);
1742 /* 3. Try to write the ParentIdPrefix to registry */
1743 Status
= ZwSetValueKey(hKey
,
1748 ((ULONG
)wcslen(KeyValue
.Buffer
) + 1) * sizeof(WCHAR
));
1751 if (NT_SUCCESS(Status
))
1753 /* Duplicate the string to return it */
1754 Status
= RtlDuplicateUnicodeString(RTL_DUPLICATE_UNICODE_STRING_NULL_TERMINATE
,
1758 ExFreePoolWithTag(ParentIdPrefixInformation
, TAG_IO
);
1759 RtlFreeUnicodeString(&KeyName
);
1771 _In_ BUS_QUERY_ID_TYPE QueryType
)
1776 ULONG SeparatorsCount
= 0;
1777 PWCHAR PtrPrevChar
= NULL
;
1778 ULONG MaxSeparators
;
1785 case BusQueryDeviceID
:
1786 MaxSeparators
= MAX_SEPARATORS_DEVICEID
;
1789 case BusQueryInstanceID
:
1790 MaxSeparators
= MAX_SEPARATORS_INSTANCEID
;
1794 case BusQueryHardwareIDs
:
1795 case BusQueryCompatibleIDs
:
1800 DPRINT1("IopValidateID: Not handled QueryType - %x\n", QueryType
);
1804 StringEnd
= Id
+ MAX_DEVICE_ID_LEN
;
1806 for (PtrChar
= Id
; PtrChar
< StringEnd
; PtrChar
++)
1810 if (Char
== UNICODE_NULL
)
1812 if (!IsMultiSz
|| (PtrPrevChar
&& PtrChar
== PtrPrevChar
+ 1))
1814 if (MaxSeparators
== SeparatorsCount
|| IsMultiSz
)
1819 DPRINT1("IopValidateID: SeparatorsCount - %lu, MaxSeparators - %lu\n",
1820 SeparatorsCount
, MaxSeparators
);
1824 StringEnd
= PtrChar
+ MAX_DEVICE_ID_LEN
+ 1;
1825 PtrPrevChar
= PtrChar
;
1827 else if (Char
< ' ' || Char
> 0x7F || Char
== ',')
1829 DPRINT1("IopValidateID: Invalid character - %04X\n", Char
);
1832 else if (Char
== ' ')
1836 else if (Char
== '\\')
1840 if (SeparatorsCount
> MaxSeparators
)
1842 DPRINT1("IopValidateID: SeparatorsCount - %lu, MaxSeparators - %lu\n",
1843 SeparatorsCount
, MaxSeparators
);
1849 DPRINT1("IopValidateID: Not terminated ID\n");
1857 IopQueryHardwareIds(PDEVICE_NODE DeviceNode
,
1860 IO_STACK_LOCATION Stack
;
1861 IO_STATUS_BLOCK IoStatusBlock
;
1863 UNICODE_STRING ValueName
;
1865 ULONG Length
, TotalLength
;
1868 DPRINT("Sending IRP_MN_QUERY_ID.BusQueryHardwareIDs to device stack\n");
1870 RtlZeroMemory(&Stack
, sizeof(Stack
));
1871 Stack
.Parameters
.QueryId
.IdType
= BusQueryHardwareIDs
;
1872 Status
= IopInitiatePnpIrp(DeviceNode
->PhysicalDeviceObject
,
1876 if (NT_SUCCESS(Status
))
1878 IsValidID
= IopValidateID((PWCHAR
)IoStatusBlock
.Information
, BusQueryHardwareIDs
);
1882 DPRINT1("Invalid HardwareIDs. DeviceNode - %p\n", DeviceNode
);
1887 Ptr
= (PWSTR
)IoStatusBlock
.Information
;
1888 DPRINT("Hardware IDs:\n");
1891 DPRINT(" %S\n", Ptr
);
1892 Length
= (ULONG
)wcslen(Ptr
) + 1;
1895 TotalLength
+= Length
;
1897 DPRINT("TotalLength: %hu\n", TotalLength
);
1900 RtlInitUnicodeString(&ValueName
, L
"HardwareID");
1901 Status
= ZwSetValueKey(InstanceKey
,
1905 (PVOID
)IoStatusBlock
.Information
,
1906 (TotalLength
+ 1) * sizeof(WCHAR
));
1907 if (!NT_SUCCESS(Status
))
1909 DPRINT1("ZwSetValueKey() failed (Status %lx)\n", Status
);
1914 DPRINT("IopInitiatePnpIrp() failed (Status %x)\n", Status
);
1921 IopQueryCompatibleIds(PDEVICE_NODE DeviceNode
,
1924 IO_STACK_LOCATION Stack
;
1925 IO_STATUS_BLOCK IoStatusBlock
;
1927 UNICODE_STRING ValueName
;
1929 ULONG Length
, TotalLength
;
1932 DPRINT("Sending IRP_MN_QUERY_ID.BusQueryCompatibleIDs to device stack\n");
1934 RtlZeroMemory(&Stack
, sizeof(Stack
));
1935 Stack
.Parameters
.QueryId
.IdType
= BusQueryCompatibleIDs
;
1936 Status
= IopInitiatePnpIrp(
1937 DeviceNode
->PhysicalDeviceObject
,
1941 if (NT_SUCCESS(Status
) && IoStatusBlock
.Information
)
1943 IsValidID
= IopValidateID((PWCHAR
)IoStatusBlock
.Information
, BusQueryCompatibleIDs
);
1947 DPRINT1("Invalid CompatibleIDs. DeviceNode - %p\n", DeviceNode
);
1952 Ptr
= (PWSTR
)IoStatusBlock
.Information
;
1953 DPRINT("Compatible IDs:\n");
1956 DPRINT(" %S\n", Ptr
);
1957 Length
= (ULONG
)wcslen(Ptr
) + 1;
1960 TotalLength
+= Length
;
1962 DPRINT("TotalLength: %hu\n", TotalLength
);
1965 RtlInitUnicodeString(&ValueName
, L
"CompatibleIDs");
1966 Status
= ZwSetValueKey(InstanceKey
,
1970 (PVOID
)IoStatusBlock
.Information
,
1971 (TotalLength
+ 1) * sizeof(WCHAR
));
1972 if (!NT_SUCCESS(Status
))
1974 DPRINT1("ZwSetValueKey() failed (Status %lx) or no Compatible ID returned\n", Status
);
1979 DPRINT("IopInitiatePnpIrp() failed (Status %x)\n", Status
);
1986 IopCreateDeviceInstancePath(
1987 _In_ PDEVICE_NODE DeviceNode
,
1988 _Out_ PUNICODE_STRING InstancePath
)
1990 IO_STATUS_BLOCK IoStatusBlock
;
1991 UNICODE_STRING DeviceId
;
1992 UNICODE_STRING InstanceId
;
1993 IO_STACK_LOCATION Stack
;
1995 UNICODE_STRING ParentIdPrefix
= { 0, 0, NULL
};
1996 DEVICE_CAPABILITIES DeviceCapabilities
;
1999 DPRINT("Sending IRP_MN_QUERY_ID.BusQueryDeviceID to device stack\n");
2001 Stack
.Parameters
.QueryId
.IdType
= BusQueryDeviceID
;
2002 Status
= IopInitiatePnpIrp(DeviceNode
->PhysicalDeviceObject
,
2006 if (!NT_SUCCESS(Status
))
2008 DPRINT1("IopInitiatePnpIrp(BusQueryDeviceID) failed (Status %x)\n", Status
);
2012 IsValidID
= IopValidateID((PWCHAR
)IoStatusBlock
.Information
, BusQueryDeviceID
);
2016 DPRINT1("Invalid DeviceID. DeviceNode - %p\n", DeviceNode
);
2019 /* Save the device id string */
2020 RtlInitUnicodeString(&DeviceId
, (PWSTR
)IoStatusBlock
.Information
);
2022 DPRINT("Sending IRP_MN_QUERY_CAPABILITIES to device stack (after enumeration)\n");
2024 Status
= IopQueryDeviceCapabilities(DeviceNode
, &DeviceCapabilities
);
2025 if (!NT_SUCCESS(Status
))
2027 DPRINT1("IopQueryDeviceCapabilities() failed (Status 0x%08lx)\n", Status
);
2028 RtlFreeUnicodeString(&DeviceId
);
2032 /* This bit is only check after enumeration */
2033 if (DeviceCapabilities
.HardwareDisabled
)
2035 /* FIXME: Cleanup device */
2036 DeviceNode
->Flags
|= DNF_DISABLED
;
2037 RtlFreeUnicodeString(&DeviceId
);
2038 return STATUS_PLUGPLAY_NO_DEVICE
;
2042 DeviceNode
->Flags
&= ~DNF_DISABLED
;
2045 if (!DeviceCapabilities
.UniqueID
)
2047 /* Device has not a unique ID. We need to prepend parent bus unique identifier */
2048 DPRINT("Instance ID is not unique\n");
2049 Status
= IopGetParentIdPrefix(DeviceNode
, &ParentIdPrefix
);
2050 if (!NT_SUCCESS(Status
))
2052 DPRINT1("IopGetParentIdPrefix() failed (Status 0x%08lx)\n", Status
);
2053 RtlFreeUnicodeString(&DeviceId
);
2058 DPRINT("Sending IRP_MN_QUERY_ID.BusQueryInstanceID to device stack\n");
2060 Stack
.Parameters
.QueryId
.IdType
= BusQueryInstanceID
;
2061 Status
= IopInitiatePnpIrp(DeviceNode
->PhysicalDeviceObject
,
2065 if (!NT_SUCCESS(Status
))
2067 DPRINT("IopInitiatePnpIrp(BusQueryInstanceID) failed (Status %lx)\n", Status
);
2068 ASSERT(IoStatusBlock
.Information
== 0);
2071 if (IoStatusBlock
.Information
)
2073 IsValidID
= IopValidateID((PWCHAR
)IoStatusBlock
.Information
, BusQueryInstanceID
);
2077 DPRINT1("Invalid InstanceID. DeviceNode - %p\n", DeviceNode
);
2081 RtlInitUnicodeString(&InstanceId
,
2082 (PWSTR
)IoStatusBlock
.Information
);
2084 InstancePath
->Length
= 0;
2085 InstancePath
->MaximumLength
= DeviceId
.Length
+ sizeof(WCHAR
) +
2086 ParentIdPrefix
.Length
+
2088 sizeof(UNICODE_NULL
);
2089 if (ParentIdPrefix
.Length
&& InstanceId
.Length
)
2091 InstancePath
->MaximumLength
+= sizeof(WCHAR
);
2094 InstancePath
->Buffer
= ExAllocatePoolWithTag(PagedPool
,
2095 InstancePath
->MaximumLength
,
2097 if (!InstancePath
->Buffer
)
2099 RtlFreeUnicodeString(&InstanceId
);
2100 RtlFreeUnicodeString(&ParentIdPrefix
);
2101 RtlFreeUnicodeString(&DeviceId
);
2102 return STATUS_INSUFFICIENT_RESOURCES
;
2105 /* Start with the device id */
2106 RtlCopyUnicodeString(InstancePath
, &DeviceId
);
2107 RtlAppendUnicodeToString(InstancePath
, L
"\\");
2109 /* Add information from parent bus device to InstancePath */
2110 RtlAppendUnicodeStringToString(InstancePath
, &ParentIdPrefix
);
2111 if (ParentIdPrefix
.Length
&& InstanceId
.Length
)
2113 RtlAppendUnicodeToString(InstancePath
, L
"&");
2116 /* Finally, add the id returned by the driver stack */
2117 RtlAppendUnicodeStringToString(InstancePath
, &InstanceId
);
2120 * FIXME: Check for valid characters, if there is invalid characters
2124 RtlFreeUnicodeString(&InstanceId
);
2125 RtlFreeUnicodeString(&DeviceId
);
2126 RtlFreeUnicodeString(&ParentIdPrefix
);
2128 return STATUS_SUCCESS
;
2132 * IopActionInterrogateDeviceStack
2134 * Retrieve information for all (direct) child nodes of a parent node.
2138 * Pointer to device node.
2140 * Pointer to parent node to retrieve child node information for.
2143 * Any errors that occur are logged instead so that all child services have a chance
2144 * of being interrogated.
2148 IopActionInterrogateDeviceStack(PDEVICE_NODE DeviceNode
,
2151 IO_STATUS_BLOCK IoStatusBlock
;
2152 PWSTR DeviceDescription
;
2153 PWSTR LocationInformation
;
2154 PDEVICE_NODE ParentDeviceNode
;
2155 IO_STACK_LOCATION Stack
;
2157 ULONG RequiredLength
;
2159 HANDLE InstanceKey
= NULL
;
2160 UNICODE_STRING ValueName
;
2161 UNICODE_STRING InstancePathU
;
2162 PDEVICE_OBJECT OldDeviceObject
;
2164 DPRINT("IopActionInterrogateDeviceStack(%p, %p)\n", DeviceNode
, Context
);
2165 DPRINT("PDO 0x%p\n", DeviceNode
->PhysicalDeviceObject
);
2167 ParentDeviceNode
= (PDEVICE_NODE
)Context
;
2170 * We are called for the parent too, but we don't need to do special
2171 * handling for this node
2173 if (DeviceNode
== ParentDeviceNode
)
2175 DPRINT("Success\n");
2176 return STATUS_SUCCESS
;
2180 * Make sure this device node is a direct child of the parent device node
2181 * that is given as an argument
2183 if (DeviceNode
->Parent
!= ParentDeviceNode
)
2185 DPRINT("Skipping 2+ level child\n");
2186 return STATUS_SUCCESS
;
2189 /* Skip processing if it was already completed before */
2190 if (DeviceNode
->Flags
& DNF_PROCESSED
)
2193 return STATUS_SUCCESS
;
2197 Status
= ZwQueryDefaultLocale(FALSE
, &LocaleId
);
2198 if (!NT_SUCCESS(Status
))
2200 DPRINT1("ZwQueryDefaultLocale() failed with status 0x%lx\n", Status
);
2205 * FIXME: For critical errors, cleanup and disable device, but always
2206 * return STATUS_SUCCESS.
2209 Status
= IopCreateDeviceInstancePath(DeviceNode
, &InstancePathU
);
2210 if (!NT_SUCCESS(Status
))
2212 if (Status
!= STATUS_PLUGPLAY_NO_DEVICE
)
2214 DPRINT1("IopCreateDeviceInstancePath() failed with status 0x%lx\n", Status
);
2217 /* We have to return success otherwise we abort the traverse operation */
2218 return STATUS_SUCCESS
;
2221 /* Verify that this is not a duplicate */
2222 OldDeviceObject
= IopGetDeviceObjectFromDeviceInstance(&InstancePathU
);
2223 if (OldDeviceObject
!= NULL
)
2225 PDEVICE_NODE OldDeviceNode
= IopGetDeviceNode(OldDeviceObject
);
2227 DPRINT1("Duplicate device instance '%wZ'\n", &InstancePathU
);
2228 DPRINT1("Current instance parent: '%wZ'\n", &DeviceNode
->Parent
->InstancePath
);
2229 DPRINT1("Old instance parent: '%wZ'\n", &OldDeviceNode
->Parent
->InstancePath
);
2231 KeBugCheckEx(PNP_DETECTED_FATAL_ERROR
,
2233 (ULONG_PTR
)DeviceNode
->PhysicalDeviceObject
,
2234 (ULONG_PTR
)OldDeviceObject
,
2238 DeviceNode
->InstancePath
= InstancePathU
;
2240 DPRINT("InstancePath is %S\n", DeviceNode
->InstancePath
.Buffer
);
2243 * Create registry key for the instance id, if it doesn't exist yet
2245 Status
= IopCreateDeviceKeyPath(&DeviceNode
->InstancePath
, 0, &InstanceKey
);
2246 if (!NT_SUCCESS(Status
))
2248 DPRINT1("Failed to create the instance key! (Status %lx)\n", Status
);
2250 /* We have to return success otherwise we abort the traverse operation */
2251 return STATUS_SUCCESS
;
2254 IopQueryHardwareIds(DeviceNode
, InstanceKey
);
2256 IopQueryCompatibleIds(DeviceNode
, InstanceKey
);
2258 DPRINT("Sending IRP_MN_QUERY_DEVICE_TEXT.DeviceTextDescription to device stack\n");
2260 Stack
.Parameters
.QueryDeviceText
.DeviceTextType
= DeviceTextDescription
;
2261 Stack
.Parameters
.QueryDeviceText
.LocaleId
= LocaleId
;
2262 Status
= IopInitiatePnpIrp(DeviceNode
->PhysicalDeviceObject
,
2264 IRP_MN_QUERY_DEVICE_TEXT
,
2266 DeviceDescription
= NT_SUCCESS(Status
) ? (PWSTR
)IoStatusBlock
.Information
2268 /* This key is mandatory, so even if the Irp fails, we still write it */
2269 RtlInitUnicodeString(&ValueName
, L
"DeviceDesc");
2270 if (ZwQueryValueKey(InstanceKey
, &ValueName
, KeyValueBasicInformation
, NULL
, 0, &RequiredLength
) == STATUS_OBJECT_NAME_NOT_FOUND
)
2272 if (DeviceDescription
&&
2273 *DeviceDescription
!= UNICODE_NULL
)
2275 /* This key is overriden when a driver is installed. Don't write the
2276 * new description if another one already exists */
2277 Status
= ZwSetValueKey(InstanceKey
,
2282 ((ULONG
)wcslen(DeviceDescription
) + 1) * sizeof(WCHAR
));
2286 UNICODE_STRING DeviceDesc
= RTL_CONSTANT_STRING(L
"Unknown device");
2287 DPRINT("Driver didn't return DeviceDesc (Status 0x%08lx), so place unknown device there\n", Status
);
2289 Status
= ZwSetValueKey(InstanceKey
,
2294 DeviceDesc
.MaximumLength
);
2295 if (!NT_SUCCESS(Status
))
2297 DPRINT1("ZwSetValueKey() failed (Status 0x%lx)\n", Status
);
2303 if (DeviceDescription
)
2305 ExFreePoolWithTag(DeviceDescription
, 0);
2308 DPRINT("Sending IRP_MN_QUERY_DEVICE_TEXT.DeviceTextLocation to device stack\n");
2310 Stack
.Parameters
.QueryDeviceText
.DeviceTextType
= DeviceTextLocationInformation
;
2311 Stack
.Parameters
.QueryDeviceText
.LocaleId
= LocaleId
;
2312 Status
= IopInitiatePnpIrp(DeviceNode
->PhysicalDeviceObject
,
2314 IRP_MN_QUERY_DEVICE_TEXT
,
2316 if (NT_SUCCESS(Status
) && IoStatusBlock
.Information
)
2318 LocationInformation
= (PWSTR
)IoStatusBlock
.Information
;
2319 DPRINT("LocationInformation: %S\n", LocationInformation
);
2320 RtlInitUnicodeString(&ValueName
, L
"LocationInformation");
2321 Status
= ZwSetValueKey(InstanceKey
,
2325 LocationInformation
,
2326 ((ULONG
)wcslen(LocationInformation
) + 1) * sizeof(WCHAR
));
2327 if (!NT_SUCCESS(Status
))
2329 DPRINT1("ZwSetValueKey() failed (Status %lx)\n", Status
);
2332 ExFreePoolWithTag(LocationInformation
, 0);
2336 DPRINT("IopInitiatePnpIrp() failed (Status %x) or IoStatusBlock.Information=NULL\n", Status
);
2339 DPRINT("Sending IRP_MN_QUERY_BUS_INFORMATION to device stack\n");
2341 Status
= IopInitiatePnpIrp(DeviceNode
->PhysicalDeviceObject
,
2343 IRP_MN_QUERY_BUS_INFORMATION
,
2345 if (NT_SUCCESS(Status
) && IoStatusBlock
.Information
)
2347 PPNP_BUS_INFORMATION BusInformation
= (PPNP_BUS_INFORMATION
)IoStatusBlock
.Information
;
2349 DeviceNode
->ChildBusNumber
= BusInformation
->BusNumber
;
2350 DeviceNode
->ChildInterfaceType
= BusInformation
->LegacyBusType
;
2351 DeviceNode
->ChildBusTypeIndex
= IopGetBusTypeGuidIndex(&BusInformation
->BusTypeGuid
);
2352 ExFreePoolWithTag(BusInformation
, 0);
2356 DPRINT("IopInitiatePnpIrp() failed (Status %x) or IoStatusBlock.Information=NULL\n", Status
);
2358 DeviceNode
->ChildBusNumber
= 0xFFFFFFF0;
2359 DeviceNode
->ChildInterfaceType
= InterfaceTypeUndefined
;
2360 DeviceNode
->ChildBusTypeIndex
= -1;
2363 DPRINT("Sending IRP_MN_QUERY_RESOURCES to device stack\n");
2365 Status
= IopInitiatePnpIrp(DeviceNode
->PhysicalDeviceObject
,
2367 IRP_MN_QUERY_RESOURCES
,
2369 if (NT_SUCCESS(Status
) && IoStatusBlock
.Information
)
2371 DeviceNode
->BootResources
= (PCM_RESOURCE_LIST
)IoStatusBlock
.Information
;
2372 IopDeviceNodeSetFlag(DeviceNode
, DNF_HAS_BOOT_CONFIG
);
2376 DPRINT("IopInitiatePnpIrp() failed (Status %x) or IoStatusBlock.Information=NULL\n", Status
);
2377 DeviceNode
->BootResources
= NULL
;
2380 DPRINT("Sending IRP_MN_QUERY_RESOURCE_REQUIREMENTS to device stack\n");
2382 Status
= IopInitiatePnpIrp(DeviceNode
->PhysicalDeviceObject
,
2384 IRP_MN_QUERY_RESOURCE_REQUIREMENTS
,
2386 if (NT_SUCCESS(Status
))
2388 DeviceNode
->ResourceRequirements
= (PIO_RESOURCE_REQUIREMENTS_LIST
)IoStatusBlock
.Information
;
2392 DPRINT("IopInitiatePnpIrp() failed (Status %08lx)\n", Status
);
2393 DeviceNode
->ResourceRequirements
= NULL
;
2396 if (InstanceKey
!= NULL
)
2398 IopSetDeviceInstanceData(InstanceKey
, DeviceNode
);
2401 ZwClose(InstanceKey
);
2403 IopDeviceNodeSetFlag(DeviceNode
, DNF_PROCESSED
);
2405 if (!IopDeviceNodeHasFlag(DeviceNode
, DNF_LEGACY_DRIVER
))
2407 /* Report the device to the user-mode pnp manager */
2408 IopQueueTargetDeviceEvent(&GUID_DEVICE_ENUMERATED
,
2409 &DeviceNode
->InstancePath
);
2412 return STATUS_SUCCESS
;
2417 IopHandleDeviceRemoval(
2418 IN PDEVICE_NODE DeviceNode
,
2419 IN PDEVICE_RELATIONS DeviceRelations
)
2421 PDEVICE_NODE Child
= DeviceNode
->Child
, NextChild
;
2425 if (DeviceNode
== IopRootDeviceNode
)
2428 while (Child
!= NULL
)
2430 NextChild
= Child
->Sibling
;
2433 for (i
= 0; DeviceRelations
&& i
< DeviceRelations
->Count
; i
++)
2435 if (IopGetDeviceNode(DeviceRelations
->Objects
[i
]) == Child
)
2442 if (!Found
&& !(Child
->Flags
& DNF_WILL_BE_REMOVED
))
2444 /* Send removal IRPs to all of its children */
2445 IopPrepareDeviceForRemoval(Child
->PhysicalDeviceObject
, TRUE
);
2447 /* Send the surprise removal IRP */
2448 IopSendSurpriseRemoval(Child
->PhysicalDeviceObject
);
2450 /* Tell the user-mode PnP manager that a device was removed */
2451 IopQueueTargetDeviceEvent(&GUID_DEVICE_SURPRISE_REMOVAL
,
2452 &Child
->InstancePath
);
2454 /* Send the remove device IRP */
2455 IopSendRemoveDevice(Child
->PhysicalDeviceObject
);
2464 IN PDEVICE_OBJECT DeviceObject
)
2466 PDEVICE_NODE DeviceNode
= IopGetDeviceNode(DeviceObject
);
2467 DEVICETREE_TRAVERSE_CONTEXT Context
;
2468 PDEVICE_RELATIONS DeviceRelations
;
2469 PDEVICE_OBJECT ChildDeviceObject
;
2470 IO_STATUS_BLOCK IoStatusBlock
;
2471 PDEVICE_NODE ChildDeviceNode
;
2472 IO_STACK_LOCATION Stack
;
2476 DPRINT("DeviceObject 0x%p\n", DeviceObject
);
2478 if (DeviceNode
->Flags
& DNF_NEED_ENUMERATION_ONLY
)
2480 DeviceNode
->Flags
&= ~DNF_NEED_ENUMERATION_ONLY
;
2482 DPRINT("Sending GUID_DEVICE_ARRIVAL\n");
2483 IopQueueTargetDeviceEvent(&GUID_DEVICE_ARRIVAL
,
2484 &DeviceNode
->InstancePath
);
2487 DPRINT("Sending IRP_MN_QUERY_DEVICE_RELATIONS to device stack\n");
2489 Stack
.Parameters
.QueryDeviceRelations
.Type
= BusRelations
;
2491 Status
= IopInitiatePnpIrp(
2494 IRP_MN_QUERY_DEVICE_RELATIONS
,
2496 if (!NT_SUCCESS(Status
) || Status
== STATUS_PENDING
)
2498 DPRINT("IopInitiatePnpIrp() failed with status 0x%08lx\n", Status
);
2502 DeviceRelations
= (PDEVICE_RELATIONS
)IoStatusBlock
.Information
;
2505 * Send removal IRPs for devices that have disappeared
2506 * NOTE: This code handles the case where no relations are specified
2508 IopHandleDeviceRemoval(DeviceNode
, DeviceRelations
);
2510 /* Now we bail if nothing was returned */
2511 if (!DeviceRelations
)
2513 /* We're all done */
2514 DPRINT("No PDOs\n");
2515 return STATUS_SUCCESS
;
2518 DPRINT("Got %u PDOs\n", DeviceRelations
->Count
);
2521 * Create device nodes for all discovered devices
2523 for (i
= 0; i
< DeviceRelations
->Count
; i
++)
2525 ChildDeviceObject
= DeviceRelations
->Objects
[i
];
2526 ASSERT((ChildDeviceObject
->Flags
& DO_DEVICE_INITIALIZING
) == 0);
2528 ChildDeviceNode
= IopGetDeviceNode(ChildDeviceObject
);
2529 if (!ChildDeviceNode
)
2531 /* One doesn't exist, create it */
2532 Status
= IopCreateDeviceNode(
2537 if (NT_SUCCESS(Status
))
2539 /* Mark the node as enumerated */
2540 ChildDeviceNode
->Flags
|= DNF_ENUMERATED
;
2542 /* Mark the DO as bus enumerated */
2543 ChildDeviceObject
->Flags
|= DO_BUS_ENUMERATED_DEVICE
;
2547 /* Ignore this DO */
2548 DPRINT1("IopCreateDeviceNode() failed with status 0x%08x. Skipping PDO %u\n", Status
, i
);
2549 ObDereferenceObject(ChildDeviceObject
);
2554 /* Mark it as enumerated */
2555 ChildDeviceNode
->Flags
|= DNF_ENUMERATED
;
2556 ObDereferenceObject(ChildDeviceObject
);
2559 ExFreePool(DeviceRelations
);
2562 * Retrieve information about all discovered children from the bus driver
2564 IopInitDeviceTreeTraverseContext(
2567 IopActionInterrogateDeviceStack
,
2570 Status
= IopTraverseDeviceTree(&Context
);
2571 if (!NT_SUCCESS(Status
))
2573 DPRINT("IopTraverseDeviceTree() failed with status 0x%08lx\n", Status
);
2578 * Retrieve configuration from the registry for discovered children
2580 IopInitDeviceTreeTraverseContext(
2583 IopActionConfigureChildServices
,
2586 Status
= IopTraverseDeviceTree(&Context
);
2587 if (!NT_SUCCESS(Status
))
2589 DPRINT("IopTraverseDeviceTree() failed with status 0x%08lx\n", Status
);
2594 * Initialize services for discovered children.
2596 Status
= IopInitializePnpServices(DeviceNode
);
2597 if (!NT_SUCCESS(Status
))
2599 DPRINT("IopInitializePnpServices() failed with status 0x%08lx\n", Status
);
2603 DPRINT("IopEnumerateDevice() finished\n");
2604 return STATUS_SUCCESS
;
2609 * IopActionConfigureChildServices
2611 * Retrieve configuration for all (direct) child nodes of a parent node.
2615 * Pointer to device node.
2617 * Pointer to parent node to retrieve child node configuration for.
2620 * Any errors that occur are logged instead so that all child services have a chance of beeing
2625 IopActionConfigureChildServices(PDEVICE_NODE DeviceNode
,
2628 RTL_QUERY_REGISTRY_TABLE QueryTable
[3];
2629 PDEVICE_NODE ParentDeviceNode
;
2630 PUNICODE_STRING Service
;
2631 UNICODE_STRING ClassGUID
;
2633 DEVICE_CAPABILITIES DeviceCaps
;
2635 DPRINT("IopActionConfigureChildServices(%p, %p)\n", DeviceNode
, Context
);
2637 ParentDeviceNode
= (PDEVICE_NODE
)Context
;
2640 * We are called for the parent too, but we don't need to do special
2641 * handling for this node
2643 if (DeviceNode
== ParentDeviceNode
)
2645 DPRINT("Success\n");
2646 return STATUS_SUCCESS
;
2650 * Make sure this device node is a direct child of the parent device node
2651 * that is given as an argument
2654 if (DeviceNode
->Parent
!= ParentDeviceNode
)
2656 DPRINT("Skipping 2+ level child\n");
2657 return STATUS_SUCCESS
;
2660 if (!(DeviceNode
->Flags
& DNF_PROCESSED
))
2662 DPRINT1("Child not ready to be configured\n");
2663 return STATUS_SUCCESS
;
2666 if (!(DeviceNode
->Flags
& (DNF_DISABLED
| DNF_STARTED
| DNF_ADDED
)))
2668 WCHAR RegKeyBuffer
[MAX_PATH
];
2669 UNICODE_STRING RegKey
;
2671 /* Install the service for this if it's in the CDDB */
2672 IopInstallCriticalDevice(DeviceNode
);
2675 RegKey
.MaximumLength
= sizeof(RegKeyBuffer
);
2676 RegKey
.Buffer
= RegKeyBuffer
;
2679 * Retrieve configuration from Enum key
2682 Service
= &DeviceNode
->ServiceName
;
2684 RtlZeroMemory(QueryTable
, sizeof(QueryTable
));
2685 RtlInitUnicodeString(Service
, NULL
);
2686 RtlInitUnicodeString(&ClassGUID
, NULL
);
2688 QueryTable
[0].Name
= L
"Service";
2689 QueryTable
[0].Flags
= RTL_QUERY_REGISTRY_DIRECT
;
2690 QueryTable
[0].EntryContext
= Service
;
2692 QueryTable
[1].Name
= L
"ClassGUID";
2693 QueryTable
[1].Flags
= RTL_QUERY_REGISTRY_DIRECT
;
2694 QueryTable
[1].EntryContext
= &ClassGUID
;
2695 QueryTable
[1].DefaultType
= REG_SZ
;
2696 QueryTable
[1].DefaultData
= L
"";
2697 QueryTable
[1].DefaultLength
= 0;
2699 RtlAppendUnicodeToString(&RegKey
, L
"\\Registry\\Machine\\System\\CurrentControlSet\\Enum\\");
2700 RtlAppendUnicodeStringToString(&RegKey
, &DeviceNode
->InstancePath
);
2702 Status
= RtlQueryRegistryValues(RTL_REGISTRY_ABSOLUTE
,
2703 RegKey
.Buffer
, QueryTable
, NULL
, NULL
);
2705 if (!NT_SUCCESS(Status
))
2707 /* FIXME: Log the error */
2708 DPRINT("Could not retrieve configuration for device %wZ (Status 0x%08x)\n",
2709 &DeviceNode
->InstancePath
, Status
);
2710 IopDeviceNodeSetFlag(DeviceNode
, DNF_DISABLED
);
2711 return STATUS_SUCCESS
;
2714 if (Service
->Buffer
== NULL
)
2716 if (NT_SUCCESS(IopQueryDeviceCapabilities(DeviceNode
, &DeviceCaps
)) &&
2717 DeviceCaps
.RawDeviceOK
)
2719 DPRINT("%wZ is using parent bus driver (%wZ)\n", &DeviceNode
->InstancePath
, &ParentDeviceNode
->ServiceName
);
2721 DeviceNode
->ServiceName
.Length
= 0;
2722 DeviceNode
->ServiceName
.MaximumLength
= 0;
2723 DeviceNode
->ServiceName
.Buffer
= NULL
;
2725 else if (ClassGUID
.Length
!= 0)
2727 /* Device has a ClassGUID value, but no Service value.
2728 * Suppose it is using the NULL driver, so state the
2729 * device is started */
2730 DPRINT("%wZ is using NULL driver\n", &DeviceNode
->InstancePath
);
2731 IopDeviceNodeSetFlag(DeviceNode
, DNF_STARTED
);
2735 DeviceNode
->Problem
= CM_PROB_FAILED_INSTALL
;
2736 IopDeviceNodeSetFlag(DeviceNode
, DNF_DISABLED
);
2738 return STATUS_SUCCESS
;
2741 DPRINT("Got Service %S\n", Service
->Buffer
);
2744 return STATUS_SUCCESS
;
2748 * IopActionInitChildServices
2750 * Initialize the service for all (direct) child nodes of a parent node
2754 * Pointer to device node.
2756 * Pointer to parent node to initialize child node services for.
2759 * If the driver image for a service is not loaded and initialized
2760 * it is done here too. Any errors that occur are logged instead so
2761 * that all child services have a chance of being initialized.
2765 IopActionInitChildServices(PDEVICE_NODE DeviceNode
,
2768 PDEVICE_NODE ParentDeviceNode
;
2770 BOOLEAN BootDrivers
= !PnpSystemInit
;
2772 DPRINT("IopActionInitChildServices(%p, %p)\n", DeviceNode
, Context
);
2774 ParentDeviceNode
= Context
;
2777 * We are called for the parent too, but we don't need to do special
2778 * handling for this node
2780 if (DeviceNode
== ParentDeviceNode
)
2782 DPRINT("Success\n");
2783 return STATUS_SUCCESS
;
2787 * We don't want to check for a direct child because
2788 * this function is called during boot to reinitialize
2789 * devices with drivers that couldn't load yet due to
2790 * stage 0 limitations (ie can't load from disk yet).
2793 if (!(DeviceNode
->Flags
& DNF_PROCESSED
))
2795 DPRINT1("Child not ready to be added\n");
2796 return STATUS_SUCCESS
;
2799 if (IopDeviceNodeHasFlag(DeviceNode
, DNF_STARTED
) ||
2800 IopDeviceNodeHasFlag(DeviceNode
, DNF_ADDED
) ||
2801 IopDeviceNodeHasFlag(DeviceNode
, DNF_DISABLED
))
2802 return STATUS_SUCCESS
;
2804 if (DeviceNode
->ServiceName
.Buffer
== NULL
)
2806 /* We don't need to worry about loading the driver because we're
2807 * being driven in raw mode so our parent must be loaded to get here */
2808 Status
= IopInitializeDevice(DeviceNode
, NULL
);
2809 if (NT_SUCCESS(Status
))
2811 Status
= IopStartDevice(DeviceNode
);
2812 if (!NT_SUCCESS(Status
))
2814 DPRINT1("IopStartDevice(%wZ) failed with status 0x%08x\n",
2815 &DeviceNode
->InstancePath
, Status
);
2821 PLDR_DATA_TABLE_ENTRY ModuleObject
;
2822 PDRIVER_OBJECT DriverObject
;
2824 KeEnterCriticalRegion();
2825 ExAcquireResourceExclusiveLite(&IopDriverLoadResource
, TRUE
);
2826 /* Get existing DriverObject pointer (in case the driver has
2827 already been loaded and initialized) */
2828 Status
= IopGetDriverObject(
2830 &DeviceNode
->ServiceName
,
2833 if (!NT_SUCCESS(Status
))
2835 /* Driver is not initialized, try to load it */
2836 Status
= IopLoadServiceModule(&DeviceNode
->ServiceName
, &ModuleObject
);
2838 if (NT_SUCCESS(Status
) || Status
== STATUS_IMAGE_ALREADY_LOADED
)
2840 /* Initialize the driver */
2841 Status
= IopInitializeDriverModule(DeviceNode
, ModuleObject
,
2842 &DeviceNode
->ServiceName
, FALSE
, &DriverObject
);
2843 if (!NT_SUCCESS(Status
)) DeviceNode
->Problem
= CM_PROB_FAILED_DRIVER_ENTRY
;
2845 else if (Status
== STATUS_DRIVER_UNABLE_TO_LOAD
)
2847 DPRINT1("Service '%wZ' is disabled\n", &DeviceNode
->ServiceName
);
2848 DeviceNode
->Problem
= CM_PROB_DISABLED_SERVICE
;
2852 DPRINT("IopLoadServiceModule(%wZ) failed with status 0x%08x\n",
2853 &DeviceNode
->ServiceName
, Status
);
2854 if (!BootDrivers
) DeviceNode
->Problem
= CM_PROB_DRIVER_FAILED_LOAD
;
2857 ExReleaseResourceLite(&IopDriverLoadResource
);
2858 KeLeaveCriticalRegion();
2860 /* Driver is loaded and initialized at this point */
2861 if (NT_SUCCESS(Status
))
2863 /* Initialize the device, including all filters */
2864 Status
= PipCallDriverAddDevice(DeviceNode
, FALSE
, DriverObject
);
2866 /* Remove the extra reference */
2867 ObDereferenceObject(DriverObject
);
2872 * Don't disable when trying to load only boot drivers
2876 IopDeviceNodeSetFlag(DeviceNode
, DNF_DISABLED
);
2881 return STATUS_SUCCESS
;
2885 * IopInitializePnpServices
2887 * Initialize services for discovered children
2891 * Top device node to start initializing services.
2897 IopInitializePnpServices(IN PDEVICE_NODE DeviceNode
)
2899 DEVICETREE_TRAVERSE_CONTEXT Context
;
2901 DPRINT("IopInitializePnpServices(%p)\n", DeviceNode
);
2903 IopInitDeviceTreeTraverseContext(
2906 IopActionInitChildServices
,
2909 return IopTraverseDeviceTree(&Context
);
2912 static NTSTATUS INIT_FUNCTION
2913 IopEnumerateDetectedDevices(
2915 IN PUNICODE_STRING RelativePath OPTIONAL
,
2917 IN BOOLEAN EnumerateSubKeys
,
2918 IN PCM_FULL_RESOURCE_DESCRIPTOR ParentBootResources
,
2919 IN ULONG ParentBootResourcesLength
)
2921 UNICODE_STRING IdentifierU
= RTL_CONSTANT_STRING(L
"Identifier");
2922 UNICODE_STRING HardwareIDU
= RTL_CONSTANT_STRING(L
"HardwareID");
2923 UNICODE_STRING ConfigurationDataU
= RTL_CONSTANT_STRING(L
"Configuration Data");
2924 UNICODE_STRING BootConfigU
= RTL_CONSTANT_STRING(L
"BootConfig");
2925 UNICODE_STRING LogConfU
= RTL_CONSTANT_STRING(L
"LogConf");
2926 OBJECT_ATTRIBUTES ObjectAttributes
;
2927 HANDLE hDevicesKey
= NULL
;
2928 HANDLE hDeviceKey
= NULL
;
2929 HANDLE hLevel1Key
, hLevel2Key
= NULL
, hLogConf
;
2930 UNICODE_STRING Level2NameU
;
2931 WCHAR Level2Name
[5];
2932 ULONG IndexDevice
= 0;
2934 PKEY_BASIC_INFORMATION pDeviceInformation
= NULL
;
2935 ULONG DeviceInfoLength
= sizeof(KEY_BASIC_INFORMATION
) + 50 * sizeof(WCHAR
);
2936 PKEY_VALUE_PARTIAL_INFORMATION pValueInformation
= NULL
;
2937 ULONG ValueInfoLength
= sizeof(KEY_VALUE_PARTIAL_INFORMATION
) + 50 * sizeof(WCHAR
);
2938 UNICODE_STRING DeviceName
, ValueName
;
2940 PCM_FULL_RESOURCE_DESCRIPTOR BootResources
= NULL
;
2941 ULONG BootResourcesLength
;
2944 const UNICODE_STRING IdentifierSerial
= RTL_CONSTANT_STRING(L
"SerialController");
2945 UNICODE_STRING HardwareIdSerial
= RTL_CONSTANT_STRING(L
"*PNP0501\0");
2946 static ULONG DeviceIndexSerial
= 0;
2947 const UNICODE_STRING IdentifierKeyboard
= RTL_CONSTANT_STRING(L
"KeyboardController");
2948 UNICODE_STRING HardwareIdKeyboard
= RTL_CONSTANT_STRING(L
"*PNP0303\0");
2949 static ULONG DeviceIndexKeyboard
= 0;
2950 const UNICODE_STRING IdentifierMouse
= RTL_CONSTANT_STRING(L
"PointerController");
2951 UNICODE_STRING HardwareIdMouse
= RTL_CONSTANT_STRING(L
"*PNP0F13\0");
2952 static ULONG DeviceIndexMouse
= 0;
2953 const UNICODE_STRING IdentifierParallel
= RTL_CONSTANT_STRING(L
"ParallelController");
2954 UNICODE_STRING HardwareIdParallel
= RTL_CONSTANT_STRING(L
"*PNP0400\0");
2955 static ULONG DeviceIndexParallel
= 0;
2956 const UNICODE_STRING IdentifierFloppy
= RTL_CONSTANT_STRING(L
"FloppyDiskPeripheral");
2957 UNICODE_STRING HardwareIdFloppy
= RTL_CONSTANT_STRING(L
"*PNP0700\0");
2958 static ULONG DeviceIndexFloppy
= 0;
2959 UNICODE_STRING HardwareIdKey
;
2960 PUNICODE_STRING pHardwareId
;
2961 ULONG DeviceIndex
= 0;
2962 PUCHAR CmResourceList
;
2967 Status
= IopOpenRegistryKeyEx(&hDevicesKey
, hBaseKey
, RelativePath
, KEY_ENUMERATE_SUB_KEYS
);
2968 if (!NT_SUCCESS(Status
))
2970 DPRINT("ZwOpenKey() failed with status 0x%08lx\n", Status
);
2975 hDevicesKey
= hBaseKey
;
2977 pDeviceInformation
= ExAllocatePool(PagedPool
, DeviceInfoLength
);
2978 if (!pDeviceInformation
)
2980 DPRINT("ExAllocatePool() failed\n");
2981 Status
= STATUS_NO_MEMORY
;
2985 pValueInformation
= ExAllocatePool(PagedPool
, ValueInfoLength
);
2986 if (!pValueInformation
)
2988 DPRINT("ExAllocatePool() failed\n");
2989 Status
= STATUS_NO_MEMORY
;
2995 Status
= ZwEnumerateKey(hDevicesKey
, IndexDevice
, KeyBasicInformation
, pDeviceInformation
, DeviceInfoLength
, &RequiredSize
);
2996 if (Status
== STATUS_NO_MORE_ENTRIES
)
2998 else if (Status
== STATUS_BUFFER_OVERFLOW
|| Status
== STATUS_BUFFER_TOO_SMALL
)
3000 ExFreePool(pDeviceInformation
);
3001 DeviceInfoLength
= RequiredSize
;
3002 pDeviceInformation
= ExAllocatePool(PagedPool
, DeviceInfoLength
);
3003 if (!pDeviceInformation
)
3005 DPRINT("ExAllocatePool() failed\n");
3006 Status
= STATUS_NO_MEMORY
;
3009 Status
= ZwEnumerateKey(hDevicesKey
, IndexDevice
, KeyBasicInformation
, pDeviceInformation
, DeviceInfoLength
, &RequiredSize
);
3011 if (!NT_SUCCESS(Status
))
3013 DPRINT("ZwEnumerateKey() failed with status 0x%08lx\n", Status
);
3018 /* Open device key */
3019 DeviceName
.Length
= DeviceName
.MaximumLength
= (USHORT
)pDeviceInformation
->NameLength
;
3020 DeviceName
.Buffer
= pDeviceInformation
->Name
;
3022 Status
= IopOpenRegistryKeyEx(&hDeviceKey
, hDevicesKey
, &DeviceName
,
3023 KEY_QUERY_VALUE
+ (EnumerateSubKeys
? KEY_ENUMERATE_SUB_KEYS
: 0));
3024 if (!NT_SUCCESS(Status
))
3026 DPRINT("ZwOpenKey() failed with status 0x%08lx\n", Status
);
3030 /* Read boot resources, and add then to parent ones */
3031 Status
= ZwQueryValueKey(hDeviceKey
, &ConfigurationDataU
, KeyValuePartialInformation
, pValueInformation
, ValueInfoLength
, &RequiredSize
);
3032 if (Status
== STATUS_BUFFER_OVERFLOW
|| Status
== STATUS_BUFFER_TOO_SMALL
)
3034 ExFreePool(pValueInformation
);
3035 ValueInfoLength
= RequiredSize
;
3036 pValueInformation
= ExAllocatePool(PagedPool
, ValueInfoLength
);
3037 if (!pValueInformation
)
3039 DPRINT("ExAllocatePool() failed\n");
3040 ZwDeleteKey(hLevel2Key
);
3041 Status
= STATUS_NO_MEMORY
;
3044 Status
= ZwQueryValueKey(hDeviceKey
, &ConfigurationDataU
, KeyValuePartialInformation
, pValueInformation
, ValueInfoLength
, &RequiredSize
);
3046 if (Status
== STATUS_OBJECT_NAME_NOT_FOUND
)
3048 BootResources
= ParentBootResources
;
3049 BootResourcesLength
= ParentBootResourcesLength
;
3051 else if (!NT_SUCCESS(Status
))
3053 DPRINT("ZwQueryValueKey() failed with status 0x%08lx\n", Status
);
3056 else if (pValueInformation
->Type
!= REG_FULL_RESOURCE_DESCRIPTOR
)
3058 DPRINT("Wrong registry type: got 0x%lx, expected 0x%lx\n", pValueInformation
->Type
, REG_FULL_RESOURCE_DESCRIPTOR
);
3063 static const ULONG Header
= FIELD_OFFSET(CM_FULL_RESOURCE_DESCRIPTOR
, PartialResourceList
.PartialDescriptors
);
3065 /* Concatenate current resources and parent ones */
3066 if (ParentBootResourcesLength
== 0)
3067 BootResourcesLength
= pValueInformation
->DataLength
;
3069 BootResourcesLength
= ParentBootResourcesLength
3070 + pValueInformation
->DataLength
3072 BootResources
= ExAllocatePool(PagedPool
, BootResourcesLength
);
3075 DPRINT("ExAllocatePool() failed\n");
3078 if (ParentBootResourcesLength
< sizeof(CM_FULL_RESOURCE_DESCRIPTOR
))
3080 RtlCopyMemory(BootResources
, pValueInformation
->Data
, pValueInformation
->DataLength
);
3082 else if (ParentBootResources
->PartialResourceList
.PartialDescriptors
[ParentBootResources
->PartialResourceList
.Count
- 1].Type
== CmResourceTypeDeviceSpecific
)
3084 RtlCopyMemory(BootResources
, pValueInformation
->Data
, pValueInformation
->DataLength
);
3086 (PVOID
)((ULONG_PTR
)BootResources
+ pValueInformation
->DataLength
),
3087 (PVOID
)((ULONG_PTR
)ParentBootResources
+ Header
),
3088 ParentBootResourcesLength
- Header
);
3089 BootResources
->PartialResourceList
.Count
+= ParentBootResources
->PartialResourceList
.Count
;
3093 RtlCopyMemory(BootResources
, pValueInformation
->Data
, Header
);
3095 (PVOID
)((ULONG_PTR
)BootResources
+ Header
),
3096 (PVOID
)((ULONG_PTR
)ParentBootResources
+ Header
),
3097 ParentBootResourcesLength
- Header
);
3099 (PVOID
)((ULONG_PTR
)BootResources
+ ParentBootResourcesLength
),
3100 pValueInformation
->Data
+ Header
,
3101 pValueInformation
->DataLength
- Header
);
3102 BootResources
->PartialResourceList
.Count
+= ParentBootResources
->PartialResourceList
.Count
;
3106 if (EnumerateSubKeys
)
3111 Status
= ZwEnumerateKey(hDeviceKey
, IndexSubKey
, KeyBasicInformation
, pDeviceInformation
, DeviceInfoLength
, &RequiredSize
);
3112 if (Status
== STATUS_NO_MORE_ENTRIES
)
3114 else if (Status
== STATUS_BUFFER_OVERFLOW
|| Status
== STATUS_BUFFER_TOO_SMALL
)
3116 ExFreePool(pDeviceInformation
);
3117 DeviceInfoLength
= RequiredSize
;
3118 pDeviceInformation
= ExAllocatePool(PagedPool
, DeviceInfoLength
);
3119 if (!pDeviceInformation
)
3121 DPRINT("ExAllocatePool() failed\n");
3122 Status
= STATUS_NO_MEMORY
;
3125 Status
= ZwEnumerateKey(hDeviceKey
, IndexSubKey
, KeyBasicInformation
, pDeviceInformation
, DeviceInfoLength
, &RequiredSize
);
3127 if (!NT_SUCCESS(Status
))
3129 DPRINT("ZwEnumerateKey() failed with status 0x%08lx\n", Status
);
3133 DeviceName
.Length
= DeviceName
.MaximumLength
= (USHORT
)pDeviceInformation
->NameLength
;
3134 DeviceName
.Buffer
= pDeviceInformation
->Name
;
3136 Status
= IopEnumerateDetectedDevices(
3142 BootResourcesLength
);
3143 if (!NT_SUCCESS(Status
))
3148 /* Read identifier */
3149 Status
= ZwQueryValueKey(hDeviceKey
, &IdentifierU
, KeyValuePartialInformation
, pValueInformation
, ValueInfoLength
, &RequiredSize
);
3150 if (Status
== STATUS_BUFFER_OVERFLOW
|| Status
== STATUS_BUFFER_TOO_SMALL
)
3152 ExFreePool(pValueInformation
);
3153 ValueInfoLength
= RequiredSize
;
3154 pValueInformation
= ExAllocatePool(PagedPool
, ValueInfoLength
);
3155 if (!pValueInformation
)
3157 DPRINT("ExAllocatePool() failed\n");
3158 Status
= STATUS_NO_MEMORY
;
3161 Status
= ZwQueryValueKey(hDeviceKey
, &IdentifierU
, KeyValuePartialInformation
, pValueInformation
, ValueInfoLength
, &RequiredSize
);
3163 if (!NT_SUCCESS(Status
))
3165 if (Status
!= STATUS_OBJECT_NAME_NOT_FOUND
)
3167 DPRINT("ZwQueryValueKey() failed with status 0x%08lx\n", Status
);
3170 ValueName
.Length
= ValueName
.MaximumLength
= 0;
3172 else if (pValueInformation
->Type
!= REG_SZ
)
3174 DPRINT("Wrong registry type: got 0x%lx, expected 0x%lx\n", pValueInformation
->Type
, REG_SZ
);
3179 /* Assign hardware id to this device */
3180 ValueName
.Length
= ValueName
.MaximumLength
= (USHORT
)pValueInformation
->DataLength
;
3181 ValueName
.Buffer
= (PWCHAR
)pValueInformation
->Data
;
3182 if (ValueName
.Length
>= sizeof(WCHAR
) && ValueName
.Buffer
[ValueName
.Length
/ sizeof(WCHAR
) - 1] == UNICODE_NULL
)
3183 ValueName
.Length
-= sizeof(WCHAR
);
3186 if (RelativePath
&& RtlCompareUnicodeString(RelativePath
, &IdentifierSerial
, FALSE
) == 0)
3188 pHardwareId
= &HardwareIdSerial
;
3189 DeviceIndex
= DeviceIndexSerial
++;
3191 else if (RelativePath
&& RtlCompareUnicodeString(RelativePath
, &IdentifierKeyboard
, FALSE
) == 0)
3193 pHardwareId
= &HardwareIdKeyboard
;
3194 DeviceIndex
= DeviceIndexKeyboard
++;
3196 else if (RelativePath
&& RtlCompareUnicodeString(RelativePath
, &IdentifierMouse
, FALSE
) == 0)
3198 pHardwareId
= &HardwareIdMouse
;
3199 DeviceIndex
= DeviceIndexMouse
++;
3201 else if (RelativePath
&& RtlCompareUnicodeString(RelativePath
, &IdentifierParallel
, FALSE
) == 0)
3203 pHardwareId
= &HardwareIdParallel
;
3204 DeviceIndex
= DeviceIndexParallel
++;
3206 else if (RelativePath
&& RtlCompareUnicodeString(RelativePath
, &IdentifierFloppy
, FALSE
) == 0)
3208 pHardwareId
= &HardwareIdFloppy
;
3209 DeviceIndex
= DeviceIndexFloppy
++;
3213 /* Unknown key path */
3214 DPRINT("Unknown key path '%wZ'\n", RelativePath
);
3218 /* Prepare hardware id key (hardware id value without final \0) */
3219 HardwareIdKey
= *pHardwareId
;
3220 HardwareIdKey
.Length
-= sizeof(UNICODE_NULL
);
3222 /* Add the detected device to Root key */
3223 InitializeObjectAttributes(&ObjectAttributes
, &HardwareIdKey
, OBJ_KERNEL_HANDLE
, hRootKey
, NULL
);
3224 Status
= ZwCreateKey(
3230 ExpInTextModeSetup
? REG_OPTION_VOLATILE
: 0,
3232 if (!NT_SUCCESS(Status
))
3234 DPRINT("ZwCreateKey() failed with status 0x%08lx\n", Status
);
3237 swprintf(Level2Name
, L
"%04lu", DeviceIndex
);
3238 RtlInitUnicodeString(&Level2NameU
, Level2Name
);
3239 InitializeObjectAttributes(&ObjectAttributes
, &Level2NameU
, OBJ_KERNEL_HANDLE
, hLevel1Key
, NULL
);
3240 Status
= ZwCreateKey(
3242 KEY_SET_VALUE
| KEY_CREATE_SUB_KEY
,
3246 ExpInTextModeSetup
? REG_OPTION_VOLATILE
: 0,
3248 ZwClose(hLevel1Key
);
3249 if (!NT_SUCCESS(Status
))
3251 DPRINT("ZwCreateKey() failed with status 0x%08lx\n", Status
);
3254 DPRINT("Found %wZ #%lu (%wZ)\n", &ValueName
, DeviceIndex
, &HardwareIdKey
);
3255 Status
= ZwSetValueKey(hLevel2Key
, &HardwareIDU
, 0, REG_MULTI_SZ
, pHardwareId
->Buffer
, pHardwareId
->MaximumLength
);
3256 if (!NT_SUCCESS(Status
))
3258 DPRINT("ZwSetValueKey() failed with status 0x%08lx\n", Status
);
3259 ZwDeleteKey(hLevel2Key
);
3262 /* Create 'LogConf' subkey */
3263 InitializeObjectAttributes(&ObjectAttributes
, &LogConfU
, OBJ_KERNEL_HANDLE
, hLevel2Key
, NULL
);
3264 Status
= ZwCreateKey(
3270 REG_OPTION_VOLATILE
,
3272 if (!NT_SUCCESS(Status
))
3274 DPRINT("ZwCreateKey() failed with status 0x%08lx\n", Status
);
3275 ZwDeleteKey(hLevel2Key
);
3278 if (BootResourcesLength
>= sizeof(CM_FULL_RESOURCE_DESCRIPTOR
))
3280 CmResourceList
= ExAllocatePool(PagedPool
, BootResourcesLength
+ sizeof(ULONG
));
3281 if (!CmResourceList
)
3284 ZwDeleteKey(hLevel2Key
);
3288 /* Add the list count (1st member of CM_RESOURCE_LIST) */
3290 RtlCopyMemory(CmResourceList
,
3294 /* Now add the actual list (2nd member of CM_RESOURCE_LIST) */
3295 RtlCopyMemory(CmResourceList
+ sizeof(ULONG
),
3297 BootResourcesLength
);
3299 /* Save boot resources to 'LogConf\BootConfig' */
3300 Status
= ZwSetValueKey(hLogConf
, &BootConfigU
, 0, REG_RESOURCE_LIST
, CmResourceList
, BootResourcesLength
+ sizeof(ULONG
));
3301 if (!NT_SUCCESS(Status
))
3303 DPRINT("ZwSetValueKey() failed with status 0x%08lx\n", Status
);
3305 ZwDeleteKey(hLevel2Key
);
3312 if (BootResources
&& BootResources
!= ParentBootResources
)
3314 ExFreePool(BootResources
);
3315 BootResources
= NULL
;
3319 ZwClose(hLevel2Key
);
3324 ZwClose(hDeviceKey
);
3329 Status
= STATUS_SUCCESS
;
3332 if (hDevicesKey
&& hDevicesKey
!= hBaseKey
)
3333 ZwClose(hDevicesKey
);
3335 ZwClose(hDeviceKey
);
3336 if (pDeviceInformation
)
3337 ExFreePool(pDeviceInformation
);
3338 if (pValueInformation
)
3339 ExFreePool(pValueInformation
);
3343 static BOOLEAN INIT_FUNCTION
3344 IopIsFirmwareMapperDisabled(VOID
)
3346 UNICODE_STRING KeyPathU
= RTL_CONSTANT_STRING(L
"\\Registry\\Machine\\SYSTEM\\CURRENTCONTROLSET\\Control\\Pnp");
3347 UNICODE_STRING KeyNameU
= RTL_CONSTANT_STRING(L
"DisableFirmwareMapper");
3348 OBJECT_ATTRIBUTES ObjectAttributes
;
3350 PKEY_VALUE_PARTIAL_INFORMATION KeyInformation
;
3351 ULONG DesiredLength
, Length
;
3355 InitializeObjectAttributes(&ObjectAttributes
, &KeyPathU
, OBJ_KERNEL_HANDLE
| OBJ_CASE_INSENSITIVE
, NULL
, NULL
);
3356 Status
= ZwOpenKey(&hPnpKey
, KEY_QUERY_VALUE
, &ObjectAttributes
);
3357 if (NT_SUCCESS(Status
))
3359 Status
= ZwQueryValueKey(hPnpKey
,
3361 KeyValuePartialInformation
,
3365 if ((Status
== STATUS_BUFFER_TOO_SMALL
) ||
3366 (Status
== STATUS_BUFFER_OVERFLOW
))
3368 Length
= DesiredLength
;
3369 KeyInformation
= ExAllocatePool(PagedPool
, Length
);
3372 Status
= ZwQueryValueKey(hPnpKey
,
3374 KeyValuePartialInformation
,
3378 if (NT_SUCCESS(Status
) && KeyInformation
->DataLength
== sizeof(ULONG
))
3380 KeyValue
= (ULONG
)(*KeyInformation
->Data
);
3384 DPRINT1("ZwQueryValueKey(%wZ%wZ) failed\n", &KeyPathU
, &KeyNameU
);
3387 ExFreePool(KeyInformation
);
3391 DPRINT1("Failed to allocate memory for registry query\n");
3396 DPRINT1("ZwQueryValueKey(%wZ%wZ) failed with status 0x%08lx\n", &KeyPathU
, &KeyNameU
, Status
);
3403 DPRINT1("ZwOpenKey(%wZ) failed with status 0x%08lx\n", &KeyPathU
, Status
);
3406 DPRINT("Firmware mapper is %s\n", KeyValue
!= 0 ? "disabled" : "enabled");
3408 return (KeyValue
!= 0) ? TRUE
: FALSE
;
3414 IopUpdateRootKey(VOID
)
3416 UNICODE_STRING EnumU
= RTL_CONSTANT_STRING(L
"\\Registry\\Machine\\SYSTEM\\CurrentControlSet\\Enum");
3417 UNICODE_STRING RootPathU
= RTL_CONSTANT_STRING(L
"Root");
3418 UNICODE_STRING MultiKeyPathU
= RTL_CONSTANT_STRING(L
"\\Registry\\Machine\\HARDWARE\\DESCRIPTION\\System\\MultifunctionAdapter");
3419 OBJECT_ATTRIBUTES ObjectAttributes
;
3420 HANDLE hEnum
, hRoot
;
3423 InitializeObjectAttributes(&ObjectAttributes
, &EnumU
, OBJ_KERNEL_HANDLE
| OBJ_CASE_INSENSITIVE
, NULL
, NULL
);
3424 Status
= ZwCreateKey(&hEnum
, KEY_CREATE_SUB_KEY
, &ObjectAttributes
, 0, NULL
, 0, NULL
);
3425 if (!NT_SUCCESS(Status
))
3427 DPRINT1("ZwCreateKey() failed with status 0x%08lx\n", Status
);
3431 InitializeObjectAttributes(&ObjectAttributes
, &RootPathU
, OBJ_KERNEL_HANDLE
| OBJ_CASE_INSENSITIVE
, hEnum
, NULL
);
3432 Status
= ZwCreateKey(&hRoot
, KEY_CREATE_SUB_KEY
, &ObjectAttributes
, 0, NULL
, 0, NULL
);
3434 if (!NT_SUCCESS(Status
))
3436 DPRINT1("ZwOpenKey() failed with status 0x%08lx\n", Status
);
3440 if (!IopIsFirmwareMapperDisabled())
3442 Status
= IopOpenRegistryKeyEx(&hEnum
, NULL
, &MultiKeyPathU
, KEY_ENUMERATE_SUB_KEYS
);
3443 if (!NT_SUCCESS(Status
))
3445 /* Nothing to do, don't return with an error status */
3446 DPRINT("ZwOpenKey() failed with status 0x%08lx\n", Status
);
3448 return STATUS_SUCCESS
;
3450 Status
= IopEnumerateDetectedDevices(
3461 /* Enumeration is disabled */
3462 Status
= STATUS_SUCCESS
;
3472 IopOpenRegistryKeyEx(PHANDLE KeyHandle
,
3474 PUNICODE_STRING Name
,
3475 ACCESS_MASK DesiredAccess
)
3477 OBJECT_ATTRIBUTES ObjectAttributes
;
3484 InitializeObjectAttributes(&ObjectAttributes
,
3486 OBJ_CASE_INSENSITIVE
| OBJ_KERNEL_HANDLE
,
3490 Status
= ZwOpenKey(KeyHandle
, DesiredAccess
, &ObjectAttributes
);
3497 IopCreateRegistryKeyEx(OUT PHANDLE Handle
,
3498 IN HANDLE RootHandle OPTIONAL
,
3499 IN PUNICODE_STRING KeyName
,
3500 IN ACCESS_MASK DesiredAccess
,
3501 IN ULONG CreateOptions
,
3502 OUT PULONG Disposition OPTIONAL
)
3504 OBJECT_ATTRIBUTES ObjectAttributes
;
3505 ULONG KeyDisposition
, RootHandleIndex
= 0, i
= 1, NestedCloseLevel
= 0;
3507 HANDLE HandleArray
[2];
3508 BOOLEAN Recursing
= TRUE
;
3510 UNICODE_STRING KeyString
;
3511 NTSTATUS Status
= STATUS_SUCCESS
;
3514 /* P1 is start, pp is end */
3515 p1
= KeyName
->Buffer
;
3516 pp
= (PVOID
)((ULONG_PTR
)p1
+ KeyName
->Length
);
3518 /* Create the target key */
3519 InitializeObjectAttributes(&ObjectAttributes
,
3521 OBJ_CASE_INSENSITIVE
| OBJ_KERNEL_HANDLE
,
3524 Status
= ZwCreateKey(&HandleArray
[i
],
3532 /* Now we check if this failed */
3533 if ((Status
== STATUS_OBJECT_NAME_NOT_FOUND
) && (RootHandle
))
3535 /* Target key failed, so we'll need to create its parent. Setup array */
3536 HandleArray
[0] = NULL
;
3537 HandleArray
[1] = RootHandle
;
3539 /* Keep recursing for each missing parent */
3542 /* And if we're deep enough, close the last handle */
3543 if (NestedCloseLevel
> 1) ZwClose(HandleArray
[RootHandleIndex
]);
3545 /* We're setup to ping-pong between the two handle array entries */
3546 RootHandleIndex
= i
;
3549 /* Clear the one we're attempting to open now */
3550 HandleArray
[i
] = NULL
;
3552 /* Process the parent key name */
3553 for (p
= p1
; ((p
< pp
) && (*p
!= OBJ_NAME_PATH_SEPARATOR
)); p
++);
3554 Length
= (USHORT
)(p
- p1
) * sizeof(WCHAR
);
3556 /* Is there a parent name? */
3559 /* Build the unicode string for it */
3560 KeyString
.Buffer
= p1
;
3561 KeyString
.Length
= KeyString
.MaximumLength
= Length
;
3563 /* Now try opening the parent */
3564 InitializeObjectAttributes(&ObjectAttributes
,
3566 OBJ_CASE_INSENSITIVE
| OBJ_KERNEL_HANDLE
,
3567 HandleArray
[RootHandleIndex
],
3569 Status
= ZwCreateKey(&HandleArray
[i
],
3576 if (NT_SUCCESS(Status
))
3578 /* It worked, we have one more handle */
3583 /* Parent key creation failed, abandon loop */
3590 /* We don't have a parent name, probably corrupted key name */
3591 Status
= STATUS_INVALID_PARAMETER
;
3596 /* Now see if there's more parents to create */
3598 if ((p
== pp
) || (p1
== pp
))
3600 /* We're done, hopefully successfully, so stop */
3605 /* Outer loop check for handle nesting that requires closing the top handle */
3606 if (NestedCloseLevel
> 1) ZwClose(HandleArray
[RootHandleIndex
]);
3609 /* Check if we broke out of the loop due to success */
3610 if (NT_SUCCESS(Status
))
3612 /* Return the target handle (we closed all the parent ones) and disposition */
3613 *Handle
= HandleArray
[i
];
3614 if (Disposition
) *Disposition
= KeyDisposition
;
3617 /* Return the success state */
3623 IopGetRegistryValue(IN HANDLE Handle
,
3625 OUT PKEY_VALUE_FULL_INFORMATION
*Information
)
3627 UNICODE_STRING ValueString
;
3629 PKEY_VALUE_FULL_INFORMATION FullInformation
;
3633 RtlInitUnicodeString(&ValueString
, ValueName
);
3635 Status
= ZwQueryValueKey(Handle
,
3637 KeyValueFullInformation
,
3641 if ((Status
!= STATUS_BUFFER_OVERFLOW
) &&
3642 (Status
!= STATUS_BUFFER_TOO_SMALL
))
3647 FullInformation
= ExAllocatePool(NonPagedPool
, Size
);
3648 if (!FullInformation
) return STATUS_INSUFFICIENT_RESOURCES
;
3650 Status
= ZwQueryValueKey(Handle
,
3652 KeyValueFullInformation
,
3656 if (!NT_SUCCESS(Status
))
3658 ExFreePool(FullInformation
);
3662 *Information
= FullInformation
;
3663 return STATUS_SUCCESS
;
3666 RTL_GENERIC_COMPARE_RESULTS
3668 PiCompareInstancePath(IN PRTL_AVL_TABLE Table
,
3669 IN PVOID FirstStruct
,
3670 IN PVOID SecondStruct
)
3678 // The allocation function is called by the generic table package whenever
3679 // it needs to allocate memory for the table.
3684 PiAllocateGenericTableEntry(IN PRTL_AVL_TABLE Table
,
3694 PiFreeGenericTableEntry(IN PRTL_AVL_TABLE Table
,
3703 PpInitializeDeviceReferenceTable(VOID
)
3705 /* Setup the guarded mutex and AVL table */
3706 KeInitializeGuardedMutex(&PpDeviceReferenceTableLock
);
3707 RtlInitializeGenericTableAvl(
3708 &PpDeviceReferenceTable
,
3709 (PRTL_AVL_COMPARE_ROUTINE
)PiCompareInstancePath
,
3710 (PRTL_AVL_ALLOCATE_ROUTINE
)PiAllocateGenericTableEntry
,
3711 (PRTL_AVL_FREE_ROUTINE
)PiFreeGenericTableEntry
,
3719 /* Initialize the resource when accessing device registry data */
3720 ExInitializeResourceLite(&PpRegistryDeviceResource
);
3722 /* Setup the device reference AVL table */
3723 PpInitializeDeviceReferenceTable();
3731 /* Check the initialization phase */
3732 switch (ExpInitializationPhase
)
3737 return PiInitPhase0();
3743 //return PiInitPhase1();
3747 /* Don't know any other phase! Bugcheck! */
3748 KeBugCheck(UNEXPECTED_INITIALIZATION_CALL
);
3753 LONG IopNumberDeviceNodes
;
3757 PipAllocateDeviceNode(IN PDEVICE_OBJECT PhysicalDeviceObject
)
3759 PDEVICE_NODE DeviceNode
;
3763 DeviceNode
= ExAllocatePoolWithTag(NonPagedPool
, sizeof(DEVICE_NODE
), TAG_IO_DEVNODE
);
3764 if (!DeviceNode
) return DeviceNode
;
3767 InterlockedIncrement(&IopNumberDeviceNodes
);
3770 RtlZeroMemory(DeviceNode
, sizeof(DEVICE_NODE
));
3771 DeviceNode
->InterfaceType
= InterfaceTypeUndefined
;
3772 DeviceNode
->BusNumber
= -1;
3773 DeviceNode
->ChildInterfaceType
= InterfaceTypeUndefined
;
3774 DeviceNode
->ChildBusNumber
= -1;
3775 DeviceNode
->ChildBusTypeIndex
= -1;
3776 // KeInitializeEvent(&DeviceNode->EnumerationMutex, SynchronizationEvent, TRUE);
3777 InitializeListHead(&DeviceNode
->DeviceArbiterList
);
3778 InitializeListHead(&DeviceNode
->DeviceTranslatorList
);
3779 InitializeListHead(&DeviceNode
->TargetDeviceNotify
);
3780 InitializeListHead(&DeviceNode
->DockInfo
.ListEntry
);
3781 InitializeListHead(&DeviceNode
->PendedSetInterfaceState
);
3783 /* Check if there is a PDO */
3784 if (PhysicalDeviceObject
)
3786 /* Link it and remove the init flag */
3787 DeviceNode
->PhysicalDeviceObject
= PhysicalDeviceObject
;
3788 ((PEXTENDED_DEVOBJ_EXTENSION
)PhysicalDeviceObject
->DeviceObjectExtension
)->DeviceNode
= DeviceNode
;
3789 PhysicalDeviceObject
->Flags
&= ~DO_DEVICE_INITIALIZING
;
3792 /* Return the node */
3796 /* PUBLIC FUNCTIONS **********************************************************/
3800 PnpBusTypeGuidGet(IN USHORT Index
,
3801 IN LPGUID BusTypeGuid
)
3803 NTSTATUS Status
= STATUS_SUCCESS
;
3805 /* Acquire the lock */
3806 ExAcquireFastMutex(&PnpBusTypeGuidList
->Lock
);
3809 if (Index
< PnpBusTypeGuidList
->GuidCount
)
3812 RtlCopyMemory(BusTypeGuid
, &PnpBusTypeGuidList
->Guids
[Index
], sizeof(GUID
));
3817 Status
= STATUS_OBJECT_NAME_NOT_FOUND
;
3820 /* Release lock and return status */
3821 ExReleaseFastMutex(&PnpBusTypeGuidList
->Lock
);
3827 PnpDeviceObjectToDeviceInstance(IN PDEVICE_OBJECT DeviceObject
,
3828 IN PHANDLE DeviceInstanceHandle
,
3829 IN ACCESS_MASK DesiredAccess
)
3833 PDEVICE_NODE DeviceNode
;
3834 UNICODE_STRING KeyName
= RTL_CONSTANT_STRING(L
"\\REGISTRY\\MACHINE\\SYSTEM\\CURRENTCONTROLSET\\ENUM");
3837 /* Open the enum key */
3838 Status
= IopOpenRegistryKeyEx(&KeyHandle
,
3842 if (!NT_SUCCESS(Status
)) return Status
;
3844 /* Make sure we have an instance path */
3845 DeviceNode
= IopGetDeviceNode(DeviceObject
);
3846 if ((DeviceNode
) && (DeviceNode
->InstancePath
.Length
))
3848 /* Get the instance key */
3849 Status
= IopOpenRegistryKeyEx(DeviceInstanceHandle
,
3851 &DeviceNode
->InstancePath
,
3857 Status
= STATUS_INVALID_DEVICE_REQUEST
;
3860 /* Close the handle and return status */
3867 PnpDetermineResourceListSize(IN PCM_RESOURCE_LIST ResourceList
)
3869 ULONG FinalSize
, PartialSize
, EntrySize
, i
, j
;
3870 PCM_FULL_RESOURCE_DESCRIPTOR FullDescriptor
;
3871 PCM_PARTIAL_RESOURCE_DESCRIPTOR PartialDescriptor
;
3873 /* If we don't have one, that's easy */
3874 if (!ResourceList
) return 0;
3876 /* Start with the minimum size possible */
3877 FinalSize
= FIELD_OFFSET(CM_RESOURCE_LIST
, List
);
3879 /* Loop each full descriptor */
3880 FullDescriptor
= ResourceList
->List
;
3881 for (i
= 0; i
< ResourceList
->Count
; i
++)
3883 /* Start with the minimum size possible */
3884 PartialSize
= FIELD_OFFSET(CM_FULL_RESOURCE_DESCRIPTOR
, PartialResourceList
) +
3885 FIELD_OFFSET(CM_PARTIAL_RESOURCE_LIST
, PartialDescriptors
);
3887 /* Loop each partial descriptor */
3888 PartialDescriptor
= FullDescriptor
->PartialResourceList
.PartialDescriptors
;
3889 for (j
= 0; j
< FullDescriptor
->PartialResourceList
.Count
; j
++)
3891 /* Start with the minimum size possible */
3892 EntrySize
= sizeof(CM_PARTIAL_RESOURCE_DESCRIPTOR
);
3894 /* Check if there is extra data */
3895 if (PartialDescriptor
->Type
== CmResourceTypeDeviceSpecific
)
3898 EntrySize
+= PartialDescriptor
->u
.DeviceSpecificData
.DataSize
;
3901 /* The size of partial descriptors is bigger */
3902 PartialSize
+= EntrySize
;
3904 /* Go to the next partial descriptor */
3905 PartialDescriptor
= (PVOID
)((ULONG_PTR
)PartialDescriptor
+ EntrySize
);
3908 /* The size of full descriptors is bigger */
3909 FinalSize
+= PartialSize
;
3911 /* Go to the next full descriptor */
3912 FullDescriptor
= (PVOID
)((ULONG_PTR
)FullDescriptor
+ PartialSize
);
3915 /* Return the final size */
3921 PiGetDeviceRegistryProperty(IN PDEVICE_OBJECT DeviceObject
,
3926 IN PULONG BufferLength
)
3929 HANDLE KeyHandle
, SubHandle
;
3930 UNICODE_STRING KeyString
;
3931 PKEY_VALUE_FULL_INFORMATION KeyValueInfo
= NULL
;
3935 /* Find the instance key */
3936 Status
= PnpDeviceObjectToDeviceInstance(DeviceObject
, &KeyHandle
, KEY_READ
);
3937 if (NT_SUCCESS(Status
))
3939 /* Check for name given by caller */
3943 RtlInitUnicodeString(&KeyString
, KeyName
);
3944 Status
= IopOpenRegistryKeyEx(&SubHandle
,
3948 if (NT_SUCCESS(Status
))
3950 /* And use this handle instead */
3952 KeyHandle
= SubHandle
;
3956 /* Check if sub-key handle succeeded (or no-op if no key name given) */
3957 if (NT_SUCCESS(Status
))
3959 /* Now get the size of the property */
3960 Status
= IopGetRegistryValue(KeyHandle
,
3969 /* Fail if any of the registry operations failed */
3970 if (!NT_SUCCESS(Status
)) return Status
;
3972 /* Check how much data we have to copy */
3973 Length
= KeyValueInfo
->DataLength
;
3974 if (*BufferLength
>= Length
)
3976 /* Check for a match in the value type */
3977 if (KeyValueInfo
->Type
== ValueType
)
3980 RtlCopyMemory(Buffer
,
3981 (PVOID
)((ULONG_PTR
)KeyValueInfo
+
3982 KeyValueInfo
->DataOffset
),
3987 /* Invalid registry property type, fail */
3988 Status
= STATUS_INVALID_PARAMETER_2
;
3993 /* Buffer is too small to hold data */
3994 Status
= STATUS_BUFFER_TOO_SMALL
;
3997 /* Return the required buffer length, free the buffer, and return status */
3998 *BufferLength
= Length
;
3999 ExFreePool(KeyValueInfo
);
4003 #define PIP_RETURN_DATA(x, y) {ReturnLength = x; Data = y; Status = STATUS_SUCCESS; break;}
4004 #define PIP_REGISTRY_DATA(x, y) {ValueName = x; ValueType = y; break;}
4005 #define PIP_UNIMPLEMENTED() {UNIMPLEMENTED_DBGBREAK(); break;}
4012 IoGetDeviceProperty(IN PDEVICE_OBJECT DeviceObject
,
4013 IN DEVICE_REGISTRY_PROPERTY DeviceProperty
,
4014 IN ULONG BufferLength
,
4015 OUT PVOID PropertyBuffer
,
4016 OUT PULONG ResultLength
)
4018 PDEVICE_NODE DeviceNode
= IopGetDeviceNode(DeviceObject
);
4019 DEVICE_CAPABILITIES DeviceCaps
;
4020 ULONG ReturnLength
= 0, Length
= 0, ValueType
;
4021 PWCHAR ValueName
= NULL
, EnumeratorNameEnd
, DeviceInstanceName
;
4023 NTSTATUS Status
= STATUS_BUFFER_TOO_SMALL
;
4025 POBJECT_NAME_INFORMATION ObjectNameInfo
= NULL
;
4026 BOOLEAN NullTerminate
= FALSE
;
4028 DPRINT("IoGetDeviceProperty(0x%p %d)\n", DeviceObject
, DeviceProperty
);
4030 /* Assume failure */
4033 /* Only PDOs can call this */
4034 if (!DeviceNode
) return STATUS_INVALID_DEVICE_REQUEST
;
4036 /* Handle all properties */
4037 switch (DeviceProperty
)
4039 case DevicePropertyBusTypeGuid
:
4041 /* Get the GUID from the internal cache */
4042 Status
= PnpBusTypeGuidGet(DeviceNode
->ChildBusTypeIndex
, &BusTypeGuid
);
4043 if (!NT_SUCCESS(Status
)) return Status
;
4045 /* This is the format of the returned data */
4046 PIP_RETURN_DATA(sizeof(GUID
), &BusTypeGuid
);
4048 case DevicePropertyLegacyBusType
:
4050 /* Validate correct interface type */
4051 if (DeviceNode
->ChildInterfaceType
== InterfaceTypeUndefined
)
4052 return STATUS_OBJECT_NAME_NOT_FOUND
;
4054 /* This is the format of the returned data */
4055 PIP_RETURN_DATA(sizeof(INTERFACE_TYPE
), &DeviceNode
->ChildInterfaceType
);
4057 case DevicePropertyBusNumber
:
4059 /* Validate correct bus number */
4060 if ((DeviceNode
->ChildBusNumber
& 0x80000000) == 0x80000000)
4061 return STATUS_OBJECT_NAME_NOT_FOUND
;
4063 /* This is the format of the returned data */
4064 PIP_RETURN_DATA(sizeof(ULONG
), &DeviceNode
->ChildBusNumber
);
4066 case DevicePropertyEnumeratorName
:
4068 /* Get the instance path */
4069 DeviceInstanceName
= DeviceNode
->InstancePath
.Buffer
;
4072 ASSERT((BufferLength
& 1) == 0);
4073 ASSERT(DeviceInstanceName
!= NULL
);
4075 /* Get the name from the path */
4076 EnumeratorNameEnd
= wcschr(DeviceInstanceName
, OBJ_NAME_PATH_SEPARATOR
);
4077 ASSERT(EnumeratorNameEnd
);
4079 /* This string needs to be NULL-terminated */
4080 NullTerminate
= TRUE
;
4082 /* This is the format of the returned data */
4083 PIP_RETURN_DATA((ULONG
)(EnumeratorNameEnd
- DeviceInstanceName
) * sizeof(WCHAR
),
4084 DeviceInstanceName
);
4086 case DevicePropertyAddress
:
4088 /* Query the device caps */
4089 Status
= IopQueryDeviceCapabilities(DeviceNode
, &DeviceCaps
);
4090 if (!NT_SUCCESS(Status
) || (DeviceCaps
.Address
== MAXULONG
))
4091 return STATUS_OBJECT_NAME_NOT_FOUND
;
4093 /* This is the format of the returned data */
4094 PIP_RETURN_DATA(sizeof(ULONG
), &DeviceCaps
.Address
);
4096 case DevicePropertyBootConfigurationTranslated
:
4098 /* Validate we have resources */
4099 if (!DeviceNode
->BootResources
)
4100 // if (!DeviceNode->BootResourcesTranslated) // FIXFIX: Need this field
4102 /* No resources will still fake success, but with 0 bytes */
4104 return STATUS_SUCCESS
;
4107 /* This is the format of the returned data */
4108 PIP_RETURN_DATA(PnpDetermineResourceListSize(DeviceNode
->BootResources
), // FIXFIX: Should use BootResourcesTranslated
4109 DeviceNode
->BootResources
); // FIXFIX: Should use BootResourcesTranslated
4111 case DevicePropertyPhysicalDeviceObjectName
:
4113 /* Sanity check for Unicode-sized string */
4114 ASSERT((BufferLength
& 1) == 0);
4116 /* Allocate name buffer */
4117 Length
= BufferLength
+ sizeof(OBJECT_NAME_INFORMATION
);
4118 ObjectNameInfo
= ExAllocatePool(PagedPool
, Length
);
4119 if (!ObjectNameInfo
) return STATUS_INSUFFICIENT_RESOURCES
;
4121 /* Query the PDO name */
4122 Status
= ObQueryNameString(DeviceObject
,
4126 if (Status
== STATUS_INFO_LENGTH_MISMATCH
)
4128 /* It's up to the caller to try again */
4129 Status
= STATUS_BUFFER_TOO_SMALL
;
4132 /* This string needs to be NULL-terminated */
4133 NullTerminate
= TRUE
;
4135 /* Return if successful */
4136 if (NT_SUCCESS(Status
)) PIP_RETURN_DATA(ObjectNameInfo
->Name
.Length
,
4137 ObjectNameInfo
->Name
.Buffer
);
4139 /* Let the caller know how big the name is */
4140 *ResultLength
-= sizeof(OBJECT_NAME_INFORMATION
);
4143 /* Handle the registry-based properties */
4144 case DevicePropertyUINumber
:
4145 PIP_REGISTRY_DATA(REGSTR_VAL_UI_NUMBER
, REG_DWORD
);
4146 case DevicePropertyLocationInformation
:
4147 PIP_REGISTRY_DATA(REGSTR_VAL_LOCATION_INFORMATION
, REG_SZ
);
4148 case DevicePropertyDeviceDescription
:
4149 PIP_REGISTRY_DATA(REGSTR_VAL_DEVDESC
, REG_SZ
);
4150 case DevicePropertyHardwareID
:
4151 PIP_REGISTRY_DATA(REGSTR_VAL_HARDWAREID
, REG_MULTI_SZ
);
4152 case DevicePropertyCompatibleIDs
:
4153 PIP_REGISTRY_DATA(REGSTR_VAL_COMPATIBLEIDS
, REG_MULTI_SZ
);
4154 case DevicePropertyBootConfiguration
:
4155 PIP_REGISTRY_DATA(REGSTR_VAL_BOOTCONFIG
, REG_RESOURCE_LIST
);
4156 case DevicePropertyClassName
:
4157 PIP_REGISTRY_DATA(REGSTR_VAL_CLASS
, REG_SZ
);
4158 case DevicePropertyClassGuid
:
4159 PIP_REGISTRY_DATA(REGSTR_VAL_CLASSGUID
, REG_SZ
);
4160 case DevicePropertyDriverKeyName
:
4161 PIP_REGISTRY_DATA(REGSTR_VAL_DRIVER
, REG_SZ
);
4162 case DevicePropertyManufacturer
:
4163 PIP_REGISTRY_DATA(REGSTR_VAL_MFG
, REG_SZ
);
4164 case DevicePropertyFriendlyName
:
4165 PIP_REGISTRY_DATA(REGSTR_VAL_FRIENDLYNAME
, REG_SZ
);
4166 case DevicePropertyContainerID
:
4167 //PIP_REGISTRY_DATA(REGSTR_VAL_CONTAINERID, REG_SZ); // Win7
4168 PIP_UNIMPLEMENTED();
4169 case DevicePropertyRemovalPolicy
:
4170 PIP_UNIMPLEMENTED();
4172 case DevicePropertyInstallState
:
4173 PIP_REGISTRY_DATA(REGSTR_VAL_CONFIGFLAGS
, REG_DWORD
);
4175 case DevicePropertyResourceRequirements
:
4176 PIP_UNIMPLEMENTED();
4177 case DevicePropertyAllocatedResources
:
4178 PIP_UNIMPLEMENTED();
4180 return STATUS_INVALID_PARAMETER_2
;
4183 /* Having a registry value name implies registry data */
4186 /* We know up-front how much data to expect */
4187 *ResultLength
= BufferLength
;
4189 /* Go get the data, use the LogConf subkey if necessary */
4190 Status
= PiGetDeviceRegistryProperty(DeviceObject
,
4194 DevicePropertyBootConfiguration
) ?
4199 else if (NT_SUCCESS(Status
))
4201 /* We know up-front how much data to expect, check the caller's buffer */
4202 *ResultLength
= ReturnLength
+ (NullTerminate
? sizeof(UNICODE_NULL
) : 0);
4203 if (*ResultLength
<= BufferLength
)
4205 /* Buffer is all good, copy the data */
4206 RtlCopyMemory(PropertyBuffer
, Data
, ReturnLength
);
4208 /* Check if we need to NULL-terminate the string */
4211 /* Terminate the string */
4212 ((PWCHAR
)PropertyBuffer
)[ReturnLength
/ sizeof(WCHAR
)] = UNICODE_NULL
;
4215 /* This is the success path */
4216 Status
= STATUS_SUCCESS
;
4221 Status
= STATUS_BUFFER_TOO_SMALL
;
4225 /* Free any allocation we may have made, and return the status code */
4226 if (ObjectNameInfo
) ExFreePool(ObjectNameInfo
);
4235 IoInvalidateDeviceState(IN PDEVICE_OBJECT PhysicalDeviceObject
)
4237 PDEVICE_NODE DeviceNode
= IopGetDeviceNode(PhysicalDeviceObject
);
4238 IO_STACK_LOCATION Stack
;
4241 IO_STATUS_BLOCK IoStatusBlock
;
4243 RtlZeroMemory(&Stack
, sizeof(IO_STACK_LOCATION
));
4244 Stack
.MajorFunction
= IRP_MJ_PNP
;
4245 Stack
.MinorFunction
= IRP_MN_QUERY_PNP_DEVICE_STATE
;
4247 Status
= IopSynchronousCall(PhysicalDeviceObject
, &Stack
, (PVOID
*)&PnPFlags
);
4248 if (!NT_SUCCESS(Status
))
4250 if (Status
!= STATUS_NOT_SUPPORTED
)
4252 DPRINT1("IRP_MN_QUERY_PNP_DEVICE_STATE failed with status 0x%lx\n", Status
);
4257 if (PnPFlags
& PNP_DEVICE_NOT_DISABLEABLE
)
4258 DeviceNode
->UserFlags
|= DNUF_NOT_DISABLEABLE
;
4260 DeviceNode
->UserFlags
&= ~DNUF_NOT_DISABLEABLE
;
4262 if (PnPFlags
& PNP_DEVICE_DONT_DISPLAY_IN_UI
)
4263 DeviceNode
->UserFlags
|= DNUF_DONT_SHOW_IN_UI
;
4265 DeviceNode
->UserFlags
&= ~DNUF_DONT_SHOW_IN_UI
;
4267 if ((PnPFlags
& PNP_DEVICE_REMOVED
) ||
4268 ((PnPFlags
& PNP_DEVICE_FAILED
) && !(PnPFlags
& PNP_DEVICE_RESOURCE_REQUIREMENTS_CHANGED
)))
4270 /* Flag it if it's failed */
4271 if (PnPFlags
& PNP_DEVICE_FAILED
) DeviceNode
->Problem
= CM_PROB_FAILED_POST_START
;
4273 /* Send removal IRPs to all of its children */
4274 IopPrepareDeviceForRemoval(PhysicalDeviceObject
, TRUE
);
4276 /* Send surprise removal */
4277 IopSendSurpriseRemoval(PhysicalDeviceObject
);
4279 /* Tell the user-mode PnP manager that a device was removed */
4280 IopQueueTargetDeviceEvent(&GUID_DEVICE_SURPRISE_REMOVAL
,
4281 &DeviceNode
->InstancePath
);
4283 IopSendRemoveDevice(PhysicalDeviceObject
);
4285 else if ((PnPFlags
& PNP_DEVICE_FAILED
) && (PnPFlags
& PNP_DEVICE_RESOURCE_REQUIREMENTS_CHANGED
))
4287 /* Stop for resource rebalance */
4288 Status
= IopStopDevice(DeviceNode
);
4289 if (!NT_SUCCESS(Status
))
4291 DPRINT1("Failed to stop device for rebalancing\n");
4293 /* Stop failed so don't rebalance */
4294 PnPFlags
&= ~PNP_DEVICE_RESOURCE_REQUIREMENTS_CHANGED
;
4298 /* Resource rebalance */
4299 if (PnPFlags
& PNP_DEVICE_RESOURCE_REQUIREMENTS_CHANGED
)
4301 DPRINT("Sending IRP_MN_QUERY_RESOURCES to device stack\n");
4303 Status
= IopInitiatePnpIrp(PhysicalDeviceObject
,
4305 IRP_MN_QUERY_RESOURCES
,
4307 if (NT_SUCCESS(Status
) && IoStatusBlock
.Information
)
4309 DeviceNode
->BootResources
=
4310 (PCM_RESOURCE_LIST
)IoStatusBlock
.Information
;
4311 IopDeviceNodeSetFlag(DeviceNode
, DNF_HAS_BOOT_CONFIG
);
4315 DPRINT("IopInitiatePnpIrp() failed (Status %x) or IoStatusBlock.Information=NULL\n", Status
);
4316 DeviceNode
->BootResources
= NULL
;
4319 DPRINT("Sending IRP_MN_QUERY_RESOURCE_REQUIREMENTS to device stack\n");
4321 Status
= IopInitiatePnpIrp(PhysicalDeviceObject
,
4323 IRP_MN_QUERY_RESOURCE_REQUIREMENTS
,
4325 if (NT_SUCCESS(Status
))
4327 DeviceNode
->ResourceRequirements
=
4328 (PIO_RESOURCE_REQUIREMENTS_LIST
)IoStatusBlock
.Information
;
4332 DPRINT("IopInitiatePnpIrp() failed (Status %08lx)\n", Status
);
4333 DeviceNode
->ResourceRequirements
= NULL
;
4336 /* IRP_MN_FILTER_RESOURCE_REQUIREMENTS is called indirectly by IopStartDevice */
4337 if (IopStartDevice(DeviceNode
) != STATUS_SUCCESS
)
4339 DPRINT1("Restart after resource rebalance failed\n");
4341 DeviceNode
->Flags
&= ~(DNF_STARTED
| DNF_START_REQUEST_PENDING
);
4342 DeviceNode
->Flags
|= DNF_START_FAILED
;
4344 IopRemoveDevice(DeviceNode
);
4350 * @name IoOpenDeviceRegistryKey
4352 * Open a registry key unique for a specified driver or device instance.
4354 * @param DeviceObject Device to get the registry key for.
4355 * @param DevInstKeyType Type of the key to return.
4356 * @param DesiredAccess Access mask (eg. KEY_READ | KEY_WRITE).
4357 * @param DevInstRegKey Handle to the opened registry key on
4358 * successful return.
4366 IoOpenDeviceRegistryKey(IN PDEVICE_OBJECT DeviceObject
,
4367 IN ULONG DevInstKeyType
,
4368 IN ACCESS_MASK DesiredAccess
,
4369 OUT PHANDLE DevInstRegKey
)
4371 static WCHAR RootKeyName
[] =
4372 L
"\\Registry\\Machine\\System\\CurrentControlSet\\";
4373 static WCHAR ProfileKeyName
[] =
4374 L
"Hardware Profiles\\Current\\System\\CurrentControlSet\\";
4375 static WCHAR ClassKeyName
[] = L
"Control\\Class\\";
4376 static WCHAR EnumKeyName
[] = L
"Enum\\";
4377 static WCHAR DeviceParametersKeyName
[] = L
"Device Parameters";
4378 ULONG KeyNameLength
;
4379 PWSTR KeyNameBuffer
;
4380 UNICODE_STRING KeyName
;
4381 ULONG DriverKeyLength
;
4382 OBJECT_ATTRIBUTES ObjectAttributes
;
4383 PDEVICE_NODE DeviceNode
= NULL
;
4386 DPRINT("IoOpenDeviceRegistryKey() called\n");
4388 if ((DevInstKeyType
& (PLUGPLAY_REGKEY_DEVICE
| PLUGPLAY_REGKEY_DRIVER
)) == 0)
4390 DPRINT1("IoOpenDeviceRegistryKey(): got wrong params, exiting... \n");
4391 return STATUS_INVALID_PARAMETER
;
4394 if (!IopIsValidPhysicalDeviceObject(DeviceObject
))
4395 return STATUS_INVALID_DEVICE_REQUEST
;
4396 DeviceNode
= IopGetDeviceNode(DeviceObject
);
4399 * Calculate the length of the base key name. This is the full
4400 * name for driver key or the name excluding "Device Parameters"
4401 * subkey for device key.
4404 KeyNameLength
= sizeof(RootKeyName
);
4405 if (DevInstKeyType
& PLUGPLAY_REGKEY_CURRENT_HWPROFILE
)
4406 KeyNameLength
+= sizeof(ProfileKeyName
) - sizeof(UNICODE_NULL
);
4407 if (DevInstKeyType
& PLUGPLAY_REGKEY_DRIVER
)
4409 KeyNameLength
+= sizeof(ClassKeyName
) - sizeof(UNICODE_NULL
);
4410 Status
= IoGetDeviceProperty(DeviceObject
, DevicePropertyDriverKeyName
,
4411 0, NULL
, &DriverKeyLength
);
4412 if (Status
!= STATUS_BUFFER_TOO_SMALL
)
4414 KeyNameLength
+= DriverKeyLength
;
4418 KeyNameLength
+= sizeof(EnumKeyName
) - sizeof(UNICODE_NULL
) +
4419 DeviceNode
->InstancePath
.Length
;
4423 * Now allocate the buffer for the key name...
4426 KeyNameBuffer
= ExAllocatePool(PagedPool
, KeyNameLength
);
4427 if (KeyNameBuffer
== NULL
)
4428 return STATUS_INSUFFICIENT_RESOURCES
;
4431 KeyName
.MaximumLength
= (USHORT
)KeyNameLength
;
4432 KeyName
.Buffer
= KeyNameBuffer
;
4435 * ...and build the key name.
4438 KeyName
.Length
+= sizeof(RootKeyName
) - sizeof(UNICODE_NULL
);
4439 RtlCopyMemory(KeyNameBuffer
, RootKeyName
, KeyName
.Length
);
4441 if (DevInstKeyType
& PLUGPLAY_REGKEY_CURRENT_HWPROFILE
)
4442 RtlAppendUnicodeToString(&KeyName
, ProfileKeyName
);
4444 if (DevInstKeyType
& PLUGPLAY_REGKEY_DRIVER
)
4446 RtlAppendUnicodeToString(&KeyName
, ClassKeyName
);
4447 Status
= IoGetDeviceProperty(DeviceObject
, DevicePropertyDriverKeyName
,
4448 DriverKeyLength
, KeyNameBuffer
+
4449 (KeyName
.Length
/ sizeof(WCHAR
)),
4451 if (!NT_SUCCESS(Status
))
4453 DPRINT1("Call to IoGetDeviceProperty() failed with Status 0x%08lx\n", Status
);
4454 ExFreePool(KeyNameBuffer
);
4457 KeyName
.Length
+= (USHORT
)DriverKeyLength
- sizeof(UNICODE_NULL
);
4461 RtlAppendUnicodeToString(&KeyName
, EnumKeyName
);
4462 Status
= RtlAppendUnicodeStringToString(&KeyName
, &DeviceNode
->InstancePath
);
4463 if (DeviceNode
->InstancePath
.Length
== 0)
4465 ExFreePool(KeyNameBuffer
);
4471 * Open the base key.
4473 Status
= IopOpenRegistryKeyEx(DevInstRegKey
, NULL
, &KeyName
, DesiredAccess
);
4474 if (!NT_SUCCESS(Status
))
4476 DPRINT1("IoOpenDeviceRegistryKey(%wZ): Base key doesn't exist, exiting... (Status 0x%08lx)\n", &KeyName
, Status
);
4477 ExFreePool(KeyNameBuffer
);
4480 ExFreePool(KeyNameBuffer
);
4483 * For driver key we're done now.
4486 if (DevInstKeyType
& PLUGPLAY_REGKEY_DRIVER
)
4490 * Let's go further. For device key we must open "Device Parameters"
4491 * subkey and create it if it doesn't exist yet.
4494 RtlInitUnicodeString(&KeyName
, DeviceParametersKeyName
);
4495 InitializeObjectAttributes(&ObjectAttributes
,
4497 OBJ_CASE_INSENSITIVE
| OBJ_KERNEL_HANDLE
,
4500 Status
= ZwCreateKey(DevInstRegKey
, DesiredAccess
, &ObjectAttributes
,
4501 0, NULL
, ExpInTextModeSetup
? REG_OPTION_VOLATILE
: 0, NULL
);
4502 ZwClose(ObjectAttributes
.RootDirectory
);
4509 IopQueryRemoveChildDevices(PDEVICE_NODE ParentDeviceNode
, BOOLEAN Force
)
4511 PDEVICE_NODE ChildDeviceNode
, NextDeviceNode
, FailedRemoveDevice
;
4515 KeAcquireSpinLock(&IopDeviceTreeLock
, &OldIrql
);
4516 ChildDeviceNode
= ParentDeviceNode
->Child
;
4517 while (ChildDeviceNode
!= NULL
)
4519 NextDeviceNode
= ChildDeviceNode
->Sibling
;
4520 KeReleaseSpinLock(&IopDeviceTreeLock
, OldIrql
);
4522 Status
= IopPrepareDeviceForRemoval(ChildDeviceNode
->PhysicalDeviceObject
, Force
);
4523 if (!NT_SUCCESS(Status
))
4525 FailedRemoveDevice
= ChildDeviceNode
;
4529 KeAcquireSpinLock(&IopDeviceTreeLock
, &OldIrql
);
4530 ChildDeviceNode
= NextDeviceNode
;
4532 KeReleaseSpinLock(&IopDeviceTreeLock
, OldIrql
);
4534 return STATUS_SUCCESS
;
4537 KeAcquireSpinLock(&IopDeviceTreeLock
, &OldIrql
);
4538 ChildDeviceNode
= ParentDeviceNode
->Child
;
4539 while (ChildDeviceNode
!= NULL
)
4541 NextDeviceNode
= ChildDeviceNode
->Sibling
;
4542 KeReleaseSpinLock(&IopDeviceTreeLock
, OldIrql
);
4544 IopCancelPrepareDeviceForRemoval(ChildDeviceNode
->PhysicalDeviceObject
);
4546 /* IRP_MN_CANCEL_REMOVE_DEVICE is also sent to the device
4547 * that failed the IRP_MN_QUERY_REMOVE_DEVICE request */
4548 if (ChildDeviceNode
== FailedRemoveDevice
)
4551 ChildDeviceNode
= NextDeviceNode
;
4553 KeAcquireSpinLock(&IopDeviceTreeLock
, &OldIrql
);
4555 KeReleaseSpinLock(&IopDeviceTreeLock
, OldIrql
);
4562 IopSendRemoveChildDevices(PDEVICE_NODE ParentDeviceNode
)
4564 PDEVICE_NODE ChildDeviceNode
, NextDeviceNode
;
4567 KeAcquireSpinLock(&IopDeviceTreeLock
, &OldIrql
);
4568 ChildDeviceNode
= ParentDeviceNode
->Child
;
4569 while (ChildDeviceNode
!= NULL
)
4571 NextDeviceNode
= ChildDeviceNode
->Sibling
;
4572 KeReleaseSpinLock(&IopDeviceTreeLock
, OldIrql
);
4574 IopSendRemoveDevice(ChildDeviceNode
->PhysicalDeviceObject
);
4576 ChildDeviceNode
= NextDeviceNode
;
4578 KeAcquireSpinLock(&IopDeviceTreeLock
, &OldIrql
);
4580 KeReleaseSpinLock(&IopDeviceTreeLock
, OldIrql
);
4585 IopCancelRemoveChildDevices(PDEVICE_NODE ParentDeviceNode
)
4587 PDEVICE_NODE ChildDeviceNode
, NextDeviceNode
;
4590 KeAcquireSpinLock(&IopDeviceTreeLock
, &OldIrql
);
4591 ChildDeviceNode
= ParentDeviceNode
->Child
;
4592 while (ChildDeviceNode
!= NULL
)
4594 NextDeviceNode
= ChildDeviceNode
->Sibling
;
4595 KeReleaseSpinLock(&IopDeviceTreeLock
, OldIrql
);
4597 IopCancelPrepareDeviceForRemoval(ChildDeviceNode
->PhysicalDeviceObject
);
4599 ChildDeviceNode
= NextDeviceNode
;
4601 KeAcquireSpinLock(&IopDeviceTreeLock
, &OldIrql
);
4603 KeReleaseSpinLock(&IopDeviceTreeLock
, OldIrql
);
4608 IopQueryRemoveDeviceRelations(PDEVICE_RELATIONS DeviceRelations
, BOOLEAN Force
)
4610 /* This function DOES NOT dereference the device objects on SUCCESS
4611 * but it DOES dereference device objects on FAILURE */
4616 for (i
= 0; i
< DeviceRelations
->Count
; i
++)
4618 Status
= IopPrepareDeviceForRemoval(DeviceRelations
->Objects
[i
], Force
);
4619 if (!NT_SUCCESS(Status
))
4626 return STATUS_SUCCESS
;
4629 /* IRP_MN_CANCEL_REMOVE_DEVICE is also sent to the device
4630 * that failed the IRP_MN_QUERY_REMOVE_DEVICE request */
4631 for (i
= 0; i
<= j
; i
++)
4633 IopCancelPrepareDeviceForRemoval(DeviceRelations
->Objects
[i
]);
4634 ObDereferenceObject(DeviceRelations
->Objects
[i
]);
4635 DeviceRelations
->Objects
[i
] = NULL
;
4637 for (; i
< DeviceRelations
->Count
; i
++)
4639 ObDereferenceObject(DeviceRelations
->Objects
[i
]);
4640 DeviceRelations
->Objects
[i
] = NULL
;
4642 ExFreePool(DeviceRelations
);
4649 IopSendRemoveDeviceRelations(PDEVICE_RELATIONS DeviceRelations
)
4651 /* This function DOES dereference the device objects in all cases */
4655 for (i
= 0; i
< DeviceRelations
->Count
; i
++)
4657 IopSendRemoveDevice(DeviceRelations
->Objects
[i
]);
4658 DeviceRelations
->Objects
[i
] = NULL
;
4661 ExFreePool(DeviceRelations
);
4666 IopCancelRemoveDeviceRelations(PDEVICE_RELATIONS DeviceRelations
)
4668 /* This function DOES dereference the device objects in all cases */
4672 for (i
= 0; i
< DeviceRelations
->Count
; i
++)
4674 IopCancelPrepareDeviceForRemoval(DeviceRelations
->Objects
[i
]);
4675 ObDereferenceObject(DeviceRelations
->Objects
[i
]);
4676 DeviceRelations
->Objects
[i
] = NULL
;
4679 ExFreePool(DeviceRelations
);
4683 IopCancelPrepareDeviceForRemoval(PDEVICE_OBJECT DeviceObject
)
4685 IO_STACK_LOCATION Stack
;
4686 IO_STATUS_BLOCK IoStatusBlock
;
4687 PDEVICE_RELATIONS DeviceRelations
;
4690 IopCancelRemoveDevice(DeviceObject
);
4692 Stack
.Parameters
.QueryDeviceRelations
.Type
= RemovalRelations
;
4694 Status
= IopInitiatePnpIrp(DeviceObject
,
4696 IRP_MN_QUERY_DEVICE_RELATIONS
,
4698 if (!NT_SUCCESS(Status
))
4700 DPRINT("IopInitiatePnpIrp() failed with status 0x%08lx\n", Status
);
4701 DeviceRelations
= NULL
;
4705 DeviceRelations
= (PDEVICE_RELATIONS
)IoStatusBlock
.Information
;
4708 if (DeviceRelations
)
4709 IopCancelRemoveDeviceRelations(DeviceRelations
);
4713 IopPrepareDeviceForRemoval(IN PDEVICE_OBJECT DeviceObject
, BOOLEAN Force
)
4715 PDEVICE_NODE DeviceNode
= IopGetDeviceNode(DeviceObject
);
4716 IO_STACK_LOCATION Stack
;
4717 IO_STATUS_BLOCK IoStatusBlock
;
4718 PDEVICE_RELATIONS DeviceRelations
;
4721 if ((DeviceNode
->UserFlags
& DNUF_NOT_DISABLEABLE
) && !Force
)
4723 DPRINT1("Removal not allowed for %wZ\n", &DeviceNode
->InstancePath
);
4724 return STATUS_UNSUCCESSFUL
;
4727 if (!Force
&& IopQueryRemoveDevice(DeviceObject
) != STATUS_SUCCESS
)
4729 DPRINT1("Removal vetoed by failing the query remove request\n");
4731 IopCancelRemoveDevice(DeviceObject
);
4733 return STATUS_UNSUCCESSFUL
;
4736 Stack
.Parameters
.QueryDeviceRelations
.Type
= RemovalRelations
;
4738 Status
= IopInitiatePnpIrp(DeviceObject
,
4740 IRP_MN_QUERY_DEVICE_RELATIONS
,
4742 if (!NT_SUCCESS(Status
))
4744 DPRINT("IopInitiatePnpIrp() failed with status 0x%08lx\n", Status
);
4745 DeviceRelations
= NULL
;
4749 DeviceRelations
= (PDEVICE_RELATIONS
)IoStatusBlock
.Information
;
4752 if (DeviceRelations
)
4754 Status
= IopQueryRemoveDeviceRelations(DeviceRelations
, Force
);
4755 if (!NT_SUCCESS(Status
))
4759 Status
= IopQueryRemoveChildDevices(DeviceNode
, Force
);
4760 if (!NT_SUCCESS(Status
))
4762 if (DeviceRelations
)
4763 IopCancelRemoveDeviceRelations(DeviceRelations
);
4767 if (DeviceRelations
)
4768 IopSendRemoveDeviceRelations(DeviceRelations
);
4769 IopSendRemoveChildDevices(DeviceNode
);
4771 return STATUS_SUCCESS
;
4775 IopRemoveDevice(PDEVICE_NODE DeviceNode
)
4779 DPRINT("Removing device: %wZ\n", &DeviceNode
->InstancePath
);
4781 Status
= IopPrepareDeviceForRemoval(DeviceNode
->PhysicalDeviceObject
, FALSE
);
4782 if (NT_SUCCESS(Status
))
4784 IopSendRemoveDevice(DeviceNode
->PhysicalDeviceObject
);
4785 IopQueueTargetDeviceEvent(&GUID_DEVICE_SAFE_REMOVAL
,
4786 &DeviceNode
->InstancePath
);
4787 return STATUS_SUCCESS
;
4798 IoRequestDeviceEject(IN PDEVICE_OBJECT PhysicalDeviceObject
)
4800 PDEVICE_NODE DeviceNode
= IopGetDeviceNode(PhysicalDeviceObject
);
4801 PDEVICE_RELATIONS DeviceRelations
;
4802 IO_STATUS_BLOCK IoStatusBlock
;
4803 IO_STACK_LOCATION Stack
;
4804 DEVICE_CAPABILITIES Capabilities
;
4807 IopQueueTargetDeviceEvent(&GUID_DEVICE_KERNEL_INITIATED_EJECT
,
4808 &DeviceNode
->InstancePath
);
4810 if (IopQueryDeviceCapabilities(DeviceNode
, &Capabilities
) != STATUS_SUCCESS
)
4815 Stack
.Parameters
.QueryDeviceRelations
.Type
= EjectionRelations
;
4817 Status
= IopInitiatePnpIrp(PhysicalDeviceObject
,
4819 IRP_MN_QUERY_DEVICE_RELATIONS
,
4821 if (!NT_SUCCESS(Status
))
4823 DPRINT("IopInitiatePnpIrp() failed with status 0x%08lx\n", Status
);
4824 DeviceRelations
= NULL
;
4828 DeviceRelations
= (PDEVICE_RELATIONS
)IoStatusBlock
.Information
;
4831 if (DeviceRelations
)
4833 Status
= IopQueryRemoveDeviceRelations(DeviceRelations
, FALSE
);
4834 if (!NT_SUCCESS(Status
))
4838 Status
= IopQueryRemoveChildDevices(DeviceNode
, FALSE
);
4839 if (!NT_SUCCESS(Status
))
4841 if (DeviceRelations
)
4842 IopCancelRemoveDeviceRelations(DeviceRelations
);
4846 if (IopPrepareDeviceForRemoval(PhysicalDeviceObject
, FALSE
) != STATUS_SUCCESS
)
4848 if (DeviceRelations
)
4849 IopCancelRemoveDeviceRelations(DeviceRelations
);
4850 IopCancelRemoveChildDevices(DeviceNode
);
4854 if (DeviceRelations
)
4855 IopSendRemoveDeviceRelations(DeviceRelations
);
4856 IopSendRemoveChildDevices(DeviceNode
);
4858 DeviceNode
->Problem
= CM_PROB_HELD_FOR_EJECT
;
4859 if (Capabilities
.EjectSupported
)
4861 if (IopSendEject(PhysicalDeviceObject
) != STATUS_SUCCESS
)
4868 DeviceNode
->Flags
|= DNF_DISABLED
;
4871 IopQueueTargetDeviceEvent(&GUID_DEVICE_EJECT
,
4872 &DeviceNode
->InstancePath
);
4877 IopQueueTargetDeviceEvent(&GUID_DEVICE_EJECT_VETOED
,
4878 &DeviceNode
->InstancePath
);
4886 IoInvalidateDeviceRelations(
4887 IN PDEVICE_OBJECT DeviceObject
,
4888 IN DEVICE_RELATION_TYPE Type
)
4890 PINVALIDATE_DEVICE_RELATION_DATA Data
;
4893 Data
= ExAllocatePool(NonPagedPool
, sizeof(INVALIDATE_DEVICE_RELATION_DATA
));
4897 ObReferenceObject(DeviceObject
);
4898 Data
->DeviceObject
= DeviceObject
;
4901 KeAcquireSpinLock(&IopDeviceRelationsSpinLock
, &OldIrql
);
4902 InsertTailList(&IopDeviceRelationsRequestList
, &Data
->RequestListEntry
);
4903 if (IopDeviceRelationsRequestInProgress
)
4905 KeReleaseSpinLock(&IopDeviceRelationsSpinLock
, OldIrql
);
4908 IopDeviceRelationsRequestInProgress
= TRUE
;
4909 KeReleaseSpinLock(&IopDeviceRelationsSpinLock
, OldIrql
);
4911 ExInitializeWorkItem(&IopDeviceRelationsWorkItem
,
4912 IopDeviceRelationsWorker
,
4914 ExQueueWorkItem(&IopDeviceRelationsWorkItem
,
4923 IoSynchronousInvalidateDeviceRelations(
4924 IN PDEVICE_OBJECT DeviceObject
,
4925 IN DEVICE_RELATION_TYPE Type
)
4932 /* Enumerate the device */
4933 return IopEnumerateDevice(DeviceObject
);
4934 case PowerRelations
:
4935 /* Not handled yet */
4936 return STATUS_NOT_IMPLEMENTED
;
4937 case TargetDeviceRelation
:
4939 return STATUS_SUCCESS
;
4941 /* Ejection relations are not supported */
4942 return STATUS_NOT_SUPPORTED
;
4951 IoTranslateBusAddress(IN INTERFACE_TYPE InterfaceType
,
4953 IN PHYSICAL_ADDRESS BusAddress
,
4954 IN OUT PULONG AddressSpace
,
4955 OUT PPHYSICAL_ADDRESS TranslatedAddress
)
4957 /* FIXME: Notify the resource arbiter */
4959 return HalTranslateBusAddress(InterfaceType
,