* Sync up to trunk head (r65183).
[reactos.git] / ntoskrnl / io / pnpmgr / pnpmgr.c
1 /*
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)
8 */
9
10 /* INCLUDES ******************************************************************/
11
12 #include <ntoskrnl.h>
13 #define NDEBUG
14 #include <debug.h>
15
16 /* GLOBALS *******************************************************************/
17
18 PDEVICE_NODE IopRootDeviceNode;
19 KSPIN_LOCK IopDeviceTreeLock;
20 ERESOURCE PpRegistryDeviceResource;
21 KGUARDED_MUTEX PpDeviceReferenceTableLock;
22 RTL_AVL_TABLE PpDeviceReferenceTable;
23
24 extern ERESOURCE IopDriverLoadResource;
25 extern ULONG ExpInitializationPhase;
26 extern BOOLEAN ExpInTextModeSetup;
27 extern BOOLEAN PnpSystemInit;
28
29 /* DATA **********************************************************************/
30
31 PDRIVER_OBJECT IopRootDriverObject;
32 PIO_BUS_TYPE_GUID_LIST PnpBusTypeGuidList = NULL;
33 LIST_ENTRY IopDeviceRelationsRequestList;
34 WORK_QUEUE_ITEM IopDeviceRelationsWorkItem;
35 BOOLEAN IopDeviceRelationsRequestInProgress;
36 KSPIN_LOCK IopDeviceRelationsSpinLock;
37
38 typedef struct _INVALIDATE_DEVICE_RELATION_DATA
39 {
40 LIST_ENTRY RequestListEntry;
41 PDEVICE_OBJECT DeviceObject;
42 DEVICE_RELATION_TYPE Type;
43 } INVALIDATE_DEVICE_RELATION_DATA, *PINVALIDATE_DEVICE_RELATION_DATA;
44
45 /* FUNCTIONS *****************************************************************/
46 NTSTATUS
47 NTAPI
48 IopCreateDeviceKeyPath(IN PCUNICODE_STRING RegistryPath,
49 IN ULONG CreateOptions,
50 OUT PHANDLE Handle);
51
52 VOID
53 IopCancelPrepareDeviceForRemoval(PDEVICE_OBJECT DeviceObject);
54
55 NTSTATUS
56 IopPrepareDeviceForRemoval(PDEVICE_OBJECT DeviceObject, BOOLEAN Force);
57
58 PDEVICE_OBJECT
59 IopGetDeviceObjectFromDeviceInstance(PUNICODE_STRING DeviceInstance);
60
61 PDEVICE_NODE
62 FASTCALL
63 IopGetDeviceNode(PDEVICE_OBJECT DeviceObject)
64 {
65 return ((PEXTENDED_DEVOBJ_EXTENSION)DeviceObject->DeviceObjectExtension)->DeviceNode;
66 }
67
68 VOID
69 IopFixupDeviceId(PWCHAR String)
70 {
71 SIZE_T Length = wcslen(String), i;
72
73 for (i = 0; i < Length; i++)
74 {
75 if (String[i] == L'\\')
76 String[i] = L'#';
77 }
78 }
79
80 VOID
81 NTAPI
82 IopInstallCriticalDevice(PDEVICE_NODE DeviceNode)
83 {
84 NTSTATUS Status;
85 HANDLE CriticalDeviceKey, InstanceKey;
86 OBJECT_ATTRIBUTES ObjectAttributes;
87 UNICODE_STRING CriticalDeviceKeyU = RTL_CONSTANT_STRING(L"\\Registry\\Machine\\System\\CurrentControlSet\\Control\\CriticalDeviceDatabase");
88 UNICODE_STRING CompatibleIdU = RTL_CONSTANT_STRING(L"CompatibleIDs");
89 UNICODE_STRING HardwareIdU = RTL_CONSTANT_STRING(L"HardwareID");
90 UNICODE_STRING ServiceU = RTL_CONSTANT_STRING(L"Service");
91 UNICODE_STRING ClassGuidU = RTL_CONSTANT_STRING(L"ClassGUID");
92 PKEY_VALUE_PARTIAL_INFORMATION PartialInfo;
93 ULONG HidLength = 0, CidLength = 0, BufferLength;
94 PWCHAR IdBuffer, OriginalIdBuffer;
95
96 /* Open the device instance key */
97 Status = IopCreateDeviceKeyPath(&DeviceNode->InstancePath, 0, &InstanceKey);
98 if (Status != STATUS_SUCCESS)
99 return;
100
101 Status = ZwQueryValueKey(InstanceKey,
102 &HardwareIdU,
103 KeyValuePartialInformation,
104 NULL,
105 0,
106 &HidLength);
107 if (Status != STATUS_BUFFER_OVERFLOW && Status != STATUS_BUFFER_TOO_SMALL)
108 {
109 ZwClose(InstanceKey);
110 return;
111 }
112
113 Status = ZwQueryValueKey(InstanceKey,
114 &CompatibleIdU,
115 KeyValuePartialInformation,
116 NULL,
117 0,
118 &CidLength);
119 if (Status != STATUS_BUFFER_OVERFLOW && Status != STATUS_BUFFER_TOO_SMALL)
120 {
121 CidLength = 0;
122 }
123
124 BufferLength = HidLength + CidLength;
125 BufferLength -= (((CidLength != 0) ? 2 : 1) * FIELD_OFFSET(KEY_VALUE_PARTIAL_INFORMATION, Data));
126
127 /* Allocate a buffer to hold data from both */
128 OriginalIdBuffer = IdBuffer = ExAllocatePool(PagedPool, BufferLength);
129 if (!IdBuffer)
130 {
131 ZwClose(InstanceKey);
132 return;
133 }
134
135 /* Compute the buffer size */
136 if (HidLength > CidLength)
137 BufferLength = HidLength;
138 else
139 BufferLength = CidLength;
140
141 PartialInfo = ExAllocatePool(PagedPool, BufferLength);
142 if (!PartialInfo)
143 {
144 ZwClose(InstanceKey);
145 ExFreePool(OriginalIdBuffer);
146 return;
147 }
148
149 Status = ZwQueryValueKey(InstanceKey,
150 &HardwareIdU,
151 KeyValuePartialInformation,
152 PartialInfo,
153 HidLength,
154 &HidLength);
155 if (Status != STATUS_SUCCESS)
156 {
157 ExFreePool(PartialInfo);
158 ExFreePool(OriginalIdBuffer);
159 ZwClose(InstanceKey);
160 return;
161 }
162
163 /* Copy in HID info first (without 2nd terminating NULL if CID is present) */
164 HidLength = PartialInfo->DataLength - ((CidLength != 0) ? sizeof(WCHAR) : 0);
165 RtlCopyMemory(IdBuffer, PartialInfo->Data, HidLength);
166
167 if (CidLength != 0)
168 {
169 Status = ZwQueryValueKey(InstanceKey,
170 &CompatibleIdU,
171 KeyValuePartialInformation,
172 PartialInfo,
173 CidLength,
174 &CidLength);
175 if (Status != STATUS_SUCCESS)
176 {
177 ExFreePool(PartialInfo);
178 ExFreePool(OriginalIdBuffer);
179 ZwClose(InstanceKey);
180 return;
181 }
182
183 /* Copy CID next */
184 CidLength = PartialInfo->DataLength;
185 RtlCopyMemory(((PUCHAR)IdBuffer) + HidLength, PartialInfo->Data, CidLength);
186 }
187
188 /* Free our temp buffer */
189 ExFreePool(PartialInfo);
190
191 InitializeObjectAttributes(&ObjectAttributes,
192 &CriticalDeviceKeyU,
193 OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE,
194 NULL,
195 NULL);
196 Status = ZwOpenKey(&CriticalDeviceKey,
197 KEY_ENUMERATE_SUB_KEYS,
198 &ObjectAttributes);
199 if (!NT_SUCCESS(Status))
200 {
201 /* The critical device database doesn't exist because
202 * we're probably in 1st stage setup, but it's ok */
203 ExFreePool(OriginalIdBuffer);
204 ZwClose(InstanceKey);
205 return;
206 }
207
208 while (*IdBuffer)
209 {
210 USHORT StringLength = (USHORT)wcslen(IdBuffer) + 1, Index;
211
212 IopFixupDeviceId(IdBuffer);
213
214 /* Look through all subkeys for a match */
215 for (Index = 0; TRUE; Index++)
216 {
217 ULONG NeededLength;
218 PKEY_BASIC_INFORMATION BasicInfo;
219
220 Status = ZwEnumerateKey(CriticalDeviceKey,
221 Index,
222 KeyBasicInformation,
223 NULL,
224 0,
225 &NeededLength);
226 if (Status == STATUS_NO_MORE_ENTRIES)
227 break;
228 else if (Status == STATUS_BUFFER_OVERFLOW || Status == STATUS_BUFFER_TOO_SMALL)
229 {
230 UNICODE_STRING ChildIdNameU, RegKeyNameU;
231
232 BasicInfo = ExAllocatePool(PagedPool, NeededLength);
233 if (!BasicInfo)
234 {
235 /* No memory */
236 ExFreePool(OriginalIdBuffer);
237 ZwClose(CriticalDeviceKey);
238 ZwClose(InstanceKey);
239 return;
240 }
241
242 Status = ZwEnumerateKey(CriticalDeviceKey,
243 Index,
244 KeyBasicInformation,
245 BasicInfo,
246 NeededLength,
247 &NeededLength);
248 if (Status != STATUS_SUCCESS)
249 {
250 /* This shouldn't happen */
251 ExFreePool(BasicInfo);
252 continue;
253 }
254
255 ChildIdNameU.Buffer = IdBuffer;
256 ChildIdNameU.MaximumLength = ChildIdNameU.Length = (StringLength - 1) * sizeof(WCHAR);
257 RegKeyNameU.Buffer = BasicInfo->Name;
258 RegKeyNameU.MaximumLength = RegKeyNameU.Length = (USHORT)BasicInfo->NameLength;
259
260 if (RtlEqualUnicodeString(&ChildIdNameU, &RegKeyNameU, TRUE))
261 {
262 HANDLE ChildKeyHandle;
263
264 InitializeObjectAttributes(&ObjectAttributes,
265 &ChildIdNameU,
266 OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE,
267 CriticalDeviceKey,
268 NULL);
269
270 Status = ZwOpenKey(&ChildKeyHandle,
271 KEY_QUERY_VALUE,
272 &ObjectAttributes);
273 if (Status != STATUS_SUCCESS)
274 {
275 ExFreePool(BasicInfo);
276 continue;
277 }
278
279 /* Check if there's already a driver installed */
280 Status = ZwQueryValueKey(InstanceKey,
281 &ClassGuidU,
282 KeyValuePartialInformation,
283 NULL,
284 0,
285 &NeededLength);
286 if (Status == STATUS_BUFFER_OVERFLOW || Status == STATUS_BUFFER_TOO_SMALL)
287 {
288 ExFreePool(BasicInfo);
289 continue;
290 }
291
292 Status = ZwQueryValueKey(ChildKeyHandle,
293 &ClassGuidU,
294 KeyValuePartialInformation,
295 NULL,
296 0,
297 &NeededLength);
298 if (Status != STATUS_BUFFER_OVERFLOW && Status != STATUS_BUFFER_TOO_SMALL)
299 {
300 ExFreePool(BasicInfo);
301 continue;
302 }
303
304 PartialInfo = ExAllocatePool(PagedPool, NeededLength);
305 if (!PartialInfo)
306 {
307 ExFreePool(OriginalIdBuffer);
308 ExFreePool(BasicInfo);
309 ZwClose(InstanceKey);
310 ZwClose(ChildKeyHandle);
311 ZwClose(CriticalDeviceKey);
312 return;
313 }
314
315 /* Read ClassGUID entry in the CDDB */
316 Status = ZwQueryValueKey(ChildKeyHandle,
317 &ClassGuidU,
318 KeyValuePartialInformation,
319 PartialInfo,
320 NeededLength,
321 &NeededLength);
322 if (Status != STATUS_SUCCESS)
323 {
324 ExFreePool(BasicInfo);
325 continue;
326 }
327
328 /* Write it to the ENUM key */
329 Status = ZwSetValueKey(InstanceKey,
330 &ClassGuidU,
331 0,
332 REG_SZ,
333 PartialInfo->Data,
334 PartialInfo->DataLength);
335 if (Status != STATUS_SUCCESS)
336 {
337 ExFreePool(BasicInfo);
338 ExFreePool(PartialInfo);
339 ZwClose(ChildKeyHandle);
340 continue;
341 }
342
343 Status = ZwQueryValueKey(ChildKeyHandle,
344 &ServiceU,
345 KeyValuePartialInformation,
346 NULL,
347 0,
348 &NeededLength);
349 if (Status == STATUS_BUFFER_OVERFLOW || Status == STATUS_BUFFER_TOO_SMALL)
350 {
351 ExFreePool(PartialInfo);
352 PartialInfo = ExAllocatePool(PagedPool, NeededLength);
353 if (!PartialInfo)
354 {
355 ExFreePool(OriginalIdBuffer);
356 ExFreePool(BasicInfo);
357 ZwClose(InstanceKey);
358 ZwClose(ChildKeyHandle);
359 ZwClose(CriticalDeviceKey);
360 return;
361 }
362
363 /* Read the service entry from the CDDB */
364 Status = ZwQueryValueKey(ChildKeyHandle,
365 &ServiceU,
366 KeyValuePartialInformation,
367 PartialInfo,
368 NeededLength,
369 &NeededLength);
370 if (Status != STATUS_SUCCESS)
371 {
372 ExFreePool(BasicInfo);
373 ExFreePool(PartialInfo);
374 ZwClose(ChildKeyHandle);
375 continue;
376 }
377
378 /* Write it to the ENUM key */
379 Status = ZwSetValueKey(InstanceKey,
380 &ServiceU,
381 0,
382 REG_SZ,
383 PartialInfo->Data,
384 PartialInfo->DataLength);
385 if (Status != STATUS_SUCCESS)
386 {
387 ExFreePool(BasicInfo);
388 ExFreePool(PartialInfo);
389 ZwClose(ChildKeyHandle);
390 continue;
391 }
392
393 DPRINT("Installed service '%S' for critical device '%wZ'\n", PartialInfo->Data, &ChildIdNameU);
394 }
395 else
396 {
397 DPRINT1("Installed NULL service for critical device '%wZ'\n", &ChildIdNameU);
398 }
399
400 ExFreePool(OriginalIdBuffer);
401 ExFreePool(PartialInfo);
402 ExFreePool(BasicInfo);
403 ZwClose(InstanceKey);
404 ZwClose(ChildKeyHandle);
405 ZwClose(CriticalDeviceKey);
406
407 /* That's it */
408 return;
409 }
410
411 ExFreePool(BasicInfo);
412 }
413 else
414 {
415 /* Umm, not sure what happened here */
416 continue;
417 }
418 }
419
420 /* Advance to the next ID */
421 IdBuffer += StringLength;
422 }
423
424 ExFreePool(OriginalIdBuffer);
425 ZwClose(InstanceKey);
426 ZwClose(CriticalDeviceKey);
427 }
428
429 NTSTATUS
430 FASTCALL
431 IopInitializeDevice(PDEVICE_NODE DeviceNode,
432 PDRIVER_OBJECT DriverObject)
433 {
434 PDEVICE_OBJECT Fdo;
435 NTSTATUS Status;
436
437 if (!DriverObject)
438 {
439 /* Special case for bus driven devices */
440 DeviceNode->Flags |= DNF_ADDED;
441 return STATUS_SUCCESS;
442 }
443
444 if (!DriverObject->DriverExtension->AddDevice)
445 {
446 DeviceNode->Flags |= DNF_LEGACY_DRIVER;
447 }
448
449 if (DeviceNode->Flags & DNF_LEGACY_DRIVER)
450 {
451 DeviceNode->Flags |= DNF_ADDED + DNF_STARTED;
452 return STATUS_SUCCESS;
453 }
454
455 /* This is a Plug and Play driver */
456 DPRINT("Plug and Play driver found\n");
457 ASSERT(DeviceNode->PhysicalDeviceObject);
458
459 DPRINT("Calling %wZ->AddDevice(%wZ)\n",
460 &DriverObject->DriverName,
461 &DeviceNode->InstancePath);
462 Status = DriverObject->DriverExtension->AddDevice(
463 DriverObject, DeviceNode->PhysicalDeviceObject);
464 if (!NT_SUCCESS(Status))
465 {
466 DPRINT1("%wZ->AddDevice(%wZ) failed with status 0x%x\n",
467 &DriverObject->DriverName,
468 &DeviceNode->InstancePath,
469 Status);
470 IopDeviceNodeSetFlag(DeviceNode, DNF_DISABLED);
471 DeviceNode->Problem = CM_PROB_FAILED_ADD;
472 return Status;
473 }
474
475 Fdo = IoGetAttachedDeviceReference(DeviceNode->PhysicalDeviceObject);
476
477 /* Check if we have a ACPI device (needed for power management) */
478 if (Fdo->DeviceType == FILE_DEVICE_ACPI)
479 {
480 static BOOLEAN SystemPowerDeviceNodeCreated = FALSE;
481
482 /* There can be only one system power device */
483 if (!SystemPowerDeviceNodeCreated)
484 {
485 PopSystemPowerDeviceNode = DeviceNode;
486 ObReferenceObject(PopSystemPowerDeviceNode->PhysicalDeviceObject);
487 SystemPowerDeviceNodeCreated = TRUE;
488 }
489 }
490
491 ObDereferenceObject(Fdo);
492
493 IopDeviceNodeSetFlag(DeviceNode, DNF_ADDED);
494
495 return STATUS_SUCCESS;
496 }
497
498 static
499 NTSTATUS
500 NTAPI
501 IopSendEject(IN PDEVICE_OBJECT DeviceObject)
502 {
503 IO_STACK_LOCATION Stack;
504 PVOID Dummy;
505
506 RtlZeroMemory(&Stack, sizeof(IO_STACK_LOCATION));
507 Stack.MajorFunction = IRP_MJ_PNP;
508 Stack.MinorFunction = IRP_MN_EJECT;
509
510 return IopSynchronousCall(DeviceObject, &Stack, &Dummy);
511 }
512
513 static
514 VOID
515 NTAPI
516 IopSendSurpriseRemoval(IN PDEVICE_OBJECT DeviceObject)
517 {
518 IO_STACK_LOCATION Stack;
519 PVOID Dummy;
520
521 RtlZeroMemory(&Stack, sizeof(IO_STACK_LOCATION));
522 Stack.MajorFunction = IRP_MJ_PNP;
523 Stack.MinorFunction = IRP_MN_SURPRISE_REMOVAL;
524
525 /* Drivers should never fail a IRP_MN_SURPRISE_REMOVAL request */
526 IopSynchronousCall(DeviceObject, &Stack, &Dummy);
527 }
528
529 static
530 NTSTATUS
531 NTAPI
532 IopQueryRemoveDevice(IN PDEVICE_OBJECT DeviceObject)
533 {
534 PDEVICE_NODE DeviceNode = IopGetDeviceNode(DeviceObject);
535 IO_STACK_LOCATION Stack;
536 PVOID Dummy;
537 NTSTATUS Status;
538
539 ASSERT(DeviceNode);
540
541 IopQueueTargetDeviceEvent(&GUID_DEVICE_REMOVE_PENDING,
542 &DeviceNode->InstancePath);
543
544 RtlZeroMemory(&Stack, sizeof(IO_STACK_LOCATION));
545 Stack.MajorFunction = IRP_MJ_PNP;
546 Stack.MinorFunction = IRP_MN_QUERY_REMOVE_DEVICE;
547
548 Status = IopSynchronousCall(DeviceObject, &Stack, &Dummy);
549
550 IopNotifyPlugPlayNotification(DeviceObject,
551 EventCategoryTargetDeviceChange,
552 &GUID_TARGET_DEVICE_QUERY_REMOVE,
553 NULL,
554 NULL);
555
556 if (!NT_SUCCESS(Status))
557 {
558 DPRINT1("Removal vetoed by %wZ\n", &DeviceNode->InstancePath);
559 IopQueueTargetDeviceEvent(&GUID_DEVICE_REMOVAL_VETOED,
560 &DeviceNode->InstancePath);
561 }
562
563 return Status;
564 }
565
566 static
567 NTSTATUS
568 NTAPI
569 IopQueryStopDevice(IN PDEVICE_OBJECT DeviceObject)
570 {
571 IO_STACK_LOCATION Stack;
572 PVOID Dummy;
573
574 RtlZeroMemory(&Stack, sizeof(IO_STACK_LOCATION));
575 Stack.MajorFunction = IRP_MJ_PNP;
576 Stack.MinorFunction = IRP_MN_QUERY_STOP_DEVICE;
577
578 return IopSynchronousCall(DeviceObject, &Stack, &Dummy);
579 }
580
581 static
582 VOID
583 NTAPI
584 IopSendRemoveDevice(IN PDEVICE_OBJECT DeviceObject)
585 {
586 IO_STACK_LOCATION Stack;
587 PVOID Dummy;
588 PDEVICE_NODE DeviceNode = IopGetDeviceNode(DeviceObject);
589
590 /* Drop all our state for this device in case it isn't really going away */
591 DeviceNode->Flags &= DNF_ENUMERATED | DNF_PROCESSED;
592
593 RtlZeroMemory(&Stack, sizeof(IO_STACK_LOCATION));
594 Stack.MajorFunction = IRP_MJ_PNP;
595 Stack.MinorFunction = IRP_MN_REMOVE_DEVICE;
596
597 /* Drivers should never fail a IRP_MN_REMOVE_DEVICE request */
598 IopSynchronousCall(DeviceObject, &Stack, &Dummy);
599
600 IopNotifyPlugPlayNotification(DeviceObject,
601 EventCategoryTargetDeviceChange,
602 &GUID_TARGET_DEVICE_REMOVE_COMPLETE,
603 NULL,
604 NULL);
605 ObDereferenceObject(DeviceObject);
606 }
607
608 static
609 VOID
610 NTAPI
611 IopCancelRemoveDevice(IN PDEVICE_OBJECT DeviceObject)
612 {
613 IO_STACK_LOCATION Stack;
614 PVOID Dummy;
615
616 RtlZeroMemory(&Stack, sizeof(IO_STACK_LOCATION));
617 Stack.MajorFunction = IRP_MJ_PNP;
618 Stack.MinorFunction = IRP_MN_CANCEL_REMOVE_DEVICE;
619
620 /* Drivers should never fail a IRP_MN_CANCEL_REMOVE_DEVICE request */
621 IopSynchronousCall(DeviceObject, &Stack, &Dummy);
622
623 IopNotifyPlugPlayNotification(DeviceObject,
624 EventCategoryTargetDeviceChange,
625 &GUID_TARGET_DEVICE_REMOVE_CANCELLED,
626 NULL,
627 NULL);
628 }
629
630 static
631 VOID
632 NTAPI
633 IopSendStopDevice(IN PDEVICE_OBJECT DeviceObject)
634 {
635 IO_STACK_LOCATION Stack;
636 PVOID Dummy;
637
638 RtlZeroMemory(&Stack, sizeof(IO_STACK_LOCATION));
639 Stack.MajorFunction = IRP_MJ_PNP;
640 Stack.MinorFunction = IRP_MN_STOP_DEVICE;
641
642 /* Drivers should never fail a IRP_MN_STOP_DEVICE request */
643 IopSynchronousCall(DeviceObject, &Stack, &Dummy);
644 }
645
646 VOID
647 NTAPI
648 IopStartDevice2(IN PDEVICE_OBJECT DeviceObject)
649 {
650 IO_STACK_LOCATION Stack;
651 PDEVICE_NODE DeviceNode;
652 NTSTATUS Status;
653 PVOID Dummy;
654 DEVICE_CAPABILITIES DeviceCapabilities;
655
656 /* Get the device node */
657 DeviceNode = IopGetDeviceNode(DeviceObject);
658
659 ASSERT(!(DeviceNode->Flags & DNF_DISABLED));
660
661 /* Build the I/O stack location */
662 RtlZeroMemory(&Stack, sizeof(IO_STACK_LOCATION));
663 Stack.MajorFunction = IRP_MJ_PNP;
664 Stack.MinorFunction = IRP_MN_START_DEVICE;
665
666 Stack.Parameters.StartDevice.AllocatedResources =
667 DeviceNode->ResourceList;
668 Stack.Parameters.StartDevice.AllocatedResourcesTranslated =
669 DeviceNode->ResourceListTranslated;
670
671 /* Do the call */
672 Status = IopSynchronousCall(DeviceObject, &Stack, &Dummy);
673 if (!NT_SUCCESS(Status))
674 {
675 /* Send an IRP_MN_REMOVE_DEVICE request */
676 IopRemoveDevice(DeviceNode);
677
678 /* Set the appropriate flag */
679 DeviceNode->Flags |= DNF_START_FAILED;
680 DeviceNode->Problem = CM_PROB_FAILED_START;
681
682 DPRINT1("Warning: PnP Start failed (%wZ) [Status: 0x%x]\n", &DeviceNode->InstancePath, Status);
683 return;
684 }
685
686 DPRINT("Sending IRP_MN_QUERY_CAPABILITIES to device stack (after start)\n");
687
688 Status = IopQueryDeviceCapabilities(DeviceNode, &DeviceCapabilities);
689 if (!NT_SUCCESS(Status))
690 {
691 DPRINT1("IopInitiatePnpIrp() failed (Status 0x%08lx)\n", Status);
692 }
693
694 /* Invalidate device state so IRP_MN_QUERY_PNP_DEVICE_STATE is sent */
695 IoInvalidateDeviceState(DeviceObject);
696
697 /* Otherwise, mark us as started */
698 DeviceNode->Flags |= DNF_STARTED;
699 DeviceNode->Flags &= ~DNF_STOPPED;
700
701 /* We now need enumeration */
702 DeviceNode->Flags |= DNF_NEED_ENUMERATION_ONLY;
703 }
704
705 NTSTATUS
706 NTAPI
707 IopStartAndEnumerateDevice(IN PDEVICE_NODE DeviceNode)
708 {
709 PDEVICE_OBJECT DeviceObject;
710 NTSTATUS Status;
711 PAGED_CODE();
712
713 /* Sanity check */
714 ASSERT((DeviceNode->Flags & DNF_ADDED));
715 ASSERT((DeviceNode->Flags & (DNF_RESOURCE_ASSIGNED |
716 DNF_RESOURCE_REPORTED |
717 DNF_NO_RESOURCE_REQUIRED)));
718
719 /* Get the device object */
720 DeviceObject = DeviceNode->PhysicalDeviceObject;
721
722 /* Check if we're not started yet */
723 if (!(DeviceNode->Flags & DNF_STARTED))
724 {
725 /* Start us */
726 IopStartDevice2(DeviceObject);
727 }
728
729 /* Do we need to query IDs? This happens in the case of manual reporting */
730 #if 0
731 if (DeviceNode->Flags & DNF_NEED_QUERY_IDS)
732 {
733 DPRINT1("Warning: Device node has DNF_NEED_QUERY_IDS\n");
734 /* And that case shouldn't happen yet */
735 ASSERT(FALSE);
736 }
737 #endif
738
739 /* Make sure we're started, and check if we need enumeration */
740 if ((DeviceNode->Flags & DNF_STARTED) &&
741 (DeviceNode->Flags & DNF_NEED_ENUMERATION_ONLY))
742 {
743 /* Enumerate us */
744 IoSynchronousInvalidateDeviceRelations(DeviceObject, BusRelations);
745 Status = STATUS_SUCCESS;
746 }
747 else
748 {
749 /* Nothing to do */
750 Status = STATUS_SUCCESS;
751 }
752
753 /* Return */
754 return Status;
755 }
756
757 NTSTATUS
758 IopStopDevice(
759 PDEVICE_NODE DeviceNode)
760 {
761 NTSTATUS Status;
762
763 DPRINT("Stopping device: %wZ\n", &DeviceNode->InstancePath);
764
765 Status = IopQueryStopDevice(DeviceNode->PhysicalDeviceObject);
766 if (NT_SUCCESS(Status))
767 {
768 IopSendStopDevice(DeviceNode->PhysicalDeviceObject);
769
770 DeviceNode->Flags &= ~(DNF_STARTED | DNF_START_REQUEST_PENDING);
771 DeviceNode->Flags |= DNF_STOPPED;
772
773 return STATUS_SUCCESS;
774 }
775
776 return Status;
777 }
778
779 NTSTATUS
780 IopStartDevice(
781 PDEVICE_NODE DeviceNode)
782 {
783 NTSTATUS Status;
784 HANDLE InstanceHandle = INVALID_HANDLE_VALUE, ControlHandle = INVALID_HANDLE_VALUE;
785 UNICODE_STRING KeyName;
786 OBJECT_ATTRIBUTES ObjectAttributes;
787
788 if (DeviceNode->Flags & DNF_DISABLED)
789 return STATUS_SUCCESS;
790
791 Status = IopAssignDeviceResources(DeviceNode);
792 if (!NT_SUCCESS(Status))
793 goto ByeBye;
794
795 /* New PnP ABI */
796 IopStartAndEnumerateDevice(DeviceNode);
797
798 /* FIX: Should be done in new device instance code */
799 Status = IopCreateDeviceKeyPath(&DeviceNode->InstancePath, 0, &InstanceHandle);
800 if (!NT_SUCCESS(Status))
801 goto ByeBye;
802
803 /* FIX: Should be done in IoXxxPrepareDriverLoading */
804 // {
805 RtlInitUnicodeString(&KeyName, L"Control");
806 InitializeObjectAttributes(&ObjectAttributes,
807 &KeyName,
808 OBJ_CASE_INSENSITIVE,
809 InstanceHandle,
810 NULL);
811 Status = ZwCreateKey(&ControlHandle, KEY_SET_VALUE, &ObjectAttributes, 0, NULL, REG_OPTION_VOLATILE, NULL);
812 if (!NT_SUCCESS(Status))
813 goto ByeBye;
814
815 RtlInitUnicodeString(&KeyName, L"ActiveService");
816 Status = ZwSetValueKey(ControlHandle, &KeyName, 0, REG_SZ, DeviceNode->ServiceName.Buffer, DeviceNode->ServiceName.Length);
817 // }
818
819 ByeBye:
820 if (ControlHandle != INVALID_HANDLE_VALUE)
821 ZwClose(ControlHandle);
822
823 if (InstanceHandle != INVALID_HANDLE_VALUE)
824 ZwClose(InstanceHandle);
825
826 return Status;
827 }
828
829 NTSTATUS
830 NTAPI
831 IopQueryDeviceCapabilities(PDEVICE_NODE DeviceNode,
832 PDEVICE_CAPABILITIES DeviceCaps)
833 {
834 IO_STATUS_BLOCK StatusBlock;
835 IO_STACK_LOCATION Stack;
836 NTSTATUS Status;
837 HANDLE InstanceKey;
838 UNICODE_STRING ValueName;
839
840 /* Set up the Header */
841 RtlZeroMemory(DeviceCaps, sizeof(DEVICE_CAPABILITIES));
842 DeviceCaps->Size = sizeof(DEVICE_CAPABILITIES);
843 DeviceCaps->Version = 1;
844 DeviceCaps->Address = -1;
845 DeviceCaps->UINumber = -1;
846
847 /* Set up the Stack */
848 RtlZeroMemory(&Stack, sizeof(IO_STACK_LOCATION));
849 Stack.Parameters.DeviceCapabilities.Capabilities = DeviceCaps;
850
851 /* Send the IRP */
852 Status = IopInitiatePnpIrp(DeviceNode->PhysicalDeviceObject,
853 &StatusBlock,
854 IRP_MN_QUERY_CAPABILITIES,
855 &Stack);
856 if (!NT_SUCCESS(Status))
857 {
858 DPRINT1("IRP_MN_QUERY_CAPABILITIES failed with status 0x%x\n", Status);
859 return Status;
860 }
861
862 DeviceNode->CapabilityFlags = *(PULONG)((ULONG_PTR)&DeviceCaps->Version + sizeof(DeviceCaps->Version));
863
864 if (DeviceCaps->NoDisplayInUI)
865 DeviceNode->UserFlags |= DNUF_DONT_SHOW_IN_UI;
866 else
867 DeviceNode->UserFlags &= ~DNUF_DONT_SHOW_IN_UI;
868
869 Status = IopCreateDeviceKeyPath(&DeviceNode->InstancePath, 0, &InstanceKey);
870 if (NT_SUCCESS(Status))
871 {
872 /* Set 'Capabilities' value */
873 RtlInitUnicodeString(&ValueName, L"Capabilities");
874 Status = ZwSetValueKey(InstanceKey,
875 &ValueName,
876 0,
877 REG_DWORD,
878 (PVOID)&DeviceNode->CapabilityFlags,
879 sizeof(ULONG));
880
881 /* Set 'UINumber' value */
882 if (DeviceCaps->UINumber != MAXULONG)
883 {
884 RtlInitUnicodeString(&ValueName, L"UINumber");
885 Status = ZwSetValueKey(InstanceKey,
886 &ValueName,
887 0,
888 REG_DWORD,
889 &DeviceCaps->UINumber,
890 sizeof(ULONG));
891 }
892 }
893
894 return Status;
895 }
896
897 static
898 VOID
899 NTAPI
900 IopDeviceRelationsWorker(
901 _In_ PVOID Context)
902 {
903 PLIST_ENTRY ListEntry;
904 PINVALIDATE_DEVICE_RELATION_DATA Data;
905 KIRQL OldIrql;
906
907 KeAcquireSpinLock(&IopDeviceRelationsSpinLock, &OldIrql);
908 while (!IsListEmpty(&IopDeviceRelationsRequestList))
909 {
910 ListEntry = RemoveHeadList(&IopDeviceRelationsRequestList);
911 KeReleaseSpinLock(&IopDeviceRelationsSpinLock, OldIrql);
912 Data = CONTAINING_RECORD(ListEntry,
913 INVALIDATE_DEVICE_RELATION_DATA,
914 RequestListEntry);
915
916 IoSynchronousInvalidateDeviceRelations(Data->DeviceObject,
917 Data->Type);
918
919 ObDereferenceObject(Data->DeviceObject);
920 ExFreePool(Data);
921 KeAcquireSpinLock(&IopDeviceRelationsSpinLock, &OldIrql);
922 }
923 IopDeviceRelationsRequestInProgress = FALSE;
924 KeReleaseSpinLock(&IopDeviceRelationsSpinLock, OldIrql);
925 }
926
927 NTSTATUS
928 IopGetSystemPowerDeviceObject(PDEVICE_OBJECT *DeviceObject)
929 {
930 KIRQL OldIrql;
931
932 if (PopSystemPowerDeviceNode)
933 {
934 KeAcquireSpinLock(&IopDeviceTreeLock, &OldIrql);
935 *DeviceObject = PopSystemPowerDeviceNode->PhysicalDeviceObject;
936 KeReleaseSpinLock(&IopDeviceTreeLock, OldIrql);
937
938 return STATUS_SUCCESS;
939 }
940
941 return STATUS_UNSUCCESSFUL;
942 }
943
944 USHORT
945 NTAPI
946 IopGetBusTypeGuidIndex(LPGUID BusTypeGuid)
947 {
948 USHORT i = 0, FoundIndex = 0xFFFF;
949 ULONG NewSize;
950 PVOID NewList;
951
952 /* Acquire the lock */
953 ExAcquireFastMutex(&PnpBusTypeGuidList->Lock);
954
955 /* Loop all entries */
956 while (i < PnpBusTypeGuidList->GuidCount)
957 {
958 /* Try to find a match */
959 if (RtlCompareMemory(BusTypeGuid,
960 &PnpBusTypeGuidList->Guids[i],
961 sizeof(GUID)) == sizeof(GUID))
962 {
963 /* Found it */
964 FoundIndex = i;
965 goto Quickie;
966 }
967 i++;
968 }
969
970 /* Check if we have to grow the list */
971 if (PnpBusTypeGuidList->GuidCount)
972 {
973 /* Calculate the new size */
974 NewSize = sizeof(IO_BUS_TYPE_GUID_LIST) +
975 (sizeof(GUID) * PnpBusTypeGuidList->GuidCount);
976
977 /* Allocate the new copy */
978 NewList = ExAllocatePool(PagedPool, NewSize);
979
980 if (!NewList) {
981 /* Fail */
982 ExFreePool(PnpBusTypeGuidList);
983 goto Quickie;
984 }
985
986 /* Now copy them, decrease the size too */
987 NewSize -= sizeof(GUID);
988 RtlCopyMemory(NewList, PnpBusTypeGuidList, NewSize);
989
990 /* Free the old list */
991 ExFreePool(PnpBusTypeGuidList);
992
993 /* Use the new buffer */
994 PnpBusTypeGuidList = NewList;
995 }
996
997 /* Copy the new GUID */
998 RtlCopyMemory(&PnpBusTypeGuidList->Guids[PnpBusTypeGuidList->GuidCount],
999 BusTypeGuid,
1000 sizeof(GUID));
1001
1002 /* The new entry is the index */
1003 FoundIndex = (USHORT)PnpBusTypeGuidList->GuidCount;
1004 PnpBusTypeGuidList->GuidCount++;
1005
1006 Quickie:
1007 ExReleaseFastMutex(&PnpBusTypeGuidList->Lock);
1008 return FoundIndex;
1009 }
1010
1011 /*
1012 * DESCRIPTION
1013 * Creates a device node
1014 *
1015 * ARGUMENTS
1016 * ParentNode = Pointer to parent device node
1017 * PhysicalDeviceObject = Pointer to PDO for device object. Pass NULL
1018 * to have the root device node create one
1019 * (eg. for legacy drivers)
1020 * DeviceNode = Pointer to storage for created device node
1021 *
1022 * RETURN VALUE
1023 * Status
1024 */
1025 NTSTATUS
1026 IopCreateDeviceNode(PDEVICE_NODE ParentNode,
1027 PDEVICE_OBJECT PhysicalDeviceObject,
1028 PUNICODE_STRING ServiceName,
1029 PDEVICE_NODE *DeviceNode)
1030 {
1031 PDEVICE_NODE Node;
1032 NTSTATUS Status;
1033 KIRQL OldIrql;
1034 UNICODE_STRING FullServiceName;
1035 UNICODE_STRING LegacyPrefix = RTL_CONSTANT_STRING(L"LEGACY_");
1036 UNICODE_STRING UnknownDeviceName = RTL_CONSTANT_STRING(L"UNKNOWN");
1037 UNICODE_STRING KeyName, ClassName;
1038 PUNICODE_STRING ServiceName1;
1039 ULONG LegacyValue;
1040 UNICODE_STRING ClassGUID;
1041 HANDLE InstanceHandle;
1042
1043 DPRINT("ParentNode 0x%p PhysicalDeviceObject 0x%p ServiceName %wZ\n",
1044 ParentNode, PhysicalDeviceObject, ServiceName);
1045
1046 Node = ExAllocatePoolWithTag(NonPagedPool, sizeof(DEVICE_NODE), TAG_IO_DEVNODE);
1047 if (!Node)
1048 {
1049 return STATUS_INSUFFICIENT_RESOURCES;
1050 }
1051
1052 RtlZeroMemory(Node, sizeof(DEVICE_NODE));
1053
1054 if (!ServiceName)
1055 ServiceName1 = &UnknownDeviceName;
1056 else
1057 ServiceName1 = ServiceName;
1058
1059 if (!PhysicalDeviceObject)
1060 {
1061 FullServiceName.MaximumLength = LegacyPrefix.Length + ServiceName1->Length;
1062 FullServiceName.Length = 0;
1063 FullServiceName.Buffer = ExAllocatePool(PagedPool, FullServiceName.MaximumLength);
1064 if (!FullServiceName.Buffer)
1065 {
1066 ExFreePoolWithTag(Node, TAG_IO_DEVNODE);
1067 return STATUS_INSUFFICIENT_RESOURCES;
1068 }
1069
1070 RtlAppendUnicodeStringToString(&FullServiceName, &LegacyPrefix);
1071 RtlAppendUnicodeStringToString(&FullServiceName, ServiceName1);
1072
1073 Status = PnpRootCreateDevice(&FullServiceName, NULL, &PhysicalDeviceObject, &Node->InstancePath);
1074 if (!NT_SUCCESS(Status))
1075 {
1076 DPRINT1("PnpRootCreateDevice() failed with status 0x%08X\n", Status);
1077 ExFreePoolWithTag(Node, TAG_IO_DEVNODE);
1078 return Status;
1079 }
1080
1081 /* Create the device key for legacy drivers */
1082 Status = IopCreateDeviceKeyPath(&Node->InstancePath, REG_OPTION_VOLATILE, &InstanceHandle);
1083 if (!NT_SUCCESS(Status))
1084 {
1085 ZwClose(InstanceHandle);
1086 ExFreePoolWithTag(Node, TAG_IO_DEVNODE);
1087 ExFreePool(FullServiceName.Buffer);
1088 return Status;
1089 }
1090
1091 Node->ServiceName.Buffer = ExAllocatePool(PagedPool, ServiceName1->Length);
1092 if (!Node->ServiceName.Buffer)
1093 {
1094 ZwClose(InstanceHandle);
1095 ExFreePoolWithTag(Node, TAG_IO_DEVNODE);
1096 ExFreePool(FullServiceName.Buffer);
1097 return Status;
1098 }
1099
1100 Node->ServiceName.MaximumLength = ServiceName1->Length;
1101 Node->ServiceName.Length = 0;
1102
1103 RtlAppendUnicodeStringToString(&Node->ServiceName, ServiceName1);
1104
1105 if (ServiceName)
1106 {
1107 RtlInitUnicodeString(&KeyName, L"Service");
1108 Status = ZwSetValueKey(InstanceHandle, &KeyName, 0, REG_SZ, ServiceName->Buffer, ServiceName->Length);
1109 }
1110
1111 if (NT_SUCCESS(Status))
1112 {
1113 RtlInitUnicodeString(&KeyName, L"Legacy");
1114
1115 LegacyValue = 1;
1116 Status = ZwSetValueKey(InstanceHandle, &KeyName, 0, REG_DWORD, &LegacyValue, sizeof(LegacyValue));
1117 if (NT_SUCCESS(Status))
1118 {
1119 RtlInitUnicodeString(&KeyName, L"Class");
1120
1121 RtlInitUnicodeString(&ClassName, L"LegacyDriver\0");
1122 Status = ZwSetValueKey(InstanceHandle, &KeyName, 0, REG_SZ, ClassName.Buffer, ClassName.Length + sizeof(UNICODE_NULL));
1123 if (NT_SUCCESS(Status))
1124 {
1125 RtlInitUnicodeString(&KeyName, L"ClassGUID");
1126
1127 RtlInitUnicodeString(&ClassGUID, L"{8ECC055D-047F-11D1-A537-0000F8753ED1}\0");
1128 Status = ZwSetValueKey(InstanceHandle, &KeyName, 0, REG_SZ, ClassGUID.Buffer, ClassGUID.Length + sizeof(UNICODE_NULL));
1129 if (NT_SUCCESS(Status))
1130 {
1131 RtlInitUnicodeString(&KeyName, L"DeviceDesc");
1132
1133 Status = ZwSetValueKey(InstanceHandle, &KeyName, 0, REG_SZ, ServiceName1->Buffer, ServiceName1->Length + sizeof(UNICODE_NULL));
1134 }
1135 }
1136 }
1137 }
1138
1139 ZwClose(InstanceHandle);
1140 ExFreePool(FullServiceName.Buffer);
1141
1142 if (!NT_SUCCESS(Status))
1143 {
1144 ExFreePoolWithTag(Node, TAG_IO_DEVNODE);
1145 return Status;
1146 }
1147
1148 IopDeviceNodeSetFlag(Node, DNF_LEGACY_DRIVER);
1149 IopDeviceNodeSetFlag(Node, DNF_PROCESSED);
1150 IopDeviceNodeSetFlag(Node, DNF_ADDED);
1151 IopDeviceNodeSetFlag(Node, DNF_STARTED);
1152 }
1153
1154 Node->PhysicalDeviceObject = PhysicalDeviceObject;
1155
1156 ((PEXTENDED_DEVOBJ_EXTENSION)PhysicalDeviceObject->DeviceObjectExtension)->DeviceNode = Node;
1157
1158 if (ParentNode)
1159 {
1160 KeAcquireSpinLock(&IopDeviceTreeLock, &OldIrql);
1161 Node->Parent = ParentNode;
1162 Node->Sibling = NULL;
1163 if (ParentNode->LastChild == NULL)
1164 {
1165 ParentNode->Child = Node;
1166 ParentNode->LastChild = Node;
1167 }
1168 else
1169 {
1170 ParentNode->LastChild->Sibling = Node;
1171 ParentNode->LastChild = Node;
1172 }
1173 KeReleaseSpinLock(&IopDeviceTreeLock, OldIrql);
1174 Node->Level = ParentNode->Level + 1;
1175 }
1176
1177 PhysicalDeviceObject->Flags &= ~DO_DEVICE_INITIALIZING;
1178
1179 *DeviceNode = Node;
1180
1181 return STATUS_SUCCESS;
1182 }
1183
1184 NTSTATUS
1185 IopFreeDeviceNode(PDEVICE_NODE DeviceNode)
1186 {
1187 KIRQL OldIrql;
1188 PDEVICE_NODE PrevSibling = NULL;
1189
1190 /* All children must be deleted before a parent is deleted */
1191 ASSERT(!DeviceNode->Child);
1192 ASSERT(DeviceNode->PhysicalDeviceObject);
1193
1194 KeAcquireSpinLock(&IopDeviceTreeLock, &OldIrql);
1195
1196 /* Get previous sibling */
1197 if (DeviceNode->Parent && DeviceNode->Parent->Child != DeviceNode)
1198 {
1199 PrevSibling = DeviceNode->Parent->Child;
1200 while (PrevSibling->Sibling != DeviceNode)
1201 PrevSibling = PrevSibling->Sibling;
1202 }
1203
1204 /* Unlink from parent if it exists */
1205 if (DeviceNode->Parent)
1206 {
1207 if (DeviceNode->Parent->LastChild == DeviceNode)
1208 {
1209 DeviceNode->Parent->LastChild = PrevSibling;
1210 if (PrevSibling)
1211 PrevSibling->Sibling = NULL;
1212 }
1213 if (DeviceNode->Parent->Child == DeviceNode)
1214 DeviceNode->Parent->Child = DeviceNode->Sibling;
1215 }
1216
1217 /* Unlink from sibling list */
1218 if (PrevSibling)
1219 PrevSibling->Sibling = DeviceNode->Sibling;
1220
1221 KeReleaseSpinLock(&IopDeviceTreeLock, OldIrql);
1222
1223 RtlFreeUnicodeString(&DeviceNode->InstancePath);
1224
1225 RtlFreeUnicodeString(&DeviceNode->ServiceName);
1226
1227 if (DeviceNode->ResourceList)
1228 {
1229 ExFreePool(DeviceNode->ResourceList);
1230 }
1231
1232 if (DeviceNode->ResourceListTranslated)
1233 {
1234 ExFreePool(DeviceNode->ResourceListTranslated);
1235 }
1236
1237 if (DeviceNode->ResourceRequirements)
1238 {
1239 ExFreePool(DeviceNode->ResourceRequirements);
1240 }
1241
1242 if (DeviceNode->BootResources)
1243 {
1244 ExFreePool(DeviceNode->BootResources);
1245 }
1246
1247 ((PEXTENDED_DEVOBJ_EXTENSION)DeviceNode->PhysicalDeviceObject->DeviceObjectExtension)->DeviceNode = NULL;
1248 ExFreePoolWithTag(DeviceNode, TAG_IO_DEVNODE);
1249
1250 return STATUS_SUCCESS;
1251 }
1252
1253 NTSTATUS
1254 NTAPI
1255 IopSynchronousCall(IN PDEVICE_OBJECT DeviceObject,
1256 IN PIO_STACK_LOCATION IoStackLocation,
1257 OUT PVOID *Information)
1258 {
1259 PIRP Irp;
1260 PIO_STACK_LOCATION IrpStack;
1261 IO_STATUS_BLOCK IoStatusBlock;
1262 KEVENT Event;
1263 NTSTATUS Status;
1264 PDEVICE_OBJECT TopDeviceObject;
1265 PAGED_CODE();
1266
1267 /* Call the top of the device stack */
1268 TopDeviceObject = IoGetAttachedDeviceReference(DeviceObject);
1269
1270 /* Allocate an IRP */
1271 Irp = IoAllocateIrp(TopDeviceObject->StackSize, FALSE);
1272 if (!Irp) return STATUS_INSUFFICIENT_RESOURCES;
1273
1274 /* Initialize to failure */
1275 Irp->IoStatus.Status = IoStatusBlock.Status = STATUS_NOT_SUPPORTED;
1276 Irp->IoStatus.Information = IoStatusBlock.Information = 0;
1277
1278 /* Special case for IRP_MN_FILTER_RESOURCE_REQUIREMENTS */
1279 if (IoStackLocation->MinorFunction == IRP_MN_FILTER_RESOURCE_REQUIREMENTS)
1280 {
1281 /* Copy the resource requirements list into the IOSB */
1282 Irp->IoStatus.Information =
1283 IoStatusBlock.Information = (ULONG_PTR)IoStackLocation->Parameters.FilterResourceRequirements.IoResourceRequirementList;
1284 }
1285
1286 /* Initialize the event */
1287 KeInitializeEvent(&Event, SynchronizationEvent, FALSE);
1288
1289 /* Set them up */
1290 Irp->UserIosb = &IoStatusBlock;
1291 Irp->UserEvent = &Event;
1292
1293 /* Queue the IRP */
1294 Irp->Tail.Overlay.Thread = PsGetCurrentThread();
1295 IoQueueThreadIrp(Irp);
1296
1297 /* Copy-in the stack */
1298 IrpStack = IoGetNextIrpStackLocation(Irp);
1299 *IrpStack = *IoStackLocation;
1300
1301 /* Call the driver */
1302 Status = IoCallDriver(TopDeviceObject, Irp);
1303 if (Status == STATUS_PENDING)
1304 {
1305 /* Wait for it */
1306 KeWaitForSingleObject(&Event,
1307 Executive,
1308 KernelMode,
1309 FALSE,
1310 NULL);
1311 Status = IoStatusBlock.Status;
1312 }
1313
1314 /* Remove the reference */
1315 ObDereferenceObject(TopDeviceObject);
1316
1317 /* Return the information */
1318 *Information = (PVOID)IoStatusBlock.Information;
1319 return Status;
1320 }
1321
1322 NTSTATUS
1323 NTAPI
1324 IopInitiatePnpIrp(IN PDEVICE_OBJECT DeviceObject,
1325 IN OUT PIO_STATUS_BLOCK IoStatusBlock,
1326 IN UCHAR MinorFunction,
1327 IN PIO_STACK_LOCATION Stack OPTIONAL)
1328 {
1329 IO_STACK_LOCATION IoStackLocation;
1330
1331 /* Fill out the stack information */
1332 RtlZeroMemory(&IoStackLocation, sizeof(IO_STACK_LOCATION));
1333 IoStackLocation.MajorFunction = IRP_MJ_PNP;
1334 IoStackLocation.MinorFunction = MinorFunction;
1335 if (Stack)
1336 {
1337 /* Copy the rest */
1338 RtlCopyMemory(&IoStackLocation.Parameters,
1339 &Stack->Parameters,
1340 sizeof(Stack->Parameters));
1341 }
1342
1343 /* Do the PnP call */
1344 IoStatusBlock->Status = IopSynchronousCall(DeviceObject,
1345 &IoStackLocation,
1346 (PVOID)&IoStatusBlock->Information);
1347 return IoStatusBlock->Status;
1348 }
1349
1350 NTSTATUS
1351 IopTraverseDeviceTreeNode(PDEVICETREE_TRAVERSE_CONTEXT Context)
1352 {
1353 PDEVICE_NODE ParentDeviceNode;
1354 PDEVICE_NODE ChildDeviceNode;
1355 NTSTATUS Status;
1356
1357 /* Copy context data so we don't overwrite it in subsequent calls to this function */
1358 ParentDeviceNode = Context->DeviceNode;
1359
1360 /* Call the action routine */
1361 Status = (Context->Action)(ParentDeviceNode, Context->Context);
1362 if (!NT_SUCCESS(Status))
1363 {
1364 return Status;
1365 }
1366
1367 /* Traversal of all children nodes */
1368 for (ChildDeviceNode = ParentDeviceNode->Child;
1369 ChildDeviceNode != NULL;
1370 ChildDeviceNode = ChildDeviceNode->Sibling)
1371 {
1372 /* Pass the current device node to the action routine */
1373 Context->DeviceNode = ChildDeviceNode;
1374
1375 Status = IopTraverseDeviceTreeNode(Context);
1376 if (!NT_SUCCESS(Status))
1377 {
1378 return Status;
1379 }
1380 }
1381
1382 return Status;
1383 }
1384
1385
1386 NTSTATUS
1387 IopTraverseDeviceTree(PDEVICETREE_TRAVERSE_CONTEXT Context)
1388 {
1389 NTSTATUS Status;
1390
1391 DPRINT("Context 0x%p\n", Context);
1392
1393 DPRINT("IopTraverseDeviceTree(DeviceNode 0x%p FirstDeviceNode 0x%p Action %p Context 0x%p)\n",
1394 Context->DeviceNode, Context->FirstDeviceNode, Context->Action, Context->Context);
1395
1396 /* Start from the specified device node */
1397 Context->DeviceNode = Context->FirstDeviceNode;
1398
1399 /* Recursively traverse the device tree */
1400 Status = IopTraverseDeviceTreeNode(Context);
1401 if (Status == STATUS_UNSUCCESSFUL)
1402 {
1403 /* The action routine just wanted to terminate the traversal with status
1404 code STATUS_SUCCESS */
1405 Status = STATUS_SUCCESS;
1406 }
1407
1408 return Status;
1409 }
1410
1411
1412 /*
1413 * IopCreateDeviceKeyPath
1414 *
1415 * Creates a registry key
1416 *
1417 * Parameters
1418 * RegistryPath
1419 * Name of the key to be created.
1420 * Handle
1421 * Handle to the newly created key
1422 *
1423 * Remarks
1424 * This method can create nested trees, so parent of RegistryPath can
1425 * be not existant, and will be created if needed.
1426 */
1427 NTSTATUS
1428 NTAPI
1429 IopCreateDeviceKeyPath(IN PCUNICODE_STRING RegistryPath,
1430 IN ULONG CreateOptions,
1431 OUT PHANDLE Handle)
1432 {
1433 UNICODE_STRING EnumU = RTL_CONSTANT_STRING(ENUM_ROOT);
1434 HANDLE hParent = NULL, hKey;
1435 OBJECT_ATTRIBUTES ObjectAttributes;
1436 UNICODE_STRING KeyName;
1437 LPCWSTR Current, Last;
1438 USHORT Length;
1439 NTSTATUS Status;
1440
1441 /* Assume failure */
1442 *Handle = NULL;
1443
1444 /* Create a volatile device tree in 1st stage so we have a clean slate
1445 * for enumeration using the correct HAL (chosen in 1st stage setup) */
1446 if (ExpInTextModeSetup) CreateOptions |= REG_OPTION_VOLATILE;
1447
1448 /* Open root key for device instances */
1449 Status = IopOpenRegistryKeyEx(&hParent, NULL, &EnumU, KEY_CREATE_SUB_KEY);
1450 if (!NT_SUCCESS(Status))
1451 {
1452 DPRINT1("ZwOpenKey('%wZ') failed with status 0x%08lx\n", &EnumU, Status);
1453 return Status;
1454 }
1455
1456 Current = KeyName.Buffer = RegistryPath->Buffer;
1457 Last = &RegistryPath->Buffer[RegistryPath->Length / sizeof(WCHAR)];
1458
1459 /* Go up to the end of the string */
1460 while (Current <= Last)
1461 {
1462 if (Current != Last && *Current != '\\')
1463 {
1464 /* Not the end of the string and not a separator */
1465 Current++;
1466 continue;
1467 }
1468
1469 /* Prepare relative key name */
1470 Length = (USHORT)((ULONG_PTR)Current - (ULONG_PTR)KeyName.Buffer);
1471 KeyName.MaximumLength = KeyName.Length = Length;
1472 DPRINT("Create '%wZ'\n", &KeyName);
1473
1474 /* Open key */
1475 InitializeObjectAttributes(&ObjectAttributes,
1476 &KeyName,
1477 OBJ_CASE_INSENSITIVE,
1478 hParent,
1479 NULL);
1480 Status = ZwCreateKey(&hKey,
1481 Current == Last ? KEY_ALL_ACCESS : KEY_CREATE_SUB_KEY,
1482 &ObjectAttributes,
1483 0,
1484 NULL,
1485 CreateOptions,
1486 NULL);
1487
1488 /* Close parent key handle, we don't need it anymore */
1489 if (hParent)
1490 ZwClose(hParent);
1491
1492 /* Key opening/creating failed? */
1493 if (!NT_SUCCESS(Status))
1494 {
1495 DPRINT1("ZwCreateKey('%wZ') failed with status 0x%08lx\n", &KeyName, Status);
1496 return Status;
1497 }
1498
1499 /* Check if it is the end of the string */
1500 if (Current == Last)
1501 {
1502 /* Yes, return success */
1503 *Handle = hKey;
1504 return STATUS_SUCCESS;
1505 }
1506
1507 /* Start with this new parent key */
1508 hParent = hKey;
1509 Current++;
1510 KeyName.Buffer = (LPWSTR)Current;
1511 }
1512
1513 return STATUS_UNSUCCESSFUL;
1514 }
1515
1516 NTSTATUS
1517 IopSetDeviceInstanceData(HANDLE InstanceKey,
1518 PDEVICE_NODE DeviceNode)
1519 {
1520 OBJECT_ATTRIBUTES ObjectAttributes;
1521 UNICODE_STRING KeyName;
1522 HANDLE LogConfKey;
1523 ULONG ResCount;
1524 ULONG ResultLength;
1525 NTSTATUS Status;
1526 HANDLE ControlHandle;
1527
1528 DPRINT("IopSetDeviceInstanceData() called\n");
1529
1530 /* Create the 'LogConf' key */
1531 RtlInitUnicodeString(&KeyName, L"LogConf");
1532 InitializeObjectAttributes(&ObjectAttributes,
1533 &KeyName,
1534 OBJ_CASE_INSENSITIVE,
1535 InstanceKey,
1536 NULL);
1537 Status = ZwCreateKey(&LogConfKey,
1538 KEY_ALL_ACCESS,
1539 &ObjectAttributes,
1540 0,
1541 NULL,
1542 REG_OPTION_VOLATILE,
1543 NULL);
1544 if (NT_SUCCESS(Status))
1545 {
1546 /* Set 'BootConfig' value */
1547 if (DeviceNode->BootResources != NULL)
1548 {
1549 ResCount = DeviceNode->BootResources->Count;
1550 if (ResCount != 0)
1551 {
1552 RtlInitUnicodeString(&KeyName, L"BootConfig");
1553 Status = ZwSetValueKey(LogConfKey,
1554 &KeyName,
1555 0,
1556 REG_RESOURCE_LIST,
1557 DeviceNode->BootResources,
1558 PnpDetermineResourceListSize(DeviceNode->BootResources));
1559 }
1560 }
1561
1562 /* Set 'BasicConfigVector' value */
1563 if (DeviceNode->ResourceRequirements != NULL &&
1564 DeviceNode->ResourceRequirements->ListSize != 0)
1565 {
1566 RtlInitUnicodeString(&KeyName, L"BasicConfigVector");
1567 Status = ZwSetValueKey(LogConfKey,
1568 &KeyName,
1569 0,
1570 REG_RESOURCE_REQUIREMENTS_LIST,
1571 DeviceNode->ResourceRequirements,
1572 DeviceNode->ResourceRequirements->ListSize);
1573 }
1574
1575 ZwClose(LogConfKey);
1576 }
1577
1578 /* Set the 'ConfigFlags' value */
1579 RtlInitUnicodeString(&KeyName, L"ConfigFlags");
1580 Status = ZwQueryValueKey(InstanceKey,
1581 &KeyName,
1582 KeyValueBasicInformation,
1583 NULL,
1584 0,
1585 &ResultLength);
1586 if (Status == STATUS_OBJECT_NAME_NOT_FOUND)
1587 {
1588 /* Write the default value */
1589 ULONG DefaultConfigFlags = 0;
1590 Status = ZwSetValueKey(InstanceKey,
1591 &KeyName,
1592 0,
1593 REG_DWORD,
1594 &DefaultConfigFlags,
1595 sizeof(DefaultConfigFlags));
1596 }
1597
1598 /* Create the 'Control' key */
1599 RtlInitUnicodeString(&KeyName, L"Control");
1600 InitializeObjectAttributes(&ObjectAttributes,
1601 &KeyName,
1602 OBJ_CASE_INSENSITIVE,
1603 InstanceKey,
1604 NULL);
1605 Status = ZwCreateKey(&ControlHandle, 0, &ObjectAttributes, 0, NULL, REG_OPTION_VOLATILE, NULL);
1606
1607 if (NT_SUCCESS(Status))
1608 ZwClose(ControlHandle);
1609
1610 DPRINT("IopSetDeviceInstanceData() done\n");
1611
1612 return Status;
1613 }
1614
1615 /*
1616 * IopGetParentIdPrefix
1617 *
1618 * Retrieve (or create) a string which identifies a device.
1619 *
1620 * Parameters
1621 * DeviceNode
1622 * Pointer to device node.
1623 * ParentIdPrefix
1624 * Pointer to the string where is returned the parent node identifier
1625 *
1626 * Remarks
1627 * If the return code is STATUS_SUCCESS, the ParentIdPrefix string is
1628 * valid and its Buffer field is NULL-terminated. The caller needs to
1629 * to free the string with RtlFreeUnicodeString when it is no longer
1630 * needed.
1631 */
1632
1633 NTSTATUS
1634 IopGetParentIdPrefix(PDEVICE_NODE DeviceNode,
1635 PUNICODE_STRING ParentIdPrefix)
1636 {
1637 ULONG KeyNameBufferLength;
1638 PKEY_VALUE_PARTIAL_INFORMATION ParentIdPrefixInformation = NULL;
1639 UNICODE_STRING KeyName = {0, 0, NULL};
1640 UNICODE_STRING KeyValue;
1641 UNICODE_STRING ValueName;
1642 HANDLE hKey = NULL;
1643 ULONG crc32;
1644 NTSTATUS Status;
1645
1646 /* HACK: As long as some devices have a NULL device
1647 * instance path, the following test is required :(
1648 */
1649 if (DeviceNode->Parent->InstancePath.Length == 0)
1650 {
1651 DPRINT1("Parent of %wZ has NULL Instance path, please report!\n",
1652 &DeviceNode->InstancePath);
1653 return STATUS_UNSUCCESSFUL;
1654 }
1655
1656 /* 1. Try to retrieve ParentIdPrefix from registry */
1657 KeyNameBufferLength = FIELD_OFFSET(KEY_VALUE_PARTIAL_INFORMATION, Data[0]) + MAX_PATH * sizeof(WCHAR);
1658 ParentIdPrefixInformation = ExAllocatePool(PagedPool, KeyNameBufferLength + sizeof(WCHAR));
1659 if (!ParentIdPrefixInformation)
1660 {
1661 return STATUS_INSUFFICIENT_RESOURCES;
1662 }
1663
1664 KeyName.Buffer = ExAllocatePool(PagedPool, (49 * sizeof(WCHAR)) + DeviceNode->Parent->InstancePath.Length);
1665 if (!KeyName.Buffer)
1666 {
1667 Status = STATUS_INSUFFICIENT_RESOURCES;
1668 goto cleanup;
1669 }
1670 KeyName.Length = 0;
1671 KeyName.MaximumLength = (49 * sizeof(WCHAR)) + DeviceNode->Parent->InstancePath.Length;
1672
1673 RtlAppendUnicodeToString(&KeyName, L"\\Registry\\Machine\\System\\CurrentControlSet\\Enum\\");
1674 RtlAppendUnicodeStringToString(&KeyName, &DeviceNode->Parent->InstancePath);
1675
1676 Status = IopOpenRegistryKeyEx(&hKey, NULL, &KeyName, KEY_QUERY_VALUE | KEY_SET_VALUE);
1677 if (!NT_SUCCESS(Status))
1678 goto cleanup;
1679 RtlInitUnicodeString(&ValueName, L"ParentIdPrefix");
1680 Status = ZwQueryValueKey(
1681 hKey, &ValueName,
1682 KeyValuePartialInformation, ParentIdPrefixInformation,
1683 KeyNameBufferLength, &KeyNameBufferLength);
1684 if (NT_SUCCESS(Status))
1685 {
1686 if (ParentIdPrefixInformation->Type != REG_SZ)
1687 Status = STATUS_UNSUCCESSFUL;
1688 else
1689 {
1690 KeyValue.Length = KeyValue.MaximumLength = (USHORT)ParentIdPrefixInformation->DataLength;
1691 KeyValue.Buffer = (PWSTR)ParentIdPrefixInformation->Data;
1692 }
1693 goto cleanup;
1694 }
1695 if (Status != STATUS_OBJECT_NAME_NOT_FOUND)
1696 {
1697 KeyValue.Length = KeyValue.MaximumLength = (USHORT)ParentIdPrefixInformation->DataLength;
1698 KeyValue.Buffer = (PWSTR)ParentIdPrefixInformation->Data;
1699 goto cleanup;
1700 }
1701
1702 /* 2. Create the ParentIdPrefix value */
1703 crc32 = RtlComputeCrc32(0,
1704 (PUCHAR)DeviceNode->Parent->InstancePath.Buffer,
1705 DeviceNode->Parent->InstancePath.Length);
1706
1707 swprintf((PWSTR)ParentIdPrefixInformation->Data, L"%lx&%lx", DeviceNode->Parent->Level, crc32);
1708 RtlInitUnicodeString(&KeyValue, (PWSTR)ParentIdPrefixInformation->Data);
1709
1710 /* 3. Try to write the ParentIdPrefix to registry */
1711 Status = ZwSetValueKey(hKey,
1712 &ValueName,
1713 0,
1714 REG_SZ,
1715 (PVOID)KeyValue.Buffer,
1716 ((ULONG)wcslen(KeyValue.Buffer) + 1) * sizeof(WCHAR));
1717
1718 cleanup:
1719 if (NT_SUCCESS(Status))
1720 {
1721 /* Duplicate the string to return it */
1722 Status = RtlDuplicateUnicodeString(RTL_DUPLICATE_UNICODE_STRING_NULL_TERMINATE, &KeyValue, ParentIdPrefix);
1723 }
1724 ExFreePool(ParentIdPrefixInformation);
1725 RtlFreeUnicodeString(&KeyName);
1726 if (hKey != NULL)
1727 ZwClose(hKey);
1728 return Status;
1729 }
1730
1731 NTSTATUS
1732 IopQueryHardwareIds(PDEVICE_NODE DeviceNode,
1733 HANDLE InstanceKey)
1734 {
1735 IO_STACK_LOCATION Stack;
1736 IO_STATUS_BLOCK IoStatusBlock;
1737 PWSTR Ptr;
1738 UNICODE_STRING ValueName;
1739 NTSTATUS Status;
1740 ULONG Length, TotalLength;
1741
1742 DPRINT("Sending IRP_MN_QUERY_ID.BusQueryHardwareIDs to device stack\n");
1743
1744 RtlZeroMemory(&Stack, sizeof(Stack));
1745 Stack.Parameters.QueryId.IdType = BusQueryHardwareIDs;
1746 Status = IopInitiatePnpIrp(DeviceNode->PhysicalDeviceObject,
1747 &IoStatusBlock,
1748 IRP_MN_QUERY_ID,
1749 &Stack);
1750 if (NT_SUCCESS(Status))
1751 {
1752 /*
1753 * FIXME: Check for valid characters, if there is invalid characters
1754 * then bugcheck.
1755 */
1756 TotalLength = 0;
1757 Ptr = (PWSTR)IoStatusBlock.Information;
1758 DPRINT("Hardware IDs:\n");
1759 while (*Ptr)
1760 {
1761 DPRINT(" %S\n", Ptr);
1762 Length = (ULONG)wcslen(Ptr) + 1;
1763
1764 Ptr += Length;
1765 TotalLength += Length;
1766 }
1767 DPRINT("TotalLength: %hu\n", TotalLength);
1768 DPRINT("\n");
1769
1770 RtlInitUnicodeString(&ValueName, L"HardwareID");
1771 Status = ZwSetValueKey(InstanceKey,
1772 &ValueName,
1773 0,
1774 REG_MULTI_SZ,
1775 (PVOID)IoStatusBlock.Information,
1776 (TotalLength + 1) * sizeof(WCHAR));
1777 if (!NT_SUCCESS(Status))
1778 {
1779 DPRINT1("ZwSetValueKey() failed (Status %lx)\n", Status);
1780 }
1781 }
1782 else
1783 {
1784 DPRINT("IopInitiatePnpIrp() failed (Status %x)\n", Status);
1785 }
1786
1787 return Status;
1788 }
1789
1790 NTSTATUS
1791 IopQueryCompatibleIds(PDEVICE_NODE DeviceNode,
1792 HANDLE InstanceKey)
1793 {
1794 IO_STACK_LOCATION Stack;
1795 IO_STATUS_BLOCK IoStatusBlock;
1796 PWSTR Ptr;
1797 UNICODE_STRING ValueName;
1798 NTSTATUS Status;
1799 ULONG Length, TotalLength;
1800
1801 DPRINT("Sending IRP_MN_QUERY_ID.BusQueryCompatibleIDs to device stack\n");
1802
1803 RtlZeroMemory(&Stack, sizeof(Stack));
1804 Stack.Parameters.QueryId.IdType = BusQueryCompatibleIDs;
1805 Status = IopInitiatePnpIrp(
1806 DeviceNode->PhysicalDeviceObject,
1807 &IoStatusBlock,
1808 IRP_MN_QUERY_ID,
1809 &Stack);
1810 if (NT_SUCCESS(Status) && IoStatusBlock.Information)
1811 {
1812 /*
1813 * FIXME: Check for valid characters, if there is invalid characters
1814 * then bugcheck.
1815 */
1816 TotalLength = 0;
1817 Ptr = (PWSTR)IoStatusBlock.Information;
1818 DPRINT("Compatible IDs:\n");
1819 while (*Ptr)
1820 {
1821 DPRINT(" %S\n", Ptr);
1822 Length = (ULONG)wcslen(Ptr) + 1;
1823
1824 Ptr += Length;
1825 TotalLength += Length;
1826 }
1827 DPRINT("TotalLength: %hu\n", TotalLength);
1828 DPRINT("\n");
1829
1830 RtlInitUnicodeString(&ValueName, L"CompatibleIDs");
1831 Status = ZwSetValueKey(InstanceKey,
1832 &ValueName,
1833 0,
1834 REG_MULTI_SZ,
1835 (PVOID)IoStatusBlock.Information,
1836 (TotalLength + 1) * sizeof(WCHAR));
1837 if (!NT_SUCCESS(Status))
1838 {
1839 DPRINT1("ZwSetValueKey() failed (Status %lx) or no Compatible ID returned\n", Status);
1840 }
1841 }
1842 else
1843 {
1844 DPRINT("IopInitiatePnpIrp() failed (Status %x)\n", Status);
1845 }
1846
1847 return Status;
1848 }
1849
1850
1851 /*
1852 * IopActionInterrogateDeviceStack
1853 *
1854 * Retrieve information for all (direct) child nodes of a parent node.
1855 *
1856 * Parameters
1857 * DeviceNode
1858 * Pointer to device node.
1859 * Context
1860 * Pointer to parent node to retrieve child node information for.
1861 *
1862 * Remarks
1863 * Any errors that occur are logged instead so that all child services have a chance
1864 * of being interrogated.
1865 */
1866
1867 NTSTATUS
1868 IopActionInterrogateDeviceStack(PDEVICE_NODE DeviceNode,
1869 PVOID Context)
1870 {
1871 IO_STATUS_BLOCK IoStatusBlock;
1872 PDEVICE_NODE ParentDeviceNode;
1873 WCHAR InstancePath[MAX_PATH];
1874 IO_STACK_LOCATION Stack;
1875 NTSTATUS Status;
1876 ULONG RequiredLength;
1877 LCID LocaleId;
1878 HANDLE InstanceKey = NULL;
1879 UNICODE_STRING ValueName;
1880 UNICODE_STRING ParentIdPrefix = { 0, 0, NULL };
1881 UNICODE_STRING InstancePathU;
1882 DEVICE_CAPABILITIES DeviceCapabilities;
1883 PDEVICE_OBJECT OldDeviceObject;
1884
1885 DPRINT("IopActionInterrogateDeviceStack(%p, %p)\n", DeviceNode, Context);
1886 DPRINT("PDO 0x%p\n", DeviceNode->PhysicalDeviceObject);
1887
1888 ParentDeviceNode = (PDEVICE_NODE)Context;
1889
1890 /*
1891 * We are called for the parent too, but we don't need to do special
1892 * handling for this node
1893 */
1894
1895 if (DeviceNode == ParentDeviceNode)
1896 {
1897 DPRINT("Success\n");
1898 return STATUS_SUCCESS;
1899 }
1900
1901 /*
1902 * Make sure this device node is a direct child of the parent device node
1903 * that is given as an argument
1904 */
1905
1906 if (DeviceNode->Parent != ParentDeviceNode)
1907 {
1908 DPRINT("Skipping 2+ level child\n");
1909 return STATUS_SUCCESS;
1910 }
1911
1912 /* Skip processing if it was already completed before */
1913 if (DeviceNode->Flags & DNF_PROCESSED)
1914 {
1915 /* Nothing to do */
1916 return STATUS_SUCCESS;
1917 }
1918
1919 /* Get Locale ID */
1920 Status = ZwQueryDefaultLocale(FALSE, &LocaleId);
1921 if (!NT_SUCCESS(Status))
1922 {
1923 DPRINT1("ZwQueryDefaultLocale() failed with status 0x%lx\n", Status);
1924 return Status;
1925 }
1926
1927 /*
1928 * FIXME: For critical errors, cleanup and disable device, but always
1929 * return STATUS_SUCCESS.
1930 */
1931
1932 DPRINT("Sending IRP_MN_QUERY_ID.BusQueryDeviceID to device stack\n");
1933
1934 Stack.Parameters.QueryId.IdType = BusQueryDeviceID;
1935 Status = IopInitiatePnpIrp(DeviceNode->PhysicalDeviceObject,
1936 &IoStatusBlock,
1937 IRP_MN_QUERY_ID,
1938 &Stack);
1939 if (NT_SUCCESS(Status))
1940 {
1941 /* Copy the device id string */
1942 wcscpy(InstancePath, (PWSTR)IoStatusBlock.Information);
1943
1944 /*
1945 * FIXME: Check for valid characters, if there is invalid characters
1946 * then bugcheck.
1947 */
1948 }
1949 else
1950 {
1951 DPRINT1("IopInitiatePnpIrp() failed (Status %x)\n", Status);
1952
1953 /* We have to return success otherwise we abort the traverse operation */
1954 return STATUS_SUCCESS;
1955 }
1956
1957 DPRINT("Sending IRP_MN_QUERY_CAPABILITIES to device stack (after enumeration)\n");
1958
1959 Status = IopQueryDeviceCapabilities(DeviceNode, &DeviceCapabilities);
1960 if (!NT_SUCCESS(Status))
1961 {
1962 DPRINT1("IopInitiatePnpIrp() failed (Status 0x%08lx)\n", Status);
1963
1964 /* We have to return success otherwise we abort the traverse operation */
1965 return STATUS_SUCCESS;
1966 }
1967
1968 /* This bit is only check after enumeration */
1969 if (DeviceCapabilities.HardwareDisabled)
1970 {
1971 /* FIXME: Cleanup device */
1972 DeviceNode->Flags |= DNF_DISABLED;
1973 return STATUS_SUCCESS;
1974 }
1975 else
1976 DeviceNode->Flags &= ~DNF_DISABLED;
1977
1978 if (!DeviceCapabilities.UniqueID)
1979 {
1980 /* Device has not a unique ID. We need to prepend parent bus unique identifier */
1981 DPRINT("Instance ID is not unique\n");
1982 Status = IopGetParentIdPrefix(DeviceNode, &ParentIdPrefix);
1983 if (!NT_SUCCESS(Status))
1984 {
1985 DPRINT1("IopGetParentIdPrefix() failed (Status 0x%08lx)\n", Status);
1986
1987 /* We have to return success otherwise we abort the traverse operation */
1988 return STATUS_SUCCESS;
1989 }
1990 }
1991
1992 DPRINT("Sending IRP_MN_QUERY_ID.BusQueryInstanceID to device stack\n");
1993
1994 Stack.Parameters.QueryId.IdType = BusQueryInstanceID;
1995 Status = IopInitiatePnpIrp(DeviceNode->PhysicalDeviceObject,
1996 &IoStatusBlock,
1997 IRP_MN_QUERY_ID,
1998 &Stack);
1999 if (NT_SUCCESS(Status))
2000 {
2001 /* Append the instance id string */
2002 wcscat(InstancePath, L"\\");
2003 if (ParentIdPrefix.Length > 0)
2004 {
2005 /* Add information from parent bus device to InstancePath */
2006 wcscat(InstancePath, ParentIdPrefix.Buffer);
2007 if (IoStatusBlock.Information && *(PWSTR)IoStatusBlock.Information)
2008 wcscat(InstancePath, L"&");
2009 }
2010 if (IoStatusBlock.Information)
2011 wcscat(InstancePath, (PWSTR)IoStatusBlock.Information);
2012
2013 /*
2014 * FIXME: Check for valid characters, if there is invalid characters
2015 * then bugcheck
2016 */
2017 }
2018 else
2019 {
2020 DPRINT("IopInitiatePnpIrp() failed (Status %x)\n", Status);
2021 }
2022 RtlFreeUnicodeString(&ParentIdPrefix);
2023
2024 if (!RtlCreateUnicodeString(&InstancePathU, InstancePath))
2025 {
2026 DPRINT("No resources\n");
2027 /* FIXME: Cleanup and disable device */
2028 }
2029
2030 /* Verify that this is not a duplicate */
2031 OldDeviceObject = IopGetDeviceObjectFromDeviceInstance(&InstancePathU);
2032 if (OldDeviceObject != NULL)
2033 {
2034 PDEVICE_NODE OldDeviceNode = IopGetDeviceNode(OldDeviceObject);
2035
2036 DPRINT1("Duplicate device instance '%wZ'\n", &InstancePathU);
2037 DPRINT1("Current instance parent: '%wZ'\n", &DeviceNode->Parent->InstancePath);
2038 DPRINT1("Old instance parent: '%wZ'\n", &OldDeviceNode->Parent->InstancePath);
2039
2040 KeBugCheckEx(PNP_DETECTED_FATAL_ERROR,
2041 0x01,
2042 (ULONG_PTR)DeviceNode->PhysicalDeviceObject,
2043 (ULONG_PTR)OldDeviceObject,
2044 0);
2045 }
2046
2047 DeviceNode->InstancePath = InstancePathU;
2048
2049 DPRINT("InstancePath is %S\n", DeviceNode->InstancePath.Buffer);
2050
2051 /*
2052 * Create registry key for the instance id, if it doesn't exist yet
2053 */
2054 Status = IopCreateDeviceKeyPath(&DeviceNode->InstancePath, 0, &InstanceKey);
2055 if (!NT_SUCCESS(Status))
2056 {
2057 DPRINT1("Failed to create the instance key! (Status %lx)\n", Status);
2058
2059 /* We have to return success otherwise we abort the traverse operation */
2060 return STATUS_SUCCESS;
2061 }
2062
2063 IopQueryHardwareIds(DeviceNode, InstanceKey);
2064
2065 IopQueryCompatibleIds(DeviceNode, InstanceKey);
2066
2067 DPRINT("Sending IRP_MN_QUERY_DEVICE_TEXT.DeviceTextDescription to device stack\n");
2068
2069 Stack.Parameters.QueryDeviceText.DeviceTextType = DeviceTextDescription;
2070 Stack.Parameters.QueryDeviceText.LocaleId = LocaleId;
2071 Status = IopInitiatePnpIrp(
2072 DeviceNode->PhysicalDeviceObject,
2073 &IoStatusBlock,
2074 IRP_MN_QUERY_DEVICE_TEXT,
2075 &Stack);
2076 /* This key is mandatory, so even if the Irp fails, we still write it */
2077 RtlInitUnicodeString(&ValueName, L"DeviceDesc");
2078 if (ZwQueryValueKey(InstanceKey, &ValueName, KeyValueBasicInformation, NULL, 0, &RequiredLength) == STATUS_OBJECT_NAME_NOT_FOUND)
2079 {
2080 if (NT_SUCCESS(Status) &&
2081 IoStatusBlock.Information &&
2082 (*(PWSTR)IoStatusBlock.Information != 0))
2083 {
2084 /* This key is overriden when a driver is installed. Don't write the
2085 * new description if another one already exists */
2086 Status = ZwSetValueKey(InstanceKey,
2087 &ValueName,
2088 0,
2089 REG_SZ,
2090 (PVOID)IoStatusBlock.Information,
2091 ((ULONG)wcslen((PWSTR)IoStatusBlock.Information) + 1) * sizeof(WCHAR));
2092 }
2093 else
2094 {
2095 UNICODE_STRING DeviceDesc = RTL_CONSTANT_STRING(L"Unknown device");
2096 DPRINT("Driver didn't return DeviceDesc (Status 0x%08lx), so place unknown device there\n", Status);
2097
2098 Status = ZwSetValueKey(InstanceKey,
2099 &ValueName,
2100 0,
2101 REG_SZ,
2102 DeviceDesc.Buffer,
2103 DeviceDesc.MaximumLength);
2104
2105 if (!NT_SUCCESS(Status))
2106 {
2107 DPRINT1("ZwSetValueKey() failed (Status 0x%lx)\n", Status);
2108 }
2109
2110 }
2111 }
2112
2113 DPRINT("Sending IRP_MN_QUERY_DEVICE_TEXT.DeviceTextLocation to device stack\n");
2114
2115 Stack.Parameters.QueryDeviceText.DeviceTextType = DeviceTextLocationInformation;
2116 Stack.Parameters.QueryDeviceText.LocaleId = LocaleId;
2117 Status = IopInitiatePnpIrp(
2118 DeviceNode->PhysicalDeviceObject,
2119 &IoStatusBlock,
2120 IRP_MN_QUERY_DEVICE_TEXT,
2121 &Stack);
2122 if (NT_SUCCESS(Status) && IoStatusBlock.Information)
2123 {
2124 DPRINT("LocationInformation: %S\n", (PWSTR)IoStatusBlock.Information);
2125 RtlInitUnicodeString(&ValueName, L"LocationInformation");
2126 Status = ZwSetValueKey(InstanceKey,
2127 &ValueName,
2128 0,
2129 REG_SZ,
2130 (PVOID)IoStatusBlock.Information,
2131 ((ULONG)wcslen((PWSTR)IoStatusBlock.Information) + 1) * sizeof(WCHAR));
2132 if (!NT_SUCCESS(Status))
2133 {
2134 DPRINT1("ZwSetValueKey() failed (Status %lx)\n", Status);
2135 }
2136 }
2137 else
2138 {
2139 DPRINT("IopInitiatePnpIrp() failed (Status %x) or IoStatusBlock.Information=NULL\n", Status);
2140 }
2141
2142 DPRINT("Sending IRP_MN_QUERY_BUS_INFORMATION to device stack\n");
2143
2144 Status = IopInitiatePnpIrp(
2145 DeviceNode->PhysicalDeviceObject,
2146 &IoStatusBlock,
2147 IRP_MN_QUERY_BUS_INFORMATION,
2148 NULL);
2149 if (NT_SUCCESS(Status) && IoStatusBlock.Information)
2150 {
2151 PPNP_BUS_INFORMATION BusInformation =
2152 (PPNP_BUS_INFORMATION)IoStatusBlock.Information;
2153
2154 DeviceNode->ChildBusNumber = BusInformation->BusNumber;
2155 DeviceNode->ChildInterfaceType = BusInformation->LegacyBusType;
2156 DeviceNode->ChildBusTypeIndex = IopGetBusTypeGuidIndex(&BusInformation->BusTypeGuid);
2157 ExFreePool(BusInformation);
2158 }
2159 else
2160 {
2161 DPRINT("IopInitiatePnpIrp() failed (Status %x) or IoStatusBlock.Information=NULL\n", Status);
2162
2163 DeviceNode->ChildBusNumber = 0xFFFFFFF0;
2164 DeviceNode->ChildInterfaceType = InterfaceTypeUndefined;
2165 DeviceNode->ChildBusTypeIndex = -1;
2166 }
2167
2168 DPRINT("Sending IRP_MN_QUERY_RESOURCES to device stack\n");
2169
2170 Status = IopInitiatePnpIrp(
2171 DeviceNode->PhysicalDeviceObject,
2172 &IoStatusBlock,
2173 IRP_MN_QUERY_RESOURCES,
2174 NULL);
2175 if (NT_SUCCESS(Status) && IoStatusBlock.Information)
2176 {
2177 DeviceNode->BootResources =
2178 (PCM_RESOURCE_LIST)IoStatusBlock.Information;
2179 IopDeviceNodeSetFlag(DeviceNode, DNF_HAS_BOOT_CONFIG);
2180 }
2181 else
2182 {
2183 DPRINT("IopInitiatePnpIrp() failed (Status %x) or IoStatusBlock.Information=NULL\n", Status);
2184 DeviceNode->BootResources = NULL;
2185 }
2186
2187 DPRINT("Sending IRP_MN_QUERY_RESOURCE_REQUIREMENTS to device stack\n");
2188
2189 Status = IopInitiatePnpIrp(
2190 DeviceNode->PhysicalDeviceObject,
2191 &IoStatusBlock,
2192 IRP_MN_QUERY_RESOURCE_REQUIREMENTS,
2193 NULL);
2194 if (NT_SUCCESS(Status))
2195 {
2196 DeviceNode->ResourceRequirements =
2197 (PIO_RESOURCE_REQUIREMENTS_LIST)IoStatusBlock.Information;
2198 }
2199 else
2200 {
2201 DPRINT("IopInitiatePnpIrp() failed (Status %08lx)\n", Status);
2202 DeviceNode->ResourceRequirements = NULL;
2203 }
2204
2205 if (InstanceKey != NULL)
2206 {
2207 IopSetDeviceInstanceData(InstanceKey, DeviceNode);
2208 }
2209
2210 ZwClose(InstanceKey);
2211
2212 IopDeviceNodeSetFlag(DeviceNode, DNF_PROCESSED);
2213
2214 if (!IopDeviceNodeHasFlag(DeviceNode, DNF_LEGACY_DRIVER))
2215 {
2216 /* Report the device to the user-mode pnp manager */
2217 IopQueueTargetDeviceEvent(&GUID_DEVICE_ENUMERATED,
2218 &DeviceNode->InstancePath);
2219 }
2220
2221 return STATUS_SUCCESS;
2222 }
2223
2224 static
2225 VOID
2226 IopHandleDeviceRemoval(
2227 IN PDEVICE_NODE DeviceNode,
2228 IN PDEVICE_RELATIONS DeviceRelations)
2229 {
2230 PDEVICE_NODE Child = DeviceNode->Child, NextChild;
2231 ULONG i;
2232 BOOLEAN Found;
2233
2234 if (DeviceNode == IopRootDeviceNode)
2235 return;
2236
2237 while (Child != NULL)
2238 {
2239 NextChild = Child->Sibling;
2240 Found = FALSE;
2241
2242 for (i = 0; DeviceRelations && i < DeviceRelations->Count; i++)
2243 {
2244 if (IopGetDeviceNode(DeviceRelations->Objects[i]) == Child)
2245 {
2246 Found = TRUE;
2247 break;
2248 }
2249 }
2250
2251 if (!Found && !(Child->Flags & DNF_WILL_BE_REMOVED))
2252 {
2253 /* Send removal IRPs to all of its children */
2254 IopPrepareDeviceForRemoval(Child->PhysicalDeviceObject, TRUE);
2255
2256 /* Send the surprise removal IRP */
2257 IopSendSurpriseRemoval(Child->PhysicalDeviceObject);
2258
2259 /* Tell the user-mode PnP manager that a device was removed */
2260 IopQueueTargetDeviceEvent(&GUID_DEVICE_SURPRISE_REMOVAL,
2261 &Child->InstancePath);
2262
2263 /* Send the remove device IRP */
2264 IopSendRemoveDevice(Child->PhysicalDeviceObject);
2265 }
2266
2267 Child = NextChild;
2268 }
2269 }
2270
2271 NTSTATUS
2272 IopEnumerateDevice(
2273 IN PDEVICE_OBJECT DeviceObject)
2274 {
2275 PDEVICE_NODE DeviceNode = IopGetDeviceNode(DeviceObject);
2276 DEVICETREE_TRAVERSE_CONTEXT Context;
2277 PDEVICE_RELATIONS DeviceRelations;
2278 PDEVICE_OBJECT ChildDeviceObject;
2279 IO_STATUS_BLOCK IoStatusBlock;
2280 PDEVICE_NODE ChildDeviceNode;
2281 IO_STACK_LOCATION Stack;
2282 NTSTATUS Status;
2283 ULONG i;
2284
2285 DPRINT("DeviceObject 0x%p\n", DeviceObject);
2286
2287 if (DeviceNode->Flags & DNF_NEED_ENUMERATION_ONLY)
2288 {
2289 DeviceNode->Flags &= ~DNF_NEED_ENUMERATION_ONLY;
2290
2291 DPRINT("Sending GUID_DEVICE_ARRIVAL\n");
2292 IopQueueTargetDeviceEvent(&GUID_DEVICE_ARRIVAL,
2293 &DeviceNode->InstancePath);
2294 }
2295
2296 DPRINT("Sending IRP_MN_QUERY_DEVICE_RELATIONS to device stack\n");
2297
2298 Stack.Parameters.QueryDeviceRelations.Type = BusRelations;
2299
2300 Status = IopInitiatePnpIrp(
2301 DeviceObject,
2302 &IoStatusBlock,
2303 IRP_MN_QUERY_DEVICE_RELATIONS,
2304 &Stack);
2305 if (!NT_SUCCESS(Status) || Status == STATUS_PENDING)
2306 {
2307 DPRINT("IopInitiatePnpIrp() failed with status 0x%08lx\n", Status);
2308 return Status;
2309 }
2310
2311 DeviceRelations = (PDEVICE_RELATIONS)IoStatusBlock.Information;
2312
2313 /*
2314 * Send removal IRPs for devices that have disappeared
2315 * NOTE: This code handles the case where no relations are specified
2316 */
2317 IopHandleDeviceRemoval(DeviceNode, DeviceRelations);
2318
2319 /* Now we bail if nothing was returned */
2320 if (!DeviceRelations)
2321 {
2322 /* We're all done */
2323 DPRINT("No PDOs\n");
2324 return STATUS_SUCCESS;
2325 }
2326
2327 DPRINT("Got %u PDOs\n", DeviceRelations->Count);
2328
2329 /*
2330 * Create device nodes for all discovered devices
2331 */
2332 for (i = 0; i < DeviceRelations->Count; i++)
2333 {
2334 ChildDeviceObject = DeviceRelations->Objects[i];
2335 ASSERT((ChildDeviceObject->Flags & DO_DEVICE_INITIALIZING) == 0);
2336
2337 ChildDeviceNode = IopGetDeviceNode(ChildDeviceObject);
2338 if (!ChildDeviceNode)
2339 {
2340 /* One doesn't exist, create it */
2341 Status = IopCreateDeviceNode(
2342 DeviceNode,
2343 ChildDeviceObject,
2344 NULL,
2345 &ChildDeviceNode);
2346 if (NT_SUCCESS(Status))
2347 {
2348 /* Mark the node as enumerated */
2349 ChildDeviceNode->Flags |= DNF_ENUMERATED;
2350
2351 /* Mark the DO as bus enumerated */
2352 ChildDeviceObject->Flags |= DO_BUS_ENUMERATED_DEVICE;
2353 }
2354 else
2355 {
2356 /* Ignore this DO */
2357 DPRINT1("IopCreateDeviceNode() failed with status 0x%08x. Skipping PDO %u\n", Status, i);
2358 ObDereferenceObject(ChildDeviceObject);
2359 }
2360 }
2361 else
2362 {
2363 /* Mark it as enumerated */
2364 ChildDeviceNode->Flags |= DNF_ENUMERATED;
2365 ObDereferenceObject(ChildDeviceObject);
2366 }
2367 }
2368 ExFreePool(DeviceRelations);
2369
2370 /*
2371 * Retrieve information about all discovered children from the bus driver
2372 */
2373 IopInitDeviceTreeTraverseContext(
2374 &Context,
2375 DeviceNode,
2376 IopActionInterrogateDeviceStack,
2377 DeviceNode);
2378
2379 Status = IopTraverseDeviceTree(&Context);
2380 if (!NT_SUCCESS(Status))
2381 {
2382 DPRINT("IopTraverseDeviceTree() failed with status 0x%08lx\n", Status);
2383 return Status;
2384 }
2385
2386 /*
2387 * Retrieve configuration from the registry for discovered children
2388 */
2389 IopInitDeviceTreeTraverseContext(
2390 &Context,
2391 DeviceNode,
2392 IopActionConfigureChildServices,
2393 DeviceNode);
2394
2395 Status = IopTraverseDeviceTree(&Context);
2396 if (!NT_SUCCESS(Status))
2397 {
2398 DPRINT("IopTraverseDeviceTree() failed with status 0x%08lx\n", Status);
2399 return Status;
2400 }
2401
2402 /*
2403 * Initialize services for discovered children.
2404 */
2405 Status = IopInitializePnpServices(DeviceNode);
2406 if (!NT_SUCCESS(Status))
2407 {
2408 DPRINT("IopInitializePnpServices() failed with status 0x%08lx\n", Status);
2409 return Status;
2410 }
2411
2412 DPRINT("IopEnumerateDevice() finished\n");
2413 return STATUS_SUCCESS;
2414 }
2415
2416
2417 /*
2418 * IopActionConfigureChildServices
2419 *
2420 * Retrieve configuration for all (direct) child nodes of a parent node.
2421 *
2422 * Parameters
2423 * DeviceNode
2424 * Pointer to device node.
2425 * Context
2426 * Pointer to parent node to retrieve child node configuration for.
2427 *
2428 * Remarks
2429 * Any errors that occur are logged instead so that all child services have a chance of beeing
2430 * configured.
2431 */
2432
2433 NTSTATUS
2434 IopActionConfigureChildServices(PDEVICE_NODE DeviceNode,
2435 PVOID Context)
2436 {
2437 RTL_QUERY_REGISTRY_TABLE QueryTable[3];
2438 PDEVICE_NODE ParentDeviceNode;
2439 PUNICODE_STRING Service;
2440 UNICODE_STRING ClassGUID;
2441 NTSTATUS Status;
2442 DEVICE_CAPABILITIES DeviceCaps;
2443
2444 DPRINT("IopActionConfigureChildServices(%p, %p)\n", DeviceNode, Context);
2445
2446 ParentDeviceNode = (PDEVICE_NODE)Context;
2447
2448 /*
2449 * We are called for the parent too, but we don't need to do special
2450 * handling for this node
2451 */
2452 if (DeviceNode == ParentDeviceNode)
2453 {
2454 DPRINT("Success\n");
2455 return STATUS_SUCCESS;
2456 }
2457
2458 /*
2459 * Make sure this device node is a direct child of the parent device node
2460 * that is given as an argument
2461 */
2462
2463 if (DeviceNode->Parent != ParentDeviceNode)
2464 {
2465 DPRINT("Skipping 2+ level child\n");
2466 return STATUS_SUCCESS;
2467 }
2468
2469 if (!(DeviceNode->Flags & DNF_PROCESSED))
2470 {
2471 DPRINT1("Child not ready to be configured\n");
2472 return STATUS_SUCCESS;
2473 }
2474
2475 if (!(DeviceNode->Flags & (DNF_DISABLED | DNF_STARTED | DNF_ADDED)))
2476 {
2477 WCHAR RegKeyBuffer[MAX_PATH];
2478 UNICODE_STRING RegKey;
2479
2480 /* Install the service for this if it's in the CDDB */
2481 IopInstallCriticalDevice(DeviceNode);
2482
2483 RegKey.Length = 0;
2484 RegKey.MaximumLength = sizeof(RegKeyBuffer);
2485 RegKey.Buffer = RegKeyBuffer;
2486
2487 /*
2488 * Retrieve configuration from Enum key
2489 */
2490
2491 Service = &DeviceNode->ServiceName;
2492
2493 RtlZeroMemory(QueryTable, sizeof(QueryTable));
2494 RtlInitUnicodeString(Service, NULL);
2495 RtlInitUnicodeString(&ClassGUID, NULL);
2496
2497 QueryTable[0].Name = L"Service";
2498 QueryTable[0].Flags = RTL_QUERY_REGISTRY_DIRECT;
2499 QueryTable[0].EntryContext = Service;
2500
2501 QueryTable[1].Name = L"ClassGUID";
2502 QueryTable[1].Flags = RTL_QUERY_REGISTRY_DIRECT;
2503 QueryTable[1].EntryContext = &ClassGUID;
2504 QueryTable[1].DefaultType = REG_SZ;
2505 QueryTable[1].DefaultData = L"";
2506 QueryTable[1].DefaultLength = 0;
2507
2508 RtlAppendUnicodeToString(&RegKey, L"\\Registry\\Machine\\System\\CurrentControlSet\\Enum\\");
2509 RtlAppendUnicodeStringToString(&RegKey, &DeviceNode->InstancePath);
2510
2511 Status = RtlQueryRegistryValues(RTL_REGISTRY_ABSOLUTE,
2512 RegKey.Buffer, QueryTable, NULL, NULL);
2513
2514 if (!NT_SUCCESS(Status))
2515 {
2516 /* FIXME: Log the error */
2517 DPRINT("Could not retrieve configuration for device %wZ (Status 0x%08x)\n",
2518 &DeviceNode->InstancePath, Status);
2519 IopDeviceNodeSetFlag(DeviceNode, DNF_DISABLED);
2520 return STATUS_SUCCESS;
2521 }
2522
2523 if (Service->Buffer == NULL)
2524 {
2525 if (NT_SUCCESS(IopQueryDeviceCapabilities(DeviceNode, &DeviceCaps)) &&
2526 DeviceCaps.RawDeviceOK)
2527 {
2528 DPRINT("%wZ is using parent bus driver (%wZ)\n", &DeviceNode->InstancePath, &ParentDeviceNode->ServiceName);
2529
2530 DeviceNode->ServiceName.Length = 0;
2531 DeviceNode->ServiceName.MaximumLength = 0;
2532 DeviceNode->ServiceName.Buffer = NULL;
2533 }
2534 else if (ClassGUID.Length != 0)
2535 {
2536 /* Device has a ClassGUID value, but no Service value.
2537 * Suppose it is using the NULL driver, so state the
2538 * device is started */
2539 DPRINT("%wZ is using NULL driver\n", &DeviceNode->InstancePath);
2540 IopDeviceNodeSetFlag(DeviceNode, DNF_STARTED);
2541 }
2542 else
2543 {
2544 DeviceNode->Problem = CM_PROB_FAILED_INSTALL;
2545 IopDeviceNodeSetFlag(DeviceNode, DNF_DISABLED);
2546 }
2547 return STATUS_SUCCESS;
2548 }
2549
2550 DPRINT("Got Service %S\n", Service->Buffer);
2551 }
2552
2553 return STATUS_SUCCESS;
2554 }
2555
2556 /*
2557 * IopActionInitChildServices
2558 *
2559 * Initialize the service for all (direct) child nodes of a parent node
2560 *
2561 * Parameters
2562 * DeviceNode
2563 * Pointer to device node.
2564 * Context
2565 * Pointer to parent node to initialize child node services for.
2566 *
2567 * Remarks
2568 * If the driver image for a service is not loaded and initialized
2569 * it is done here too. Any errors that occur are logged instead so
2570 * that all child services have a chance of being initialized.
2571 */
2572
2573 NTSTATUS
2574 IopActionInitChildServices(PDEVICE_NODE DeviceNode,
2575 PVOID Context)
2576 {
2577 PDEVICE_NODE ParentDeviceNode;
2578 NTSTATUS Status;
2579 BOOLEAN BootDrivers = !PnpSystemInit;
2580
2581 DPRINT("IopActionInitChildServices(%p, %p)\n", DeviceNode, Context);
2582
2583 ParentDeviceNode = Context;
2584
2585 /*
2586 * We are called for the parent too, but we don't need to do special
2587 * handling for this node
2588 */
2589 if (DeviceNode == ParentDeviceNode)
2590 {
2591 DPRINT("Success\n");
2592 return STATUS_SUCCESS;
2593 }
2594
2595 /*
2596 * We don't want to check for a direct child because
2597 * this function is called during boot to reinitialize
2598 * devices with drivers that couldn't load yet due to
2599 * stage 0 limitations (ie can't load from disk yet).
2600 */
2601
2602 if (!(DeviceNode->Flags & DNF_PROCESSED))
2603 {
2604 DPRINT1("Child not ready to be added\n");
2605 return STATUS_SUCCESS;
2606 }
2607
2608 if (IopDeviceNodeHasFlag(DeviceNode, DNF_STARTED) ||
2609 IopDeviceNodeHasFlag(DeviceNode, DNF_ADDED) ||
2610 IopDeviceNodeHasFlag(DeviceNode, DNF_DISABLED))
2611 return STATUS_SUCCESS;
2612
2613 if (DeviceNode->ServiceName.Buffer == NULL)
2614 {
2615 /* We don't need to worry about loading the driver because we're
2616 * being driven in raw mode so our parent must be loaded to get here */
2617 Status = IopInitializeDevice(DeviceNode, NULL);
2618 if (NT_SUCCESS(Status))
2619 {
2620 Status = IopStartDevice(DeviceNode);
2621 if (!NT_SUCCESS(Status))
2622 {
2623 DPRINT1("IopStartDevice(%wZ) failed with status 0x%08x\n",
2624 &DeviceNode->InstancePath, Status);
2625 }
2626 }
2627 }
2628 else
2629 {
2630 PLDR_DATA_TABLE_ENTRY ModuleObject;
2631 PDRIVER_OBJECT DriverObject;
2632
2633 KeEnterCriticalRegion();
2634 ExAcquireResourceExclusiveLite(&IopDriverLoadResource, TRUE);
2635 /* Get existing DriverObject pointer (in case the driver has
2636 already been loaded and initialized) */
2637 Status = IopGetDriverObject(
2638 &DriverObject,
2639 &DeviceNode->ServiceName,
2640 FALSE);
2641
2642 if (!NT_SUCCESS(Status))
2643 {
2644 /* Driver is not initialized, try to load it */
2645 Status = IopLoadServiceModule(&DeviceNode->ServiceName, &ModuleObject);
2646
2647 if (NT_SUCCESS(Status) || Status == STATUS_IMAGE_ALREADY_LOADED)
2648 {
2649 /* Initialize the driver */
2650 Status = IopInitializeDriverModule(DeviceNode, ModuleObject,
2651 &DeviceNode->ServiceName, FALSE, &DriverObject);
2652 if (!NT_SUCCESS(Status)) DeviceNode->Problem = CM_PROB_FAILED_DRIVER_ENTRY;
2653 }
2654 else if (Status == STATUS_DRIVER_UNABLE_TO_LOAD)
2655 {
2656 DPRINT1("Service '%wZ' is disabled\n", &DeviceNode->ServiceName);
2657 DeviceNode->Problem = CM_PROB_DISABLED_SERVICE;
2658 }
2659 else
2660 {
2661 DPRINT("IopLoadServiceModule(%wZ) failed with status 0x%08x\n",
2662 &DeviceNode->ServiceName, Status);
2663 if (!BootDrivers) DeviceNode->Problem = CM_PROB_DRIVER_FAILED_LOAD;
2664 }
2665 }
2666 ExReleaseResourceLite(&IopDriverLoadResource);
2667 KeLeaveCriticalRegion();
2668
2669 /* Driver is loaded and initialized at this point */
2670 if (NT_SUCCESS(Status))
2671 {
2672 /* Initialize the device, including all filters */
2673 Status = PipCallDriverAddDevice(DeviceNode, FALSE, DriverObject);
2674
2675 /* Remove the extra reference */
2676 ObDereferenceObject(DriverObject);
2677 }
2678 else
2679 {
2680 /*
2681 * Don't disable when trying to load only boot drivers
2682 */
2683 if (!BootDrivers)
2684 {
2685 IopDeviceNodeSetFlag(DeviceNode, DNF_DISABLED);
2686 }
2687 }
2688 }
2689
2690 return STATUS_SUCCESS;
2691 }
2692
2693 /*
2694 * IopInitializePnpServices
2695 *
2696 * Initialize services for discovered children
2697 *
2698 * Parameters
2699 * DeviceNode
2700 * Top device node to start initializing services.
2701 *
2702 * Return Value
2703 * Status
2704 */
2705 NTSTATUS
2706 IopInitializePnpServices(IN PDEVICE_NODE DeviceNode)
2707 {
2708 DEVICETREE_TRAVERSE_CONTEXT Context;
2709
2710 DPRINT("IopInitializePnpServices(%p)\n", DeviceNode);
2711
2712 IopInitDeviceTreeTraverseContext(
2713 &Context,
2714 DeviceNode,
2715 IopActionInitChildServices,
2716 DeviceNode);
2717
2718 return IopTraverseDeviceTree(&Context);
2719 }
2720
2721 static NTSTATUS INIT_FUNCTION
2722 IopEnumerateDetectedDevices(
2723 IN HANDLE hBaseKey,
2724 IN PUNICODE_STRING RelativePath OPTIONAL,
2725 IN HANDLE hRootKey,
2726 IN BOOLEAN EnumerateSubKeys,
2727 IN PCM_FULL_RESOURCE_DESCRIPTOR ParentBootResources,
2728 IN ULONG ParentBootResourcesLength)
2729 {
2730 UNICODE_STRING IdentifierU = RTL_CONSTANT_STRING(L"Identifier");
2731 UNICODE_STRING HardwareIDU = RTL_CONSTANT_STRING(L"HardwareID");
2732 UNICODE_STRING ConfigurationDataU = RTL_CONSTANT_STRING(L"Configuration Data");
2733 UNICODE_STRING BootConfigU = RTL_CONSTANT_STRING(L"BootConfig");
2734 UNICODE_STRING LogConfU = RTL_CONSTANT_STRING(L"LogConf");
2735 OBJECT_ATTRIBUTES ObjectAttributes;
2736 HANDLE hDevicesKey = NULL;
2737 HANDLE hDeviceKey = NULL;
2738 HANDLE hLevel1Key, hLevel2Key = NULL, hLogConf;
2739 UNICODE_STRING Level2NameU;
2740 WCHAR Level2Name[5];
2741 ULONG IndexDevice = 0;
2742 ULONG IndexSubKey;
2743 PKEY_BASIC_INFORMATION pDeviceInformation = NULL;
2744 ULONG DeviceInfoLength = sizeof(KEY_BASIC_INFORMATION) + 50 * sizeof(WCHAR);
2745 PKEY_VALUE_PARTIAL_INFORMATION pValueInformation = NULL;
2746 ULONG ValueInfoLength = sizeof(KEY_VALUE_PARTIAL_INFORMATION) + 50 * sizeof(WCHAR);
2747 UNICODE_STRING DeviceName, ValueName;
2748 ULONG RequiredSize;
2749 PCM_FULL_RESOURCE_DESCRIPTOR BootResources = NULL;
2750 ULONG BootResourcesLength;
2751 NTSTATUS Status;
2752
2753 const UNICODE_STRING IdentifierSerial = RTL_CONSTANT_STRING(L"SerialController");
2754 UNICODE_STRING HardwareIdSerial = RTL_CONSTANT_STRING(L"*PNP0501\0");
2755 static ULONG DeviceIndexSerial = 0;
2756 const UNICODE_STRING IdentifierKeyboard = RTL_CONSTANT_STRING(L"KeyboardController");
2757 UNICODE_STRING HardwareIdKeyboard = RTL_CONSTANT_STRING(L"*PNP0303\0");
2758 static ULONG DeviceIndexKeyboard = 0;
2759 const UNICODE_STRING IdentifierMouse = RTL_CONSTANT_STRING(L"PointerController");
2760 UNICODE_STRING HardwareIdMouse = RTL_CONSTANT_STRING(L"*PNP0F13\0");
2761 static ULONG DeviceIndexMouse = 0;
2762 const UNICODE_STRING IdentifierParallel = RTL_CONSTANT_STRING(L"ParallelController");
2763 UNICODE_STRING HardwareIdParallel = RTL_CONSTANT_STRING(L"*PNP0400\0");
2764 static ULONG DeviceIndexParallel = 0;
2765 const UNICODE_STRING IdentifierFloppy = RTL_CONSTANT_STRING(L"FloppyDiskPeripheral");
2766 UNICODE_STRING HardwareIdFloppy = RTL_CONSTANT_STRING(L"*PNP0700\0");
2767 static ULONG DeviceIndexFloppy = 0;
2768 UNICODE_STRING HardwareIdKey;
2769 PUNICODE_STRING pHardwareId;
2770 ULONG DeviceIndex = 0;
2771 PUCHAR CmResourceList;
2772 ULONG ListCount;
2773
2774 if (RelativePath)
2775 {
2776 Status = IopOpenRegistryKeyEx(&hDevicesKey, hBaseKey, RelativePath, KEY_ENUMERATE_SUB_KEYS);
2777 if (!NT_SUCCESS(Status))
2778 {
2779 DPRINT("ZwOpenKey() failed with status 0x%08lx\n", Status);
2780 goto cleanup;
2781 }
2782 }
2783 else
2784 hDevicesKey = hBaseKey;
2785
2786 pDeviceInformation = ExAllocatePool(PagedPool, DeviceInfoLength);
2787 if (!pDeviceInformation)
2788 {
2789 DPRINT("ExAllocatePool() failed\n");
2790 Status = STATUS_NO_MEMORY;
2791 goto cleanup;
2792 }
2793
2794 pValueInformation = ExAllocatePool(PagedPool, ValueInfoLength);
2795 if (!pValueInformation)
2796 {
2797 DPRINT("ExAllocatePool() failed\n");
2798 Status = STATUS_NO_MEMORY;
2799 goto cleanup;
2800 }
2801
2802 while (TRUE)
2803 {
2804 Status = ZwEnumerateKey(hDevicesKey, IndexDevice, KeyBasicInformation, pDeviceInformation, DeviceInfoLength, &RequiredSize);
2805 if (Status == STATUS_NO_MORE_ENTRIES)
2806 break;
2807 else if (Status == STATUS_BUFFER_OVERFLOW || Status == STATUS_BUFFER_TOO_SMALL)
2808 {
2809 ExFreePool(pDeviceInformation);
2810 DeviceInfoLength = RequiredSize;
2811 pDeviceInformation = ExAllocatePool(PagedPool, DeviceInfoLength);
2812 if (!pDeviceInformation)
2813 {
2814 DPRINT("ExAllocatePool() failed\n");
2815 Status = STATUS_NO_MEMORY;
2816 goto cleanup;
2817 }
2818 Status = ZwEnumerateKey(hDevicesKey, IndexDevice, KeyBasicInformation, pDeviceInformation, DeviceInfoLength, &RequiredSize);
2819 }
2820 if (!NT_SUCCESS(Status))
2821 {
2822 DPRINT("ZwEnumerateKey() failed with status 0x%08lx\n", Status);
2823 goto cleanup;
2824 }
2825 IndexDevice++;
2826
2827 /* Open device key */
2828 DeviceName.Length = DeviceName.MaximumLength = (USHORT)pDeviceInformation->NameLength;
2829 DeviceName.Buffer = pDeviceInformation->Name;
2830
2831 Status = IopOpenRegistryKeyEx(&hDeviceKey, hDevicesKey, &DeviceName,
2832 KEY_QUERY_VALUE + (EnumerateSubKeys ? KEY_ENUMERATE_SUB_KEYS : 0));
2833 if (!NT_SUCCESS(Status))
2834 {
2835 DPRINT("ZwOpenKey() failed with status 0x%08lx\n", Status);
2836 goto cleanup;
2837 }
2838
2839 /* Read boot resources, and add then to parent ones */
2840 Status = ZwQueryValueKey(hDeviceKey, &ConfigurationDataU, KeyValuePartialInformation, pValueInformation, ValueInfoLength, &RequiredSize);
2841 if (Status == STATUS_BUFFER_OVERFLOW || Status == STATUS_BUFFER_TOO_SMALL)
2842 {
2843 ExFreePool(pValueInformation);
2844 ValueInfoLength = RequiredSize;
2845 pValueInformation = ExAllocatePool(PagedPool, ValueInfoLength);
2846 if (!pValueInformation)
2847 {
2848 DPRINT("ExAllocatePool() failed\n");
2849 ZwDeleteKey(hLevel2Key);
2850 Status = STATUS_NO_MEMORY;
2851 goto cleanup;
2852 }
2853 Status = ZwQueryValueKey(hDeviceKey, &ConfigurationDataU, KeyValuePartialInformation, pValueInformation, ValueInfoLength, &RequiredSize);
2854 }
2855 if (Status == STATUS_OBJECT_NAME_NOT_FOUND)
2856 {
2857 BootResources = ParentBootResources;
2858 BootResourcesLength = ParentBootResourcesLength;
2859 }
2860 else if (!NT_SUCCESS(Status))
2861 {
2862 DPRINT("ZwQueryValueKey() failed with status 0x%08lx\n", Status);
2863 goto nextdevice;
2864 }
2865 else if (pValueInformation->Type != REG_FULL_RESOURCE_DESCRIPTOR)
2866 {
2867 DPRINT("Wrong registry type: got 0x%lx, expected 0x%lx\n", pValueInformation->Type, REG_FULL_RESOURCE_DESCRIPTOR);
2868 goto nextdevice;
2869 }
2870 else
2871 {
2872 static const ULONG Header = FIELD_OFFSET(CM_FULL_RESOURCE_DESCRIPTOR, PartialResourceList.PartialDescriptors);
2873
2874 /* Concatenate current resources and parent ones */
2875 if (ParentBootResourcesLength == 0)
2876 BootResourcesLength = pValueInformation->DataLength;
2877 else
2878 BootResourcesLength = ParentBootResourcesLength
2879 + pValueInformation->DataLength
2880 - Header;
2881 BootResources = ExAllocatePool(PagedPool, BootResourcesLength);
2882 if (!BootResources)
2883 {
2884 DPRINT("ExAllocatePool() failed\n");
2885 goto nextdevice;
2886 }
2887 if (ParentBootResourcesLength < sizeof(CM_FULL_RESOURCE_DESCRIPTOR))
2888 {
2889 RtlCopyMemory(BootResources, pValueInformation->Data, pValueInformation->DataLength);
2890 }
2891 else if (ParentBootResources->PartialResourceList.PartialDescriptors[ParentBootResources->PartialResourceList.Count - 1].Type == CmResourceTypeDeviceSpecific)
2892 {
2893 RtlCopyMemory(BootResources, pValueInformation->Data, pValueInformation->DataLength);
2894 RtlCopyMemory(
2895 (PVOID)((ULONG_PTR)BootResources + pValueInformation->DataLength),
2896 (PVOID)((ULONG_PTR)ParentBootResources + Header),
2897 ParentBootResourcesLength - Header);
2898 BootResources->PartialResourceList.Count += ParentBootResources->PartialResourceList.Count;
2899 }
2900 else
2901 {
2902 RtlCopyMemory(BootResources, pValueInformation->Data, Header);
2903 RtlCopyMemory(
2904 (PVOID)((ULONG_PTR)BootResources + Header),
2905 (PVOID)((ULONG_PTR)ParentBootResources + Header),
2906 ParentBootResourcesLength - Header);
2907 RtlCopyMemory(
2908 (PVOID)((ULONG_PTR)BootResources + ParentBootResourcesLength),
2909 pValueInformation->Data + Header,
2910 pValueInformation->DataLength - Header);
2911 BootResources->PartialResourceList.Count += ParentBootResources->PartialResourceList.Count;
2912 }
2913 }
2914
2915 if (EnumerateSubKeys)
2916 {
2917 IndexSubKey = 0;
2918 while (TRUE)
2919 {
2920 Status = ZwEnumerateKey(hDeviceKey, IndexSubKey, KeyBasicInformation, pDeviceInformation, DeviceInfoLength, &RequiredSize);
2921 if (Status == STATUS_NO_MORE_ENTRIES)
2922 break;
2923 else if (Status == STATUS_BUFFER_OVERFLOW || Status == STATUS_BUFFER_TOO_SMALL)
2924 {
2925 ExFreePool(pDeviceInformation);
2926 DeviceInfoLength = RequiredSize;
2927 pDeviceInformation = ExAllocatePool(PagedPool, DeviceInfoLength);
2928 if (!pDeviceInformation)
2929 {
2930 DPRINT("ExAllocatePool() failed\n");
2931 Status = STATUS_NO_MEMORY;
2932 goto cleanup;
2933 }
2934 Status = ZwEnumerateKey(hDeviceKey, IndexSubKey, KeyBasicInformation, pDeviceInformation, DeviceInfoLength, &RequiredSize);
2935 }
2936 if (!NT_SUCCESS(Status))
2937 {
2938 DPRINT("ZwEnumerateKey() failed with status 0x%08lx\n", Status);
2939 goto cleanup;
2940 }
2941 IndexSubKey++;
2942 DeviceName.Length = DeviceName.MaximumLength = (USHORT)pDeviceInformation->NameLength;
2943 DeviceName.Buffer = pDeviceInformation->Name;
2944
2945 Status = IopEnumerateDetectedDevices(
2946 hDeviceKey,
2947 &DeviceName,
2948 hRootKey,
2949 TRUE,
2950 BootResources,
2951 BootResourcesLength);
2952 if (!NT_SUCCESS(Status))
2953 goto cleanup;
2954 }
2955 }
2956
2957 /* Read identifier */
2958 Status = ZwQueryValueKey(hDeviceKey, &IdentifierU, KeyValuePartialInformation, pValueInformation, ValueInfoLength, &RequiredSize);
2959 if (Status == STATUS_BUFFER_OVERFLOW || Status == STATUS_BUFFER_TOO_SMALL)
2960 {
2961 ExFreePool(pValueInformation);
2962 ValueInfoLength = RequiredSize;
2963 pValueInformation = ExAllocatePool(PagedPool, ValueInfoLength);
2964 if (!pValueInformation)
2965 {
2966 DPRINT("ExAllocatePool() failed\n");
2967 Status = STATUS_NO_MEMORY;
2968 goto cleanup;
2969 }
2970 Status = ZwQueryValueKey(hDeviceKey, &IdentifierU, KeyValuePartialInformation, pValueInformation, ValueInfoLength, &RequiredSize);
2971 }
2972 if (!NT_SUCCESS(Status))
2973 {
2974 if (Status != STATUS_OBJECT_NAME_NOT_FOUND)
2975 {
2976 DPRINT("ZwQueryValueKey() failed with status 0x%08lx\n", Status);
2977 goto nextdevice;
2978 }
2979 ValueName.Length = ValueName.MaximumLength = 0;
2980 }
2981 else if (pValueInformation->Type != REG_SZ)
2982 {
2983 DPRINT("Wrong registry type: got 0x%lx, expected 0x%lx\n", pValueInformation->Type, REG_SZ);
2984 goto nextdevice;
2985 }
2986 else
2987 {
2988 /* Assign hardware id to this device */
2989 ValueName.Length = ValueName.MaximumLength = (USHORT)pValueInformation->DataLength;
2990 ValueName.Buffer = (PWCHAR)pValueInformation->Data;
2991 if (ValueName.Length >= sizeof(WCHAR) && ValueName.Buffer[ValueName.Length / sizeof(WCHAR) - 1] == UNICODE_NULL)
2992 ValueName.Length -= sizeof(WCHAR);
2993 }
2994
2995 if (RelativePath && RtlCompareUnicodeString(RelativePath, &IdentifierSerial, FALSE) == 0)
2996 {
2997 pHardwareId = &HardwareIdSerial;
2998 DeviceIndex = DeviceIndexSerial++;
2999 }
3000 else if (RelativePath && RtlCompareUnicodeString(RelativePath, &IdentifierKeyboard, FALSE) == 0)
3001 {
3002 pHardwareId = &HardwareIdKeyboard;
3003 DeviceIndex = DeviceIndexKeyboard++;
3004 }
3005 else if (RelativePath && RtlCompareUnicodeString(RelativePath, &IdentifierMouse, FALSE) == 0)
3006 {
3007 pHardwareId = &HardwareIdMouse;
3008 DeviceIndex = DeviceIndexMouse++;
3009 }
3010 else if (RelativePath && RtlCompareUnicodeString(RelativePath, &IdentifierParallel, FALSE) == 0)
3011 {
3012 pHardwareId = &HardwareIdParallel;
3013 DeviceIndex = DeviceIndexParallel++;
3014 }
3015 else if (RelativePath && RtlCompareUnicodeString(RelativePath, &IdentifierFloppy, FALSE) == 0)
3016 {
3017 pHardwareId = &HardwareIdFloppy;
3018 DeviceIndex = DeviceIndexFloppy++;
3019 }
3020 else
3021 {
3022 /* Unknown key path */
3023 DPRINT("Unknown key path '%wZ'\n", RelativePath);
3024 goto nextdevice;
3025 }
3026
3027 /* Prepare hardware id key (hardware id value without final \0) */
3028 HardwareIdKey = *pHardwareId;
3029 HardwareIdKey.Length -= sizeof(UNICODE_NULL);
3030
3031 /* Add the detected device to Root key */
3032 InitializeObjectAttributes(&ObjectAttributes, &HardwareIdKey, OBJ_KERNEL_HANDLE, hRootKey, NULL);
3033 Status = ZwCreateKey(
3034 &hLevel1Key,
3035 KEY_CREATE_SUB_KEY,
3036 &ObjectAttributes,
3037 0,
3038 NULL,
3039 ExpInTextModeSetup ? REG_OPTION_VOLATILE : 0,
3040 NULL);
3041 if (!NT_SUCCESS(Status))
3042 {
3043 DPRINT("ZwCreateKey() failed with status 0x%08lx\n", Status);
3044 goto nextdevice;
3045 }
3046 swprintf(Level2Name, L"%04lu", DeviceIndex);
3047 RtlInitUnicodeString(&Level2NameU, Level2Name);
3048 InitializeObjectAttributes(&ObjectAttributes, &Level2NameU, OBJ_KERNEL_HANDLE, hLevel1Key, NULL);
3049 Status = ZwCreateKey(
3050 &hLevel2Key,
3051 KEY_SET_VALUE | KEY_CREATE_SUB_KEY,
3052 &ObjectAttributes,
3053 0,
3054 NULL,
3055 ExpInTextModeSetup ? REG_OPTION_VOLATILE : 0,
3056 NULL);
3057 ZwClose(hLevel1Key);
3058 if (!NT_SUCCESS(Status))
3059 {
3060 DPRINT("ZwCreateKey() failed with status 0x%08lx\n", Status);
3061 goto nextdevice;
3062 }
3063 DPRINT("Found %wZ #%lu (%wZ)\n", &ValueName, DeviceIndex, &HardwareIdKey);
3064 Status = ZwSetValueKey(hLevel2Key, &HardwareIDU, 0, REG_MULTI_SZ, pHardwareId->Buffer, pHardwareId->MaximumLength);
3065 if (!NT_SUCCESS(Status))
3066 {
3067 DPRINT("ZwSetValueKey() failed with status 0x%08lx\n", Status);
3068 ZwDeleteKey(hLevel2Key);
3069 goto nextdevice;
3070 }
3071 /* Create 'LogConf' subkey */
3072 InitializeObjectAttributes(&ObjectAttributes, &LogConfU, OBJ_KERNEL_HANDLE, hLevel2Key, NULL);
3073 Status = ZwCreateKey(
3074 &hLogConf,
3075 KEY_SET_VALUE,
3076 &ObjectAttributes,
3077 0,
3078 NULL,
3079 REG_OPTION_VOLATILE,
3080 NULL);
3081 if (!NT_SUCCESS(Status))
3082 {
3083 DPRINT("ZwCreateKey() failed with status 0x%08lx\n", Status);
3084 ZwDeleteKey(hLevel2Key);
3085 goto nextdevice;
3086 }
3087 if (BootResourcesLength >= sizeof(CM_FULL_RESOURCE_DESCRIPTOR))
3088 {
3089 CmResourceList = ExAllocatePool(PagedPool, BootResourcesLength + sizeof(ULONG));
3090 if (!CmResourceList)
3091 {
3092 ZwClose(hLogConf);
3093 ZwDeleteKey(hLevel2Key);
3094 goto nextdevice;
3095 }
3096
3097 /* Add the list count (1st member of CM_RESOURCE_LIST) */
3098 ListCount = 1;
3099 RtlCopyMemory(CmResourceList,
3100 &ListCount,
3101 sizeof(ULONG));
3102
3103 /* Now add the actual list (2nd member of CM_RESOURCE_LIST) */
3104 RtlCopyMemory(CmResourceList + sizeof(ULONG),
3105 BootResources,
3106 BootResourcesLength);
3107
3108 /* Save boot resources to 'LogConf\BootConfig' */
3109 Status = ZwSetValueKey(hLogConf, &BootConfigU, 0, REG_RESOURCE_LIST, CmResourceList, BootResourcesLength + sizeof(ULONG));
3110 if (!NT_SUCCESS(Status))
3111 {
3112 DPRINT("ZwSetValueKey() failed with status 0x%08lx\n", Status);
3113 ZwClose(hLogConf);
3114 ZwDeleteKey(hLevel2Key);
3115 goto nextdevice;
3116 }
3117 }
3118 ZwClose(hLogConf);
3119
3120 nextdevice:
3121 if (BootResources && BootResources != ParentBootResources)
3122 {
3123 ExFreePool(BootResources);
3124 BootResources = NULL;
3125 }
3126 if (hLevel2Key)
3127 {
3128 ZwClose(hLevel2Key);
3129 hLevel2Key = NULL;
3130 }
3131 if (hDeviceKey)
3132 {
3133 ZwClose(hDeviceKey);
3134 hDeviceKey = NULL;
3135 }
3136 }
3137
3138 Status = STATUS_SUCCESS;
3139
3140 cleanup:
3141 if (hDevicesKey && hDevicesKey != hBaseKey)
3142 ZwClose(hDevicesKey);
3143 if (hDeviceKey)
3144 ZwClose(hDeviceKey);
3145 if (pDeviceInformation)
3146 ExFreePool(pDeviceInformation);
3147 if (pValueInformation)
3148 ExFreePool(pValueInformation);
3149 return Status;
3150 }
3151
3152 static BOOLEAN INIT_FUNCTION
3153 IopIsFirmwareMapperDisabled(VOID)
3154 {
3155 UNICODE_STRING KeyPathU = RTL_CONSTANT_STRING(L"\\Registry\\Machine\\SYSTEM\\CURRENTCONTROLSET\\Control\\Pnp");
3156 UNICODE_STRING KeyNameU = RTL_CONSTANT_STRING(L"DisableFirmwareMapper");
3157 OBJECT_ATTRIBUTES ObjectAttributes;
3158 HANDLE hPnpKey;
3159 PKEY_VALUE_PARTIAL_INFORMATION KeyInformation;
3160 ULONG DesiredLength, Length;
3161 ULONG KeyValue = 0;
3162 NTSTATUS Status;
3163
3164 InitializeObjectAttributes(&ObjectAttributes, &KeyPathU, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, NULL, NULL);
3165 Status = ZwOpenKey(&hPnpKey, KEY_QUERY_VALUE, &ObjectAttributes);
3166 if (NT_SUCCESS(Status))
3167 {
3168 Status = ZwQueryValueKey(hPnpKey,
3169 &KeyNameU,
3170 KeyValuePartialInformation,
3171 NULL,
3172 0,
3173 &DesiredLength);
3174 if ((Status == STATUS_BUFFER_TOO_SMALL) ||
3175 (Status == STATUS_BUFFER_OVERFLOW))
3176 {
3177 Length = DesiredLength;
3178 KeyInformation = ExAllocatePool(PagedPool, Length);
3179 if (KeyInformation)
3180 {
3181 Status = ZwQueryValueKey(hPnpKey,
3182 &KeyNameU,
3183 KeyValuePartialInformation,
3184 KeyInformation,
3185 Length,
3186 &DesiredLength);
3187 if (NT_SUCCESS(Status) && KeyInformation->DataLength == sizeof(ULONG))
3188 {
3189 KeyValue = (ULONG)(*KeyInformation->Data);
3190 }
3191 else
3192 {
3193 DPRINT1("ZwQueryValueKey(%wZ%wZ) failed\n", &KeyPathU, &KeyNameU);
3194 }
3195
3196 ExFreePool(KeyInformation);
3197 }
3198 else
3199 {
3200 DPRINT1("Failed to allocate memory for registry query\n");
3201 }
3202 }
3203 else
3204 {
3205 DPRINT1("ZwQueryValueKey(%wZ%wZ) failed with status 0x%08lx\n", &KeyPathU, &KeyNameU, Status);
3206 }
3207
3208 ZwClose(hPnpKey);
3209 }
3210 else
3211 {
3212 DPRINT1("ZwOpenKey(%wZ) failed with status 0x%08lx\n", &KeyPathU, Status);
3213 }
3214
3215 DPRINT("Firmware mapper is %s\n", KeyValue != 0 ? "disabled" : "enabled");
3216
3217 return (KeyValue != 0) ? TRUE : FALSE;
3218 }
3219
3220 NTSTATUS
3221 NTAPI
3222 INIT_FUNCTION
3223 IopUpdateRootKey(VOID)
3224 {
3225 UNICODE_STRING EnumU = RTL_CONSTANT_STRING(L"\\Registry\\Machine\\SYSTEM\\CurrentControlSet\\Enum");
3226 UNICODE_STRING RootPathU = RTL_CONSTANT_STRING(L"Root");
3227 UNICODE_STRING MultiKeyPathU = RTL_CONSTANT_STRING(L"\\Registry\\Machine\\HARDWARE\\DESCRIPTION\\System\\MultifunctionAdapter");
3228 OBJECT_ATTRIBUTES ObjectAttributes;
3229 HANDLE hEnum, hRoot;
3230 NTSTATUS Status;
3231
3232 InitializeObjectAttributes(&ObjectAttributes, &EnumU, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, NULL, NULL);
3233 Status = ZwCreateKey(&hEnum, KEY_CREATE_SUB_KEY, &ObjectAttributes, 0, NULL, 0, NULL);
3234 if (!NT_SUCCESS(Status))
3235 {
3236 DPRINT1("ZwCreateKey() failed with status 0x%08lx\n", Status);
3237 return Status;
3238 }
3239
3240 InitializeObjectAttributes(&ObjectAttributes, &RootPathU, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, hEnum, NULL);
3241 Status = ZwCreateKey(&hRoot, KEY_CREATE_SUB_KEY, &ObjectAttributes, 0, NULL, 0, NULL);
3242 ZwClose(hEnum);
3243 if (!NT_SUCCESS(Status))
3244 {
3245 DPRINT1("ZwOpenKey() failed with status 0x%08lx\n", Status);
3246 return Status;
3247 }
3248
3249 if (!IopIsFirmwareMapperDisabled())
3250 {
3251 Status = IopOpenRegistryKeyEx(&hEnum, NULL, &MultiKeyPathU, KEY_ENUMERATE_SUB_KEYS);
3252 if (!NT_SUCCESS(Status))
3253 {
3254 /* Nothing to do, don't return with an error status */
3255 DPRINT("ZwOpenKey() failed with status 0x%08lx\n", Status);
3256 ZwClose(hRoot);
3257 return STATUS_SUCCESS;
3258 }
3259 Status = IopEnumerateDetectedDevices(
3260 hEnum,
3261 NULL,
3262 hRoot,
3263 TRUE,
3264 NULL,
3265 0);
3266 ZwClose(hEnum);
3267 }
3268 else
3269 {
3270 /* Enumeration is disabled */
3271 Status = STATUS_SUCCESS;
3272 }
3273
3274 ZwClose(hRoot);
3275
3276 return Status;
3277 }
3278
3279 NTSTATUS
3280 NTAPI
3281 IopOpenRegistryKeyEx(PHANDLE KeyHandle,
3282 HANDLE ParentKey,
3283 PUNICODE_STRING Name,
3284 ACCESS_MASK DesiredAccess)
3285 {
3286 OBJECT_ATTRIBUTES ObjectAttributes;
3287 NTSTATUS Status;
3288
3289 PAGED_CODE();
3290
3291 *KeyHandle = NULL;
3292
3293 InitializeObjectAttributes(&ObjectAttributes,
3294 Name,
3295 OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
3296 ParentKey,
3297 NULL);
3298
3299 Status = ZwOpenKey(KeyHandle, DesiredAccess, &ObjectAttributes);
3300
3301 return Status;
3302 }
3303
3304 NTSTATUS
3305 NTAPI
3306 IopCreateRegistryKeyEx(OUT PHANDLE Handle,
3307 IN HANDLE RootHandle OPTIONAL,
3308 IN PUNICODE_STRING KeyName,
3309 IN ACCESS_MASK DesiredAccess,
3310 IN ULONG CreateOptions,
3311 OUT PULONG Disposition OPTIONAL)
3312 {
3313 OBJECT_ATTRIBUTES ObjectAttributes;
3314 ULONG KeyDisposition, RootHandleIndex = 0, i = 1, NestedCloseLevel = 0;
3315 USHORT Length;
3316 HANDLE HandleArray[2];
3317 BOOLEAN Recursing = TRUE;
3318 PWCHAR pp, p, p1;
3319 UNICODE_STRING KeyString;
3320 NTSTATUS Status = STATUS_SUCCESS;
3321 PAGED_CODE();
3322
3323 /* P1 is start, pp is end */
3324 p1 = KeyName->Buffer;
3325 pp = (PVOID)((ULONG_PTR)p1 + KeyName->Length);
3326
3327 /* Create the target key */
3328 InitializeObjectAttributes(&ObjectAttributes,
3329 KeyName,
3330 OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
3331 RootHandle,
3332 NULL);
3333 Status = ZwCreateKey(&HandleArray[i],
3334 DesiredAccess,
3335 &ObjectAttributes,
3336 0,
3337 NULL,
3338 CreateOptions,
3339 &KeyDisposition);
3340
3341 /* Now we check if this failed */
3342 if ((Status == STATUS_OBJECT_NAME_NOT_FOUND) && (RootHandle))
3343 {
3344 /* Target key failed, so we'll need to create its parent. Setup array */
3345 HandleArray[0] = NULL;
3346 HandleArray[1] = RootHandle;
3347
3348 /* Keep recursing for each missing parent */
3349 while (Recursing)
3350 {
3351 /* And if we're deep enough, close the last handle */
3352 if (NestedCloseLevel > 1) ZwClose(HandleArray[RootHandleIndex]);
3353
3354 /* We're setup to ping-pong between the two handle array entries */
3355 RootHandleIndex = i;
3356 i = (i + 1) & 1;
3357
3358 /* Clear the one we're attempting to open now */
3359 HandleArray[i] = NULL;
3360
3361 /* Process the parent key name */
3362 for (p = p1; ((p < pp) && (*p != OBJ_NAME_PATH_SEPARATOR)); p++);
3363 Length = (USHORT)(p - p1) * sizeof(WCHAR);
3364
3365 /* Is there a parent name? */
3366 if (Length)
3367 {
3368 /* Build the unicode string for it */
3369 KeyString.Buffer = p1;
3370 KeyString.Length = KeyString.MaximumLength = Length;
3371
3372 /* Now try opening the parent */
3373 InitializeObjectAttributes(&ObjectAttributes,
3374 &KeyString,
3375 OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
3376 HandleArray[RootHandleIndex],
3377 NULL);
3378 Status = ZwCreateKey(&HandleArray[i],
3379 DesiredAccess,
3380 &ObjectAttributes,
3381 0,
3382 NULL,
3383 CreateOptions,
3384 &KeyDisposition);
3385 if (NT_SUCCESS(Status))
3386 {
3387 /* It worked, we have one more handle */
3388 NestedCloseLevel++;
3389 }
3390 else
3391 {
3392 /* Parent key creation failed, abandon loop */
3393 Recursing = FALSE;
3394 continue;
3395 }
3396 }
3397 else
3398 {
3399 /* We don't have a parent name, probably corrupted key name */
3400 Status = STATUS_INVALID_PARAMETER;
3401 Recursing = FALSE;
3402 continue;
3403 }
3404
3405 /* Now see if there's more parents to create */
3406 p1 = p + 1;
3407 if ((p == pp) || (p1 == pp))
3408 {
3409 /* We're done, hopefully successfully, so stop */
3410 Recursing = FALSE;
3411 }
3412 }
3413
3414 /* Outer loop check for handle nesting that requires closing the top handle */
3415 if (NestedCloseLevel > 1) ZwClose(HandleArray[RootHandleIndex]);
3416 }
3417
3418 /* Check if we broke out of the loop due to success */
3419 if (NT_SUCCESS(Status))
3420 {
3421 /* Return the target handle (we closed all the parent ones) and disposition */
3422 *Handle = HandleArray[i];
3423 if (Disposition) *Disposition = KeyDisposition;
3424 }
3425
3426 /* Return the success state */
3427 return Status;
3428 }
3429
3430 NTSTATUS
3431 NTAPI
3432 IopGetRegistryValue(IN HANDLE Handle,
3433 IN PWSTR ValueName,
3434 OUT PKEY_VALUE_FULL_INFORMATION *Information)
3435 {
3436 UNICODE_STRING ValueString;
3437 NTSTATUS Status;
3438 PKEY_VALUE_FULL_INFORMATION FullInformation;
3439 ULONG Size;
3440 PAGED_CODE();
3441
3442 RtlInitUnicodeString(&ValueString, ValueName);
3443
3444 Status = ZwQueryValueKey(Handle,
3445 &ValueString,
3446 KeyValueFullInformation,
3447 NULL,
3448 0,
3449 &Size);
3450 if ((Status != STATUS_BUFFER_OVERFLOW) &&
3451 (Status != STATUS_BUFFER_TOO_SMALL))
3452 {
3453 return Status;
3454 }
3455
3456 FullInformation = ExAllocatePool(NonPagedPool, Size);
3457 if (!FullInformation) return STATUS_INSUFFICIENT_RESOURCES;
3458
3459 Status = ZwQueryValueKey(Handle,
3460 &ValueString,
3461 KeyValueFullInformation,
3462 FullInformation,
3463 Size,
3464 &Size);
3465 if (!NT_SUCCESS(Status))
3466 {
3467 ExFreePool(FullInformation);
3468 return Status;
3469 }
3470
3471 *Information = FullInformation;
3472 return STATUS_SUCCESS;
3473 }
3474
3475 RTL_GENERIC_COMPARE_RESULTS
3476 NTAPI
3477 PiCompareInstancePath(IN PRTL_AVL_TABLE Table,
3478 IN PVOID FirstStruct,
3479 IN PVOID SecondStruct)
3480 {
3481 /* FIXME: TODO */
3482 ASSERT(FALSE);
3483 return 0;
3484 }
3485
3486 //
3487 // The allocation function is called by the generic table package whenever
3488 // it needs to allocate memory for the table.
3489 //
3490
3491 PVOID
3492 NTAPI
3493 PiAllocateGenericTableEntry(IN PRTL_AVL_TABLE Table,
3494 IN CLONG ByteSize)
3495 {
3496 /* FIXME: TODO */
3497 ASSERT(FALSE);
3498 return NULL;
3499 }
3500
3501 VOID
3502 NTAPI
3503 PiFreeGenericTableEntry(IN PRTL_AVL_TABLE Table,
3504 IN PVOID Buffer)
3505 {
3506 /* FIXME: TODO */
3507 ASSERT(FALSE);
3508 }
3509
3510 VOID
3511 NTAPI
3512 PpInitializeDeviceReferenceTable(VOID)
3513 {
3514 /* Setup the guarded mutex and AVL table */
3515 KeInitializeGuardedMutex(&PpDeviceReferenceTableLock);
3516 RtlInitializeGenericTableAvl(
3517 &PpDeviceReferenceTable,
3518 (PRTL_AVL_COMPARE_ROUTINE)PiCompareInstancePath,
3519 (PRTL_AVL_ALLOCATE_ROUTINE)PiAllocateGenericTableEntry,
3520 (PRTL_AVL_FREE_ROUTINE)PiFreeGenericTableEntry,
3521 NULL);
3522 }
3523
3524 BOOLEAN
3525 NTAPI
3526 PiInitPhase0(VOID)
3527 {
3528 /* Initialize the resource when accessing device registry data */
3529 ExInitializeResourceLite(&PpRegistryDeviceResource);
3530
3531 /* Setup the device reference AVL table */
3532 PpInitializeDeviceReferenceTable();
3533 return TRUE;
3534 }
3535
3536 BOOLEAN
3537 NTAPI
3538 PpInitSystem(VOID)
3539 {
3540 /* Check the initialization phase */
3541 switch (ExpInitializationPhase)
3542 {
3543 case 0:
3544
3545 /* Do Phase 0 */
3546 return PiInitPhase0();
3547
3548 case 1:
3549
3550 /* Do Phase 1 */
3551 return TRUE;
3552 //return PiInitPhase1();
3553
3554 default:
3555
3556 /* Don't know any other phase! Bugcheck! */
3557 KeBugCheck(UNEXPECTED_INITIALIZATION_CALL);
3558 return FALSE;
3559 }
3560 }
3561
3562 LONG IopNumberDeviceNodes;
3563
3564 PDEVICE_NODE
3565 NTAPI
3566 PipAllocateDeviceNode(IN PDEVICE_OBJECT PhysicalDeviceObject)
3567 {
3568 PDEVICE_NODE DeviceNode;
3569 PAGED_CODE();
3570
3571 /* Allocate it */
3572 DeviceNode = ExAllocatePoolWithTag(NonPagedPool, sizeof(DEVICE_NODE), TAG_IO_DEVNODE);
3573 if (!DeviceNode) return DeviceNode;
3574
3575 /* Statistics */
3576 InterlockedIncrement(&IopNumberDeviceNodes);
3577
3578 /* Set it up */
3579 RtlZeroMemory(DeviceNode, sizeof(DEVICE_NODE));
3580 DeviceNode->InterfaceType = InterfaceTypeUndefined;
3581 DeviceNode->BusNumber = -1;
3582 DeviceNode->ChildInterfaceType = InterfaceTypeUndefined;
3583 DeviceNode->ChildBusNumber = -1;
3584 DeviceNode->ChildBusTypeIndex = -1;
3585 // KeInitializeEvent(&DeviceNode->EnumerationMutex, SynchronizationEvent, TRUE);
3586 InitializeListHead(&DeviceNode->DeviceArbiterList);
3587 InitializeListHead(&DeviceNode->DeviceTranslatorList);
3588 InitializeListHead(&DeviceNode->TargetDeviceNotify);
3589 InitializeListHead(&DeviceNode->DockInfo.ListEntry);
3590 InitializeListHead(&DeviceNode->PendedSetInterfaceState);
3591
3592 /* Check if there is a PDO */
3593 if (PhysicalDeviceObject)
3594 {
3595 /* Link it and remove the init flag */
3596 DeviceNode->PhysicalDeviceObject = PhysicalDeviceObject;
3597 ((PEXTENDED_DEVOBJ_EXTENSION)PhysicalDeviceObject->DeviceObjectExtension)->DeviceNode = DeviceNode;
3598 PhysicalDeviceObject->Flags &= ~DO_DEVICE_INITIALIZING;
3599 }
3600
3601 /* Return the node */
3602 return DeviceNode;
3603 }
3604
3605 /* PUBLIC FUNCTIONS **********************************************************/
3606
3607 NTSTATUS
3608 NTAPI
3609 PnpBusTypeGuidGet(IN USHORT Index,
3610 IN LPGUID BusTypeGuid)
3611 {
3612 NTSTATUS Status = STATUS_SUCCESS;
3613
3614 /* Acquire the lock */
3615 ExAcquireFastMutex(&PnpBusTypeGuidList->Lock);
3616
3617 /* Validate size */
3618 if (Index < PnpBusTypeGuidList->GuidCount)
3619 {
3620 /* Copy the data */
3621 RtlCopyMemory(BusTypeGuid, &PnpBusTypeGuidList->Guids[Index], sizeof(GUID));
3622 }
3623 else
3624 {
3625 /* Failure path */
3626 Status = STATUS_OBJECT_NAME_NOT_FOUND;
3627 }
3628
3629 /* Release lock and return status */
3630 ExReleaseFastMutex(&PnpBusTypeGuidList->Lock);
3631 return Status;
3632 }
3633
3634 NTSTATUS
3635 NTAPI
3636 PnpDeviceObjectToDeviceInstance(IN PDEVICE_OBJECT DeviceObject,
3637 IN PHANDLE DeviceInstanceHandle,
3638 IN ACCESS_MASK DesiredAccess)
3639 {
3640 NTSTATUS Status;
3641 HANDLE KeyHandle;
3642 PDEVICE_NODE DeviceNode;
3643 UNICODE_STRING KeyName = RTL_CONSTANT_STRING(L"\\REGISTRY\\MACHINE\\SYSTEM\\CURRENTCONTROLSET\\ENUM");
3644 PAGED_CODE();
3645
3646 /* Open the enum key */
3647 Status = IopOpenRegistryKeyEx(&KeyHandle,
3648 NULL,
3649 &KeyName,
3650 KEY_READ);
3651 if (!NT_SUCCESS(Status)) return Status;
3652
3653 /* Make sure we have an instance path */
3654 DeviceNode = IopGetDeviceNode(DeviceObject);
3655 if ((DeviceNode) && (DeviceNode->InstancePath.Length))
3656 {
3657 /* Get the instance key */
3658 Status = IopOpenRegistryKeyEx(DeviceInstanceHandle,
3659 KeyHandle,
3660 &DeviceNode->InstancePath,
3661 DesiredAccess);
3662 }
3663 else
3664 {
3665 /* Fail */
3666 Status = STATUS_INVALID_DEVICE_REQUEST;
3667 }
3668
3669 /* Close the handle and return status */
3670 ZwClose(KeyHandle);
3671 return Status;
3672 }
3673
3674 ULONG
3675 NTAPI
3676 PnpDetermineResourceListSize(IN PCM_RESOURCE_LIST ResourceList)
3677 {
3678 ULONG FinalSize, PartialSize, EntrySize, i, j;
3679 PCM_FULL_RESOURCE_DESCRIPTOR FullDescriptor;
3680 PCM_PARTIAL_RESOURCE_DESCRIPTOR PartialDescriptor;
3681
3682 /* If we don't have one, that's easy */
3683 if (!ResourceList) return 0;
3684
3685 /* Start with the minimum size possible */
3686 FinalSize = FIELD_OFFSET(CM_RESOURCE_LIST, List);
3687
3688 /* Loop each full descriptor */
3689 FullDescriptor = ResourceList->List;
3690 for (i = 0; i < ResourceList->Count; i++)
3691 {
3692 /* Start with the minimum size possible */
3693 PartialSize = FIELD_OFFSET(CM_FULL_RESOURCE_DESCRIPTOR, PartialResourceList) +
3694 FIELD_OFFSET(CM_PARTIAL_RESOURCE_LIST, PartialDescriptors);
3695
3696 /* Loop each partial descriptor */
3697 PartialDescriptor = FullDescriptor->PartialResourceList.PartialDescriptors;
3698 for (j = 0; j < FullDescriptor->PartialResourceList.Count; j++)
3699 {
3700 /* Start with the minimum size possible */
3701 EntrySize = sizeof(CM_PARTIAL_RESOURCE_DESCRIPTOR);
3702
3703 /* Check if there is extra data */
3704 if (PartialDescriptor->Type == CmResourceTypeDeviceSpecific)
3705 {
3706 /* Add that data */
3707 EntrySize += PartialDescriptor->u.DeviceSpecificData.DataSize;
3708 }
3709
3710 /* The size of partial descriptors is bigger */
3711 PartialSize += EntrySize;
3712
3713 /* Go to the next partial descriptor */
3714 PartialDescriptor = (PVOID)((ULONG_PTR)PartialDescriptor + EntrySize);
3715 }
3716
3717 /* The size of full descriptors is bigger */
3718 FinalSize += PartialSize;
3719
3720 /* Go to the next full descriptor */
3721 FullDescriptor = (PVOID)((ULONG_PTR)FullDescriptor + PartialSize);
3722 }
3723
3724 /* Return the final size */
3725 return FinalSize;
3726 }
3727
3728 NTSTATUS
3729 NTAPI
3730 PiGetDeviceRegistryProperty(IN PDEVICE_OBJECT DeviceObject,
3731 IN ULONG ValueType,
3732 IN PWSTR ValueName,
3733 IN PWSTR KeyName,
3734 OUT PVOID Buffer,
3735 IN PULONG BufferLength)
3736 {
3737 NTSTATUS Status;
3738 HANDLE KeyHandle, SubHandle;
3739 UNICODE_STRING KeyString;
3740 PKEY_VALUE_FULL_INFORMATION KeyValueInfo = NULL;
3741 ULONG Length;
3742 PAGED_CODE();
3743
3744 /* Find the instance key */
3745 Status = PnpDeviceObjectToDeviceInstance(DeviceObject, &KeyHandle, KEY_READ);
3746 if (NT_SUCCESS(Status))
3747 {
3748 /* Check for name given by caller */
3749 if (KeyName)
3750 {
3751 /* Open this key */
3752 RtlInitUnicodeString(&KeyString, KeyName);
3753 Status = IopOpenRegistryKeyEx(&SubHandle,
3754 KeyHandle,
3755 &KeyString,
3756 KEY_READ);
3757 if (NT_SUCCESS(Status))
3758 {
3759 /* And use this handle instead */
3760 ZwClose(KeyHandle);
3761 KeyHandle = SubHandle;
3762 }
3763 }
3764
3765 /* Check if sub-key handle succeeded (or no-op if no key name given) */
3766 if (NT_SUCCESS(Status))
3767 {
3768 /* Now get the size of the property */
3769 Status = IopGetRegistryValue(KeyHandle,
3770 ValueName,
3771 &KeyValueInfo);
3772 }
3773
3774 /* Close the key */
3775 ZwClose(KeyHandle);
3776 }
3777
3778 /* Fail if any of the registry operations failed */
3779 if (!NT_SUCCESS(Status)) return Status;
3780
3781 /* Check how much data we have to copy */
3782 Length = KeyValueInfo->DataLength;
3783 if (*BufferLength >= Length)
3784 {
3785 /* Check for a match in the value type */
3786 if (KeyValueInfo->Type == ValueType)
3787 {
3788 /* Copy the data */
3789 RtlCopyMemory(Buffer,
3790 (PVOID)((ULONG_PTR)KeyValueInfo +
3791 KeyValueInfo->DataOffset),
3792 Length);
3793 }
3794 else
3795 {
3796 /* Invalid registry property type, fail */
3797 Status = STATUS_INVALID_PARAMETER_2;
3798 }
3799 }
3800 else
3801 {
3802 /* Buffer is too small to hold data */
3803 Status = STATUS_BUFFER_TOO_SMALL;
3804 }
3805
3806 /* Return the required buffer length, free the buffer, and return status */
3807 *BufferLength = Length;
3808 ExFreePool(KeyValueInfo);
3809 return Status;
3810 }
3811
3812 #define PIP_RETURN_DATA(x, y) {ReturnLength = x; Data = y; Status = STATUS_SUCCESS; break;}
3813 #define PIP_REGISTRY_DATA(x, y) {ValueName = x; ValueType = y; break;}
3814 #define PIP_UNIMPLEMENTED() {UNIMPLEMENTED_DBGBREAK(); break;}
3815
3816 /*
3817 * @implemented
3818 */
3819 NTSTATUS
3820 NTAPI
3821 IoGetDeviceProperty(IN PDEVICE_OBJECT DeviceObject,
3822 IN DEVICE_REGISTRY_PROPERTY DeviceProperty,
3823 IN ULONG BufferLength,
3824 OUT PVOID PropertyBuffer,
3825 OUT PULONG ResultLength)
3826 {
3827 PDEVICE_NODE DeviceNode = IopGetDeviceNode(DeviceObject);
3828 DEVICE_CAPABILITIES DeviceCaps;
3829 ULONG ReturnLength = 0, Length = 0, ValueType;
3830 PWCHAR ValueName = NULL, EnumeratorNameEnd, DeviceInstanceName;
3831 PVOID Data = NULL;
3832 NTSTATUS Status = STATUS_BUFFER_TOO_SMALL;
3833 GUID BusTypeGuid;
3834 POBJECT_NAME_INFORMATION ObjectNameInfo = NULL;
3835 BOOLEAN NullTerminate = FALSE;
3836
3837 DPRINT("IoGetDeviceProperty(0x%p %d)\n", DeviceObject, DeviceProperty);
3838
3839 /* Assume failure */
3840 *ResultLength = 0;
3841
3842 /* Only PDOs can call this */
3843 if (!DeviceNode) return STATUS_INVALID_DEVICE_REQUEST;
3844
3845 /* Handle all properties */
3846 switch (DeviceProperty)
3847 {
3848 case DevicePropertyBusTypeGuid:
3849
3850 /* Get the GUID from the internal cache */
3851 Status = PnpBusTypeGuidGet(DeviceNode->ChildBusTypeIndex, &BusTypeGuid);
3852 if (!NT_SUCCESS(Status)) return Status;
3853
3854 /* This is the format of the returned data */
3855 PIP_RETURN_DATA(sizeof(GUID), &BusTypeGuid);
3856
3857 case DevicePropertyLegacyBusType:
3858
3859 /* Validate correct interface type */
3860 if (DeviceNode->ChildInterfaceType == InterfaceTypeUndefined)
3861 return STATUS_OBJECT_NAME_NOT_FOUND;
3862
3863 /* This is the format of the returned data */
3864 PIP_RETURN_DATA(sizeof(INTERFACE_TYPE), &DeviceNode->ChildInterfaceType);
3865
3866 case DevicePropertyBusNumber:
3867
3868 /* Validate correct bus number */
3869 if ((DeviceNode->ChildBusNumber & 0x80000000) == 0x80000000)
3870 return STATUS_OBJECT_NAME_NOT_FOUND;
3871
3872 /* This is the format of the returned data */
3873 PIP_RETURN_DATA(sizeof(ULONG), &DeviceNode->ChildBusNumber);
3874
3875 case DevicePropertyEnumeratorName:
3876
3877 /* Get the instance path */
3878 DeviceInstanceName = DeviceNode->InstancePath.Buffer;
3879
3880 /* Sanity checks */
3881 ASSERT((BufferLength & 1) == 0);
3882 ASSERT(DeviceInstanceName != NULL);
3883
3884 /* Get the name from the path */
3885 EnumeratorNameEnd = wcschr(DeviceInstanceName, OBJ_NAME_PATH_SEPARATOR);
3886 ASSERT(EnumeratorNameEnd);
3887
3888 /* This string needs to be NULL-terminated */
3889 NullTerminate = TRUE;
3890
3891 /* This is the format of the returned data */
3892 PIP_RETURN_DATA((ULONG)(EnumeratorNameEnd - DeviceInstanceName) * sizeof(WCHAR),
3893 DeviceInstanceName);
3894
3895 case DevicePropertyAddress:
3896
3897 /* Query the device caps */
3898 Status = IopQueryDeviceCapabilities(DeviceNode, &DeviceCaps);
3899 if (!NT_SUCCESS(Status) || (DeviceCaps.Address == MAXULONG))
3900 return STATUS_OBJECT_NAME_NOT_FOUND;
3901
3902 /* This is the format of the returned data */
3903 PIP_RETURN_DATA(sizeof(ULONG), &DeviceCaps.Address);
3904
3905 case DevicePropertyBootConfigurationTranslated:
3906
3907 /* Validate we have resources */
3908 if (!DeviceNode->BootResources)
3909 // if (!DeviceNode->BootResourcesTranslated) // FIXFIX: Need this field
3910 {
3911 /* No resources will still fake success, but with 0 bytes */
3912 *ResultLength = 0;
3913 return STATUS_SUCCESS;
3914 }
3915
3916 /* This is the format of the returned data */
3917 PIP_RETURN_DATA(PnpDetermineResourceListSize(DeviceNode->BootResources), // FIXFIX: Should use BootResourcesTranslated
3918 DeviceNode->BootResources); // FIXFIX: Should use BootResourcesTranslated
3919
3920 case DevicePropertyPhysicalDeviceObjectName:
3921
3922 /* Sanity check for Unicode-sized string */
3923 ASSERT((BufferLength & 1) == 0);
3924
3925 /* Allocate name buffer */
3926 Length = BufferLength + sizeof(OBJECT_NAME_INFORMATION);
3927 ObjectNameInfo = ExAllocatePool(PagedPool, Length);
3928 if (!ObjectNameInfo) return STATUS_INSUFFICIENT_RESOURCES;
3929
3930 /* Query the PDO name */
3931 Status = ObQueryNameString(DeviceObject,
3932 ObjectNameInfo,
3933 Length,
3934 ResultLength);
3935 if (Status == STATUS_INFO_LENGTH_MISMATCH)
3936 {
3937 /* It's up to the caller to try again */
3938 Status = STATUS_BUFFER_TOO_SMALL;
3939 }
3940
3941 /* This string needs to be NULL-terminated */
3942 NullTerminate = TRUE;
3943
3944 /* Return if successful */
3945 if (NT_SUCCESS(Status)) PIP_RETURN_DATA(ObjectNameInfo->Name.Length,
3946 ObjectNameInfo->Name.Buffer);
3947
3948 /* Let the caller know how big the name is */
3949 *ResultLength -= sizeof(OBJECT_NAME_INFORMATION);
3950 break;
3951
3952 /* Handle the registry-based properties */
3953 case DevicePropertyUINumber:
3954 PIP_REGISTRY_DATA(REGSTR_VAL_UI_NUMBER, REG_DWORD);
3955 case DevicePropertyLocationInformation:
3956 PIP_REGISTRY_DATA(REGSTR_VAL_LOCATION_INFORMATION, REG_SZ);
3957 case DevicePropertyDeviceDescription:
3958 PIP_REGISTRY_DATA(REGSTR_VAL_DEVDESC, REG_SZ);
3959 case DevicePropertyHardwareID:
3960 PIP_REGISTRY_DATA(REGSTR_VAL_HARDWAREID, REG_MULTI_SZ);
3961 case DevicePropertyCompatibleIDs:
3962 PIP_REGISTRY_DATA(REGSTR_VAL_COMPATIBLEIDS, REG_MULTI_SZ);
3963 case DevicePropertyBootConfiguration:
3964 PIP_REGISTRY_DATA(REGSTR_VAL_BOOTCONFIG, REG_RESOURCE_LIST);
3965 case DevicePropertyClassName:
3966 PIP_REGISTRY_DATA(REGSTR_VAL_CLASS, REG_SZ);
3967 case DevicePropertyClassGuid:
3968 PIP_REGISTRY_DATA(REGSTR_VAL_CLASSGUID, REG_SZ);
3969 case DevicePropertyDriverKeyName:
3970 PIP_REGISTRY_DATA(REGSTR_VAL_DRIVER, REG_SZ);
3971 case DevicePropertyManufacturer:
3972 PIP_REGISTRY_DATA(REGSTR_VAL_MFG, REG_SZ);
3973 case DevicePropertyFriendlyName:
3974 PIP_REGISTRY_DATA(REGSTR_VAL_FRIENDLYNAME, REG_SZ);
3975 case DevicePropertyContainerID:
3976 //PIP_REGISTRY_DATA(REGSTR_VAL_CONTAINERID, REG_SZ); // Win7
3977 PIP_UNIMPLEMENTED();
3978 case DevicePropertyRemovalPolicy:
3979 PIP_UNIMPLEMENTED();
3980 case DevicePropertyInstallState:
3981 PIP_UNIMPLEMENTED();
3982 case DevicePropertyResourceRequirements:
3983 PIP_UNIMPLEMENTED();
3984 case DevicePropertyAllocatedResources:
3985 PIP_UNIMPLEMENTED();
3986 default:
3987 return STATUS_INVALID_PARAMETER_2;
3988 }
3989
3990 /* Having a registry value name implies registry data */
3991 if (ValueName)
3992 {
3993 /* We know up-front how much data to expect */
3994 *ResultLength = BufferLength;
3995
3996 /* Go get the data, use the LogConf subkey if necessary */
3997 Status = PiGetDeviceRegistryProperty(DeviceObject,
3998 ValueType,
3999 ValueName,
4000 (DeviceProperty ==
4001 DevicePropertyBootConfiguration) ?
4002 L"LogConf": NULL,
4003 PropertyBuffer,
4004 ResultLength);
4005 }
4006 else if (NT_SUCCESS(Status))
4007 {
4008 /* We know up-front how much data to expect, check the caller's buffer */
4009 *ResultLength = ReturnLength + (NullTerminate ? sizeof(UNICODE_NULL) : 0);
4010 if (*ResultLength <= BufferLength)
4011 {
4012 /* Buffer is all good, copy the data */
4013 RtlCopyMemory(PropertyBuffer, Data, ReturnLength);
4014
4015 /* Check if we need to NULL-terminate the string */
4016 if (NullTerminate)
4017 {
4018 /* Terminate the string */
4019 ((PWCHAR)PropertyBuffer)[ReturnLength / sizeof(WCHAR)] = UNICODE_NULL;
4020 }
4021
4022 /* This is the success path */
4023 Status = STATUS_SUCCESS;
4024 }
4025 else
4026 {
4027 /* Failure path */
4028 Status = STATUS_BUFFER_TOO_SMALL;
4029 }
4030 }
4031
4032 /* Free any allocation we may have made, and return the status code */
4033 if (ObjectNameInfo) ExFreePool(ObjectNameInfo);
4034 return Status;
4035 }
4036
4037 /*
4038 * @implemented
4039 */
4040 VOID
4041 NTAPI
4042 IoInvalidateDeviceState(IN PDEVICE_OBJECT PhysicalDeviceObject)
4043 {
4044 PDEVICE_NODE DeviceNode = IopGetDeviceNode(PhysicalDeviceObject);
4045 IO_STACK_LOCATION Stack;
4046 ULONG PnPFlags;
4047 NTSTATUS Status;
4048 IO_STATUS_BLOCK IoStatusBlock;
4049
4050 RtlZeroMemory(&Stack, sizeof(IO_STACK_LOCATION));
4051 Stack.MajorFunction = IRP_MJ_PNP;
4052 Stack.MinorFunction = IRP_MN_QUERY_PNP_DEVICE_STATE;
4053
4054 Status = IopSynchronousCall(PhysicalDeviceObject, &Stack, (PVOID*)&PnPFlags);
4055 if (!NT_SUCCESS(Status))
4056 {
4057 DPRINT1("IRP_MN_QUERY_PNP_DEVICE_STATE failed with status 0x%x\n", Status);
4058 return;
4059 }
4060
4061 if (PnPFlags & PNP_DEVICE_NOT_DISABLEABLE)
4062 DeviceNode->UserFlags |= DNUF_NOT_DISABLEABLE;
4063 else
4064 DeviceNode->UserFlags &= ~DNUF_NOT_DISABLEABLE;
4065
4066 if (PnPFlags & PNP_DEVICE_DONT_DISPLAY_IN_UI)
4067 DeviceNode->UserFlags |= DNUF_DONT_SHOW_IN_UI;
4068 else
4069 DeviceNode->UserFlags &= ~DNUF_DONT_SHOW_IN_UI;
4070
4071 if ((PnPFlags & PNP_DEVICE_REMOVED) ||
4072 ((PnPFlags & PNP_DEVICE_FAILED) && !(PnPFlags & PNP_DEVICE_RESOURCE_REQUIREMENTS_CHANGED)))
4073 {
4074 /* Flag it if it's failed */
4075 if (PnPFlags & PNP_DEVICE_FAILED) DeviceNode->Problem = CM_PROB_FAILED_POST_START;
4076
4077 /* Send removal IRPs to all of its children */
4078 IopPrepareDeviceForRemoval(PhysicalDeviceObject, TRUE);
4079
4080 /* Send surprise removal */
4081 IopSendSurpriseRemoval(PhysicalDeviceObject);
4082
4083 /* Tell the user-mode PnP manager that a device was removed */
4084 IopQueueTargetDeviceEvent(&GUID_DEVICE_SURPRISE_REMOVAL,
4085 &DeviceNode->InstancePath);
4086
4087 IopSendRemoveDevice(PhysicalDeviceObject);
4088 }
4089 else if ((PnPFlags & PNP_DEVICE_FAILED) && (PnPFlags & PNP_DEVICE_RESOURCE_REQUIREMENTS_CHANGED))
4090 {
4091 /* Stop for resource rebalance */
4092 Status = IopStopDevice(DeviceNode);
4093 if (!NT_SUCCESS(Status))
4094 {
4095 DPRINT1("Failed to stop device for rebalancing\n");
4096
4097 /* Stop failed so don't rebalance */
4098 PnPFlags &= ~PNP_DEVICE_RESOURCE_REQUIREMENTS_CHANGED;
4099 }
4100 }
4101
4102 /* Resource rebalance */
4103 if (PnPFlags & PNP_DEVICE_RESOURCE_REQUIREMENTS_CHANGED)
4104 {
4105 DPRINT("Sending IRP_MN_QUERY_RESOURCES to device stack\n");
4106
4107 Status = IopInitiatePnpIrp(PhysicalDeviceObject,
4108 &IoStatusBlock,
4109 IRP_MN_QUERY_RESOURCES,
4110 NULL);
4111 if (NT_SUCCESS(Status) && IoStatusBlock.Information)
4112 {
4113 DeviceNode->BootResources =
4114 (PCM_RESOURCE_LIST)IoStatusBlock.Information;
4115 IopDeviceNodeSetFlag(DeviceNode, DNF_HAS_BOOT_CONFIG);
4116 }
4117 else
4118 {
4119 DPRINT("IopInitiatePnpIrp() failed (Status %x) or IoStatusBlock.Information=NULL\n", Status);
4120 DeviceNode->BootResources = NULL;
4121 }
4122
4123 DPRINT("Sending IRP_MN_QUERY_RESOURCE_REQUIREMENTS to device stack\n");
4124
4125 Status = IopInitiatePnpIrp(PhysicalDeviceObject,
4126 &IoStatusBlock,
4127 IRP_MN_QUERY_RESOURCE_REQUIREMENTS,
4128 NULL);
4129 if (NT_SUCCESS(Status))
4130 {
4131 DeviceNode->ResourceRequirements =
4132 (PIO_RESOURCE_REQUIREMENTS_LIST)IoStatusBlock.Information;
4133 }
4134 else
4135 {
4136 DPRINT("IopInitiatePnpIrp() failed (Status %08lx)\n", Status);
4137 DeviceNode->ResourceRequirements = NULL;
4138 }
4139
4140 /* IRP_MN_FILTER_RESOURCE_REQUIREMENTS is called indirectly by IopStartDevice */
4141 if (IopStartDevice(DeviceNode) != STATUS_SUCCESS)
4142 {
4143 DPRINT1("Restart after resource rebalance failed\n");
4144
4145 DeviceNode->Flags &= ~(DNF_STARTED | DNF_START_REQUEST_PENDING);
4146 DeviceNode->Flags |= DNF_START_FAILED;
4147
4148 IopRemoveDevice(DeviceNode);
4149 }
4150 }
4151 }
4152
4153 /**
4154 * @name IoOpenDeviceRegistryKey
4155 *
4156 * Open a registry key unique for a specified driver or device instance.
4157 *
4158 * @param DeviceObject Device to get the registry key for.
4159 * @param DevInstKeyType Type of the key to return.
4160 * @param DesiredAccess Access mask (eg. KEY_READ | KEY_WRITE).
4161 * @param DevInstRegKey Handle to the opened registry key on
4162 * successful return.
4163 *
4164 * @return Status.
4165 *
4166 * @implemented
4167 */
4168 NTSTATUS
4169 NTAPI
4170 IoOpenDeviceRegistryKey(IN PDEVICE_OBJECT DeviceObject,
4171 IN ULONG DevInstKeyType,
4172 IN ACCESS_MASK DesiredAccess,
4173 OUT PHANDLE DevInstRegKey)
4174 {
4175 static WCHAR RootKeyName[] =
4176 L"\\Registry\\Machine\\System\\CurrentControlSet\\";
4177 static WCHAR ProfileKeyName[] =
4178 L"Hardware Profiles\\Current\\System\\CurrentControlSet\\";
4179 static WCHAR ClassKeyName[] = L"Control\\Class\\";
4180 static WCHAR EnumKeyName[] = L"Enum\\";
4181 static WCHAR DeviceParametersKeyName[] = L"Device Parameters";
4182 ULONG KeyNameLength;
4183 LPWSTR KeyNameBuffer;
4184 UNICODE_STRING KeyName;
4185 ULONG DriverKeyLength;
4186 OBJECT_ATTRIBUTES ObjectAttributes;
4187 PDEVICE_NODE DeviceNode = NULL;
4188 NTSTATUS Status;
4189
4190 DPRINT("IoOpenDeviceRegistryKey() called\n");
4191
4192 if ((DevInstKeyType & (PLUGPLAY_REGKEY_DEVICE | PLUGPLAY_REGKEY_DRIVER)) == 0)
4193 {
4194 DPRINT1("IoOpenDeviceRegistryKey(): got wrong params, exiting... \n");
4195 return STATUS_INVALID_PARAMETER;
4196 }
4197
4198 if (!IopIsValidPhysicalDeviceObject(DeviceObject))
4199 return STATUS_INVALID_DEVICE_REQUEST;
4200 DeviceNode = IopGetDeviceNode(DeviceObject);
4201
4202 /*
4203 * Calculate the length of the base key name. This is the full
4204 * name for driver key or the name excluding "Device Parameters"
4205 * subkey for device key.
4206 */
4207
4208 KeyNameLength = sizeof(RootKeyName);
4209 if (DevInstKeyType & PLUGPLAY_REGKEY_CURRENT_HWPROFILE)
4210 KeyNameLength += sizeof(ProfileKeyName) - sizeof(UNICODE_NULL);
4211 if (DevInstKeyType & PLUGPLAY_REGKEY_DRIVER)
4212 {
4213 KeyNameLength += sizeof(ClassKeyName) - sizeof(UNICODE_NULL);
4214 Status = IoGetDeviceProperty(DeviceObject, DevicePropertyDriverKeyName,
4215 0, NULL, &DriverKeyLength);
4216 if (Status != STATUS_BUFFER_TOO_SMALL)
4217 return Status;
4218 KeyNameLength += DriverKeyLength;
4219 }
4220 else
4221 {
4222 KeyNameLength += sizeof(EnumKeyName) - sizeof(UNICODE_NULL) +
4223 DeviceNode->InstancePath.Length;
4224 }
4225
4226 /*
4227 * Now allocate the buffer for the key name...
4228 */
4229
4230 KeyNameBuffer = ExAllocatePool(PagedPool, KeyNameLength);
4231 if (KeyNameBuffer == NULL)
4232 return STATUS_INSUFFICIENT_RESOURCES;
4233
4234 KeyName.Length = 0;
4235 KeyName.MaximumLength = (USHORT)KeyNameLength;
4236 KeyName.Buffer = KeyNameBuffer;
4237
4238 /*
4239 * ...and build the key name.
4240 */
4241
4242 KeyName.Length += sizeof(RootKeyName) - sizeof(UNICODE_NULL);
4243 RtlCopyMemory(KeyNameBuffer, RootKeyName, KeyName.Length);
4244
4245 if (DevInstKeyType & PLUGPLAY_REGKEY_CURRENT_HWPROFILE)
4246 RtlAppendUnicodeToString(&KeyName, ProfileKeyName);
4247
4248 if (DevInstKeyType & PLUGPLAY_REGKEY_DRIVER)
4249 {
4250 RtlAppendUnicodeToString(&KeyName, ClassKeyName);
4251 Status = IoGetDeviceProperty(DeviceObject, DevicePropertyDriverKeyName,
4252 DriverKeyLength, KeyNameBuffer +
4253 (KeyName.Length / sizeof(WCHAR)),
4254 &DriverKeyLength);
4255 if (!NT_SUCCESS(Status))
4256 {
4257 DPRINT1("Call to IoGetDeviceProperty() failed with Status 0x%08lx\n", Status);
4258 ExFreePool(KeyNameBuffer);
4259 return Status;
4260 }
4261 KeyName.Length += (USHORT)DriverKeyLength - sizeof(UNICODE_NULL);
4262 }
4263 else
4264 {
4265 RtlAppendUnicodeToString(&KeyName, EnumKeyName);
4266 Status = RtlAppendUnicodeStringToString(&KeyName, &DeviceNode->InstancePath);
4267 if (DeviceNode->InstancePath.Length == 0)
4268 {
4269 ExFreePool(KeyNameBuffer);
4270 return Status;
4271 }
4272 }
4273
4274 /*
4275 * Open the base key.
4276 */
4277 Status = IopOpenRegistryKeyEx(DevInstRegKey, NULL, &KeyName, DesiredAccess);
4278 if (!NT_SUCCESS(Status))
4279 {
4280 DPRINT1("IoOpenDeviceRegistryKey(%wZ): Base key doesn't exist, exiting... (Status 0x%08lx)\n", &KeyName, Status);
4281 ExFreePool(KeyNameBuffer);
4282 return Status;
4283 }
4284 ExFreePool(KeyNameBuffer);
4285
4286 /*
4287 * For driver key we're done now.
4288 */
4289
4290 if (DevInstKeyType & PLUGPLAY_REGKEY_DRIVER)
4291 return Status;
4292
4293 /*
4294 * Let's go further. For device key we must open "Device Parameters"
4295 * subkey and create it if it doesn't exist yet.
4296 */
4297
4298 RtlInitUnicodeString(&KeyName, DeviceParametersKeyName);
4299 InitializeObjectAttributes(&ObjectAttributes, &KeyName,
4300 OBJ_CASE_INSENSITIVE, *DevInstRegKey, NULL);
4301 Status = ZwCreateKey(DevInstRegKey, DesiredAccess, &ObjectAttributes,
4302 0, NULL, ExpInTextModeSetup ? REG_OPTION_VOLATILE : 0, NULL);
4303 ZwClose(ObjectAttributes.RootDirectory);
4304
4305 return Status;
4306 }
4307
4308 static
4309 NTSTATUS
4310 IopQueryRemoveChildDevices(PDEVICE_NODE ParentDeviceNode, BOOLEAN Force)
4311 {
4312 PDEVICE_NODE ChildDeviceNode, NextDeviceNode, FailedRemoveDevice;
4313 NTSTATUS Status;
4314 KIRQL OldIrql;
4315
4316 KeAcquireSpinLock(&IopDeviceTreeLock, &OldIrql);
4317 ChildDeviceNode = ParentDeviceNode->Child;
4318 while (ChildDeviceNode != NULL)
4319 {
4320 NextDeviceNode = ChildDeviceNode->Sibling;
4321 KeReleaseSpinLock(&IopDeviceTreeLock, OldIrql);
4322
4323 Status = IopPrepareDeviceForRemoval(ChildDeviceNode->PhysicalDeviceObject, Force);
4324 if (!NT_SUCCESS(Status))
4325 {
4326 FailedRemoveDevice = ChildDeviceNode;
4327 goto cleanup;
4328 }
4329
4330 KeAcquireSpinLock(&IopDeviceTreeLock, &OldIrql);
4331 ChildDeviceNode = NextDeviceNode;
4332 }
4333 KeReleaseSpinLock(&IopDeviceTreeLock, OldIrql);
4334
4335 return STATUS_SUCCESS;
4336
4337 cleanup:
4338 KeAcquireSpinLock(&IopDeviceTreeLock, &OldIrql);
4339 ChildDeviceNode = ParentDeviceNode->Child;
4340 while (ChildDeviceNode != NULL)
4341 {
4342 NextDeviceNode = ChildDeviceNode->Sibling;
4343 KeReleaseSpinLock(&IopDeviceTreeLock, OldIrql);
4344
4345 IopCancelPrepareDeviceForRemoval(ChildDeviceNode->PhysicalDeviceObject);
4346
4347 /* IRP_MN_CANCEL_REMOVE_DEVICE is also sent to the device
4348 * that failed the IRP_MN_QUERY_REMOVE_DEVICE request */
4349 if (ChildDeviceNode == FailedRemoveDevice)
4350 return Status;
4351
4352 ChildDeviceNode = NextDeviceNode;
4353
4354 KeAcquireSpinLock(&IopDeviceTreeLock, &OldIrql);
4355 }
4356 KeReleaseSpinLock(&IopDeviceTreeLock, OldIrql);
4357
4358 return Status;
4359 }
4360
4361 static
4362 VOID
4363 IopSendRemoveChildDevices(PDEVICE_NODE ParentDeviceNode)
4364 {
4365 PDEVICE_NODE ChildDeviceNode, NextDeviceNode;
4366 KIRQL OldIrql;
4367
4368 KeAcquireSpinLock(&IopDeviceTreeLock, &OldIrql);
4369 ChildDeviceNode = ParentDeviceNode->Child;
4370 while (ChildDeviceNode != NULL)
4371 {
4372 NextDeviceNode = ChildDeviceNode->Sibling;
4373 KeReleaseSpinLock(&IopDeviceTreeLock, OldIrql);
4374
4375 IopSendRemoveDevice(ChildDeviceNode->PhysicalDeviceObject);
4376
4377 ChildDeviceNode = NextDeviceNode;
4378
4379 KeAcquireSpinLock(&IopDeviceTreeLock, &OldIrql);
4380 }
4381 KeReleaseSpinLock(&IopDeviceTreeLock, OldIrql);
4382 }
4383
4384 static
4385 VOID
4386 IopCancelRemoveChildDevices(PDEVICE_NODE ParentDeviceNode)
4387 {
4388 PDEVICE_NODE ChildDeviceNode, NextDeviceNode;
4389 KIRQL OldIrql;
4390
4391 KeAcquireSpinLock(&IopDeviceTreeLock, &OldIrql);
4392 ChildDeviceNode = ParentDeviceNode->Child;
4393 while (ChildDeviceNode != NULL)
4394 {
4395 NextDeviceNode = ChildDeviceNode->Sibling;
4396 KeReleaseSpinLock(&IopDeviceTreeLock, OldIrql);
4397
4398 IopCancelPrepareDeviceForRemoval(ChildDeviceNode->PhysicalDeviceObject);
4399
4400 ChildDeviceNode = NextDeviceNode;
4401
4402 KeAcquireSpinLock(&IopDeviceTreeLock, &OldIrql);
4403 }
4404 KeReleaseSpinLock(&IopDeviceTreeLock, OldIrql);
4405 }
4406
4407 static
4408 NTSTATUS
4409 IopQueryRemoveDeviceRelations(PDEVICE_RELATIONS DeviceRelations, BOOLEAN Force)
4410 {
4411 /* This function DOES NOT dereference the device objects on SUCCESS
4412 * but it DOES dereference device objects on FAILURE */
4413
4414 ULONG i, j;
4415 NTSTATUS Status;
4416
4417 for (i = 0; i < DeviceRelations->Count; i++)
4418 {
4419 Status = IopPrepareDeviceForRemoval(DeviceRelations->Objects[i], Force);
4420 if (!NT_SUCCESS(Status))
4421 {
4422 j = i;
4423 goto cleanup;
4424 }
4425 }
4426
4427 return STATUS_SUCCESS;
4428
4429 cleanup:
4430 /* IRP_MN_CANCEL_REMOVE_DEVICE is also sent to the device
4431 * that failed the IRP_MN_QUERY_REMOVE_DEVICE request */
4432 for (i = 0; i <= j; i++)
4433 {
4434 IopCancelPrepareDeviceForRemoval(DeviceRelations->Objects[i]);
4435 ObDereferenceObject(DeviceRelations->Objects[i]);
4436 DeviceRelations->Objects[i] = NULL;
4437 }
4438 for (; i < DeviceRelations->Count; i++)
4439 {
4440 ObDereferenceObject(DeviceRelations->Objects[i]);
4441 DeviceRelations->Objects[i] = NULL;
4442 }
4443 ExFreePool(DeviceRelations);
4444
4445 return Status;
4446 }
4447
4448 static
4449 VOID
4450 IopSendRemoveDeviceRelations(PDEVICE_RELATIONS DeviceRelations)
4451 {
4452 /* This function DOES dereference the device objects in all cases */
4453
4454 ULONG i;
4455
4456 for (i = 0; i < DeviceRelations->Count; i++)
4457 {
4458 IopSendRemoveDevice(DeviceRelations->Objects[i]);
4459 DeviceRelations->Objects[i] = NULL;
4460 }
4461
4462 ExFreePool(DeviceRelations);
4463 }
4464
4465 static
4466 VOID
4467 IopCancelRemoveDeviceRelations(PDEVICE_RELATIONS DeviceRelations)
4468 {
4469 /* This function DOES dereference the device objects in all cases */
4470
4471 ULONG i;
4472
4473 for (i = 0; i < DeviceRelations->Count; i++)
4474 {
4475 IopCancelPrepareDeviceForRemoval(DeviceRelations->Objects[i]);
4476 ObDereferenceObject(DeviceRelations->Objects[i]);
4477 DeviceRelations->Objects[i] = NULL;
4478 }
4479
4480 ExFreePool(DeviceRelations);
4481 }
4482
4483 VOID
4484 IopCancelPrepareDeviceForRemoval(PDEVICE_OBJECT DeviceObject)
4485 {
4486 IO_STACK_LOCATION Stack;
4487 IO_STATUS_BLOCK IoStatusBlock;
4488 PDEVICE_RELATIONS DeviceRelations;
4489 NTSTATUS Status;
4490
4491 IopCancelRemoveDevice(DeviceObject);
4492
4493 Stack.Parameters.QueryDeviceRelations.Type = RemovalRelations;
4494
4495 Status = IopInitiatePnpIrp(DeviceObject,
4496 &IoStatusBlock,
4497 IRP_MN_QUERY_DEVICE_RELATIONS,
4498 &Stack);
4499 if (!NT_SUCCESS(Status))
4500 {
4501 DPRINT("IopInitiatePnpIrp() failed with status 0x%08lx\n", Status);
4502 DeviceRelations = NULL;
4503 }
4504 else
4505 {
4506 DeviceRelations = (PDEVICE_RELATIONS)IoStatusBlock.Information;
4507 }
4508
4509 if (DeviceRelations)
4510 IopCancelRemoveDeviceRelations(DeviceRelations);
4511 }
4512
4513 NTSTATUS
4514 IopPrepareDeviceForRemoval(IN PDEVICE_OBJECT DeviceObject, BOOLEAN Force)
4515 {
4516 PDEVICE_NODE DeviceNode = IopGetDeviceNode(DeviceObject);
4517 IO_STACK_LOCATION Stack;
4518 IO_STATUS_BLOCK IoStatusBlock;
4519 PDEVICE_RELATIONS DeviceRelations;
4520 NTSTATUS Status;
4521
4522 if ((DeviceNode->UserFlags & DNUF_NOT_DISABLEABLE) && !Force)
4523 {
4524 DPRINT1("Removal not allowed for %wZ\n", &DeviceNode->InstancePath);
4525 return STATUS_UNSUCCESSFUL;
4526 }
4527
4528 if (!Force && IopQueryRemoveDevice(DeviceObject) != STATUS_SUCCESS)
4529 {
4530 DPRINT1("Removal vetoed by failing the query remove request\n");
4531
4532 IopCancelRemoveDevice(DeviceObject);
4533
4534 return STATUS_UNSUCCESSFUL;
4535 }
4536
4537 Stack.Parameters.QueryDeviceRelations.Type = RemovalRelations;
4538
4539 Status = IopInitiatePnpIrp(DeviceObject,
4540 &IoStatusBlock,
4541 IRP_MN_QUERY_DEVICE_RELATIONS,
4542 &Stack);
4543 if (!NT_SUCCESS(Status))
4544 {
4545 DPRINT("IopInitiatePnpIrp() failed with status 0x%08lx\n", Status);
4546 DeviceRelations = NULL;
4547 }
4548 else
4549 {
4550 DeviceRelations = (PDEVICE_RELATIONS)IoStatusBlock.Information;
4551 }
4552
4553 if (DeviceRelations)
4554 {
4555 Status = IopQueryRemoveDeviceRelations(DeviceRelations, Force);
4556 if (!NT_SUCCESS(Status))
4557 return Status;
4558 }
4559
4560 Status = IopQueryRemoveChildDevices(DeviceNode, Force);
4561 if (!NT_SUCCESS(Status))
4562 {
4563 if (DeviceRelations)
4564 IopCancelRemoveDeviceRelations(DeviceRelations);
4565 return Status;
4566 }
4567
4568 if (DeviceRelations)
4569 IopSendRemoveDeviceRelations(DeviceRelations);
4570 IopSendRemoveChildDevices(DeviceNode);
4571
4572 return STATUS_SUCCESS;
4573 }
4574
4575 NTSTATUS
4576 IopRemoveDevice(PDEVICE_NODE DeviceNode)
4577 {
4578 NTSTATUS Status;
4579
4580 DPRINT("Removing device: %wZ\n", &DeviceNode->InstancePath);
4581
4582 Status = IopPrepareDeviceForRemoval(DeviceNode->PhysicalDeviceObject, FALSE);
4583 if (NT_SUCCESS(Status))
4584 {
4585 IopSendRemoveDevice(DeviceNode->PhysicalDeviceObject);
4586 IopQueueTargetDeviceEvent(&GUID_DEVICE_SAFE_REMOVAL,
4587 &DeviceNode->InstancePath);
4588 return STATUS_SUCCESS;
4589 }
4590
4591 return Status;
4592 }
4593
4594 /*
4595 * @implemented
4596 */
4597 VOID
4598 NTAPI
4599 IoRequestDeviceEject(IN PDEVICE_OBJECT PhysicalDeviceObject)
4600 {
4601 PDEVICE_NODE DeviceNode = IopGetDeviceNode(PhysicalDeviceObject);
4602 PDEVICE_RELATIONS DeviceRelations;
4603 IO_STATUS_BLOCK IoStatusBlock;
4604 IO_STACK_LOCATION Stack;
4605 DEVICE_CAPABILITIES Capabilities;
4606 NTSTATUS Status;
4607
4608 IopQueueTargetDeviceEvent(&GUID_DEVICE_KERNEL_INITIATED_EJECT,
4609 &DeviceNode->InstancePath);
4610
4611 if (IopQueryDeviceCapabilities(DeviceNode, &Capabilities) != STATUS_SUCCESS)
4612 {
4613 goto cleanup;
4614 }
4615
4616 Stack.Parameters.QueryDeviceRelations.Type = EjectionRelations;
4617
4618 Status = IopInitiatePnpIrp(PhysicalDeviceObject,
4619 &IoStatusBlock,
4620 IRP_MN_QUERY_DEVICE_RELATIONS,
4621 &Stack);
4622 if (!NT_SUCCESS(Status))
4623 {
4624 DPRINT("IopInitiatePnpIrp() failed with status 0x%08lx\n", Status);
4625 DeviceRelations = NULL;
4626 }
4627 else
4628 {
4629 DeviceRelations = (PDEVICE_RELATIONS)IoStatusBlock.Information;
4630 }
4631
4632 if (DeviceRelations)
4633 {
4634 Status = IopQueryRemoveDeviceRelations(DeviceRelations, FALSE);
4635 if (!NT_SUCCESS(Status))
4636 goto cleanup;
4637 }
4638
4639 Status = IopQueryRemoveChildDevices(DeviceNode, FALSE);
4640 if (!NT_SUCCESS(Status))
4641 {
4642 if (DeviceRelations)
4643 IopCancelRemoveDeviceRelations(DeviceRelations);
4644 goto cleanup;
4645 }
4646
4647 if (IopPrepareDeviceForRemoval(PhysicalDeviceObject, FALSE) != STATUS_SUCCESS)
4648 {
4649 if (DeviceRelations)
4650 IopCancelRemoveDeviceRelations(DeviceRelations);
4651 IopCancelRemoveChildDevices(DeviceNode);
4652 goto cleanup;
4653 }
4654
4655 if (DeviceRelations)
4656 IopSendRemoveDeviceRelations(DeviceRelations);
4657 IopSendRemoveChildDevices(DeviceNode);
4658
4659 DeviceNode->Problem = CM_PROB_HELD_FOR_EJECT;
4660 if (Capabilities.EjectSupported)
4661 {
4662 if (IopSendEject(PhysicalDeviceObject) != STATUS_SUCCESS)
4663 {
4664 goto cleanup;
4665 }
4666 }
4667 else
4668 {
4669 DeviceNode->Flags |= DNF_DISABLED;
4670 }
4671
4672 IopQueueTargetDeviceEvent(&GUID_DEVICE_EJECT,
4673 &DeviceNode->InstancePath);
4674
4675 return;
4676
4677 cleanup:
4678 IopQueueTargetDeviceEvent(&GUID_DEVICE_EJECT_VETOED,
4679 &DeviceNode->InstancePath);
4680 }
4681
4682 /*
4683 * @implemented
4684 */
4685 VOID
4686 NTAPI
4687 IoInvalidateDeviceRelations(
4688 IN PDEVICE_OBJECT DeviceObject,
4689 IN DEVICE_RELATION_TYPE Type)
4690 {
4691 PINVALIDATE_DEVICE_RELATION_DATA Data;
4692 KIRQL OldIrql;
4693
4694 Data = ExAllocatePool(NonPagedPool, sizeof(INVALIDATE_DEVICE_RELATION_DATA));
4695 if (!Data)
4696 return;
4697
4698 ObReferenceObject(DeviceObject);
4699 Data->DeviceObject = DeviceObject;
4700 Data->Type = Type;
4701
4702 KeAcquireSpinLock(&IopDeviceRelationsSpinLock, &OldIrql);
4703 InsertTailList(&IopDeviceRelationsRequestList, &Data->RequestListEntry);
4704 if (IopDeviceRelationsRequestInProgress)
4705 {
4706 KeReleaseSpinLock(&IopDeviceRelationsSpinLock, OldIrql);
4707 return;
4708 }
4709 IopDeviceRelationsRequestInProgress = TRUE;
4710 KeReleaseSpinLock(&IopDeviceRelationsSpinLock, OldIrql);
4711
4712 ExInitializeWorkItem(&IopDeviceRelationsWorkItem,
4713 IopDeviceRelationsWorker,
4714 NULL);
4715 ExQueueWorkItem(&IopDeviceRelationsWorkItem,
4716 DelayedWorkQueue);
4717 }
4718
4719 /*
4720 * @implemented
4721 */
4722 NTSTATUS
4723 NTAPI
4724 IoSynchronousInvalidateDeviceRelations(
4725 IN PDEVICE_OBJECT DeviceObject,
4726 IN DEVICE_RELATION_TYPE Type)
4727 {
4728 PAGED_CODE();
4729
4730 switch (Type)
4731 {
4732 case BusRelations:
4733 /* Enumerate the device */
4734 return IopEnumerateDevice(DeviceObject);
4735 case PowerRelations:
4736 /* Not handled yet */
4737 return STATUS_NOT_IMPLEMENTED;
4738 case TargetDeviceRelation:
4739 /* Nothing to do */
4740 return STATUS_SUCCESS;
4741 default:
4742 /* Ejection relations are not supported */
4743 return STATUS_NOT_SUPPORTED;
4744 }
4745 }
4746
4747 /*
4748 * @implemented
4749 */
4750 BOOLEAN
4751 NTAPI
4752 IoTranslateBusAddress(IN INTERFACE_TYPE InterfaceType,
4753 IN ULONG BusNumber,
4754 IN PHYSICAL_ADDRESS BusAddress,
4755 IN OUT PULONG AddressSpace,
4756 OUT PPHYSICAL_ADDRESS TranslatedAddress)
4757 {
4758 /* FIXME: Notify the resource arbiter */
4759
4760 return HalTranslateBusAddress(InterfaceType,
4761 BusNumber,
4762 BusAddress,
4763 AddressSpace,
4764 TranslatedAddress);
4765 }