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