[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 //#define ENABLE_ACPI
17
18 /* GLOBALS *******************************************************************/
19
20 PDEVICE_NODE IopRootDeviceNode;
21 KSPIN_LOCK IopDeviceTreeLock;
22 ERESOURCE PpRegistryDeviceResource;
23 KGUARDED_MUTEX PpDeviceReferenceTableLock;
24 RTL_AVL_TABLE PpDeviceReferenceTable;
25
26 extern ULONG ExpInitializationPhase;
27 extern BOOLEAN PnpSystemInit;
28
29 /* DATA **********************************************************************/
30
31 PDRIVER_OBJECT IopRootDriverObject;
32 PIO_BUS_TYPE_GUID_LIST PnpBusTypeGuidList = NULL;
33
34 #if defined (ALLOC_PRAGMA)
35 #pragma alloc_text(INIT, PnpInit)
36 #pragma alloc_text(INIT, PnpInit2)
37 #endif
38
39 typedef struct _INVALIDATE_DEVICE_RELATION_DATA
40 {
41 PDEVICE_OBJECT DeviceObject;
42 DEVICE_RELATION_TYPE Type;
43 PIO_WORKITEM WorkItem;
44 } INVALIDATE_DEVICE_RELATION_DATA, *PINVALIDATE_DEVICE_RELATION_DATA;
45
46 /* FUNCTIONS *****************************************************************/
47 NTSTATUS
48 NTAPI
49 IopCreateDeviceKeyPath(IN PCUNICODE_STRING RegistryPath,
50 IN ULONG CreateOptions,
51 OUT PHANDLE Handle);
52
53 PDEVICE_NODE
54 FASTCALL
55 IopGetDeviceNode(PDEVICE_OBJECT DeviceObject)
56 {
57 return ((PEXTENDED_DEVOBJ_EXTENSION)DeviceObject->DeviceObjectExtension)->DeviceNode;
58 }
59
60 NTSTATUS
61 FASTCALL
62 IopInitializeDevice(PDEVICE_NODE DeviceNode,
63 PDRIVER_OBJECT DriverObject)
64 {
65 PDEVICE_OBJECT Fdo;
66 NTSTATUS Status;
67
68 if (!DriverObject->DriverExtension->AddDevice)
69 return STATUS_SUCCESS;
70
71 /* This is a Plug and Play driver */
72 DPRINT("Plug and Play driver found\n");
73 ASSERT(DeviceNode->PhysicalDeviceObject);
74
75 /* Check if this plug-and-play driver is used as a legacy one for this device node */
76 if (IopDeviceNodeHasFlag(DeviceNode, DNF_LEGACY_DRIVER))
77 {
78 IopDeviceNodeSetFlag(DeviceNode, DNF_ADDED);
79 return STATUS_SUCCESS;
80 }
81
82 DPRINT("Calling %wZ->AddDevice(%wZ)\n",
83 &DriverObject->DriverName,
84 &DeviceNode->InstancePath);
85 Status = DriverObject->DriverExtension->AddDevice(
86 DriverObject, DeviceNode->PhysicalDeviceObject);
87 if (!NT_SUCCESS(Status))
88 {
89 IopDeviceNodeSetFlag(DeviceNode, DNF_DISABLED);
90 return Status;
91 }
92
93 /* Check if driver added a FDO above the PDO */
94 Fdo = IoGetAttachedDeviceReference(DeviceNode->PhysicalDeviceObject);
95 if (Fdo == DeviceNode->PhysicalDeviceObject)
96 {
97 /* FIXME: What do we do? Unload the driver or just disable the device? */
98 DPRINT1("An FDO was not attached\n");
99 ObDereferenceObject(Fdo);
100 IopDeviceNodeSetFlag(DeviceNode, DNF_DISABLED);
101 return STATUS_UNSUCCESSFUL;
102 }
103
104 /* Check if we have a ACPI device (needed for power management) */
105 if (Fdo->DeviceType == FILE_DEVICE_ACPI)
106 {
107 static BOOLEAN SystemPowerDeviceNodeCreated = FALSE;
108
109 /* There can be only one system power device */
110 if (!SystemPowerDeviceNodeCreated)
111 {
112 PopSystemPowerDeviceNode = DeviceNode;
113 ObReferenceObject(PopSystemPowerDeviceNode);
114 SystemPowerDeviceNodeCreated = TRUE;
115 }
116 }
117
118 ObDereferenceObject(Fdo);
119
120 IopDeviceNodeSetFlag(DeviceNode, DNF_ADDED);
121
122 return STATUS_SUCCESS;
123 }
124
125 VOID
126 NTAPI
127 IopStartDevice2(IN PDEVICE_OBJECT DeviceObject)
128 {
129 IO_STACK_LOCATION Stack;
130 PDEVICE_NODE DeviceNode;
131 NTSTATUS Status;
132 PVOID Dummy;
133
134 /* Get the device node */
135 DeviceNode = IopGetDeviceNode(DeviceObject);
136
137 /* Build the I/O stack locaiton */
138 RtlZeroMemory(&Stack, sizeof(IO_STACK_LOCATION));
139 Stack.MajorFunction = IRP_MJ_PNP;
140 Stack.MinorFunction = IRP_MN_START_DEVICE;
141
142 /* Check if we didn't already report the resources */
143 if (!(DeviceNode->Flags & DNF_RESOURCE_REPORTED))
144 {
145 /* Report them */
146 Stack.Parameters.StartDevice.AllocatedResources =
147 DeviceNode->ResourceList;
148 Stack.Parameters.StartDevice.AllocatedResourcesTranslated =
149 DeviceNode->ResourceListTranslated;
150 }
151
152 /* I don't think we set this flag yet */
153 ASSERT(!(DeviceNode->Flags & DNF_STOPPED));
154
155 /* Do the call */
156 Status = IopSynchronousCall(DeviceObject, &Stack, &Dummy);
157 if (!NT_SUCCESS(Status))
158 {
159 /* We failed start */
160 DeviceNode->Flags |= DNF_START_FAILED;
161
162 /* TODO: Undo all the stuff we did up to this point */
163
164 DPRINT1("Warning: PnP Start failed (%wZ)\n", &DeviceNode->InstancePath);
165 return;
166 }
167
168 /* Otherwise, mark us as started */
169 DeviceNode->Flags |= DNF_STARTED;
170
171 /* We reported the resources */
172 DeviceNode->Flags |= DNF_RESOURCE_REPORTED;
173
174 /* We now need enumeration */
175 DeviceNode->Flags |= DNF_NEED_ENUMERATION_ONLY;
176 }
177
178 NTSTATUS
179 NTAPI
180 IopStartAndEnumerateDevice(IN PDEVICE_NODE DeviceNode)
181 {
182 PDEVICE_OBJECT DeviceObject;
183 NTSTATUS Status;
184 PAGED_CODE();
185
186 /* Sanity check */
187 // ASSERT((DeviceNode->Flags & DNF_ADDED) || (DeviceNode->Flags & DNF_ENUMERATED));
188 if (!(DeviceNode->Flags & DNF_ADDED) && !(DeviceNode->Flags & DNF_ENUMERATED))
189 DPRINT1("Warning: Starting a device node without DNF_ADDED or DNF_ENUMERATED (%wZ)\n",
190 &DeviceNode->InstancePath);
191 ASSERT((DeviceNode->Flags & (DNF_RESOURCE_ASSIGNED |
192 DNF_RESOURCE_REPORTED |
193 DNF_NO_RESOURCE_REQUIRED)));
194 ASSERT((!(DeviceNode->Flags & (DNF_HAS_PROBLEM |
195 DNF_STARTED |
196 DNF_START_REQUEST_PENDING))));
197
198 /* Get the device object */
199 DeviceObject = DeviceNode->PhysicalDeviceObject;
200
201 /* Check if we're not started yet */
202 if (!(DeviceNode->Flags & DNF_STARTED))
203 {
204 /* Start us */
205 IopStartDevice2(DeviceObject);
206 }
207
208 /* Do we need to query IDs? This happens in the case of manual reporting */
209 #if 0
210 if (DeviceNode->Flags & DNF_NEED_QUERY_IDS)
211 {
212 DPRINT1("Warning: Device node has DNF_NEED_QUERY_IDS\n");
213 /* And that case shouldn't happen yet */
214 ASSERT(FALSE);
215 }
216 #endif
217
218 /* Make sure we're started, and check if we need enumeration */
219 if ((DeviceNode->Flags & DNF_STARTED) &&
220 (DeviceNode->Flags & DNF_NEED_ENUMERATION_ONLY))
221 {
222 /* Enumerate us */
223 IoSynchronousInvalidateDeviceRelations(DeviceObject, BusRelations);
224 IopDeviceNodeClearFlag(DeviceNode, DNF_NEED_ENUMERATION_ONLY);
225 Status = STATUS_SUCCESS;
226 }
227 else
228 {
229 /* Nothing to do */
230 Status = STATUS_SUCCESS;
231 }
232
233 /* Return */
234 return Status;
235 }
236
237 NTSTATUS
238 IopStartDevice(
239 PDEVICE_NODE DeviceNode)
240 {
241 NTSTATUS Status;
242 HANDLE InstanceHandle = INVALID_HANDLE_VALUE, ControlHandle = INVALID_HANDLE_VALUE;
243 UNICODE_STRING KeyName;
244 OBJECT_ATTRIBUTES ObjectAttributes;
245
246 Status = IopAssignDeviceResources(DeviceNode);
247 if (!NT_SUCCESS(Status))
248 goto ByeBye;
249
250 /* New PnP ABI */
251 IopStartAndEnumerateDevice(DeviceNode);
252
253 /* FIX: Should be done in new device instance code */
254 Status = IopCreateDeviceKeyPath(&DeviceNode->InstancePath, 0, &InstanceHandle);
255 if (!NT_SUCCESS(Status))
256 goto ByeBye;
257
258 /* FIX: Should be done in IoXxxPrepareDriverLoading */
259 // {
260 RtlInitUnicodeString(&KeyName, L"Control");
261 InitializeObjectAttributes(&ObjectAttributes,
262 &KeyName,
263 OBJ_CASE_INSENSITIVE,
264 InstanceHandle,
265 NULL);
266 Status = ZwCreateKey(&ControlHandle, KEY_SET_VALUE, &ObjectAttributes, 0, NULL, REG_OPTION_VOLATILE, NULL);
267 if (!NT_SUCCESS(Status))
268 goto ByeBye;
269
270 RtlInitUnicodeString(&KeyName, L"ActiveService");
271 Status = ZwSetValueKey(ControlHandle, &KeyName, 0, REG_SZ, DeviceNode->ServiceName.Buffer, DeviceNode->ServiceName.Length);
272 // }
273
274 ByeBye:
275 if (ControlHandle != INVALID_HANDLE_VALUE)
276 ZwClose(ControlHandle);
277
278 if (InstanceHandle != INVALID_HANDLE_VALUE)
279 ZwClose(InstanceHandle);
280
281 return Status;
282 }
283
284 NTSTATUS
285 NTAPI
286 IopQueryDeviceCapabilities(PDEVICE_NODE DeviceNode,
287 PDEVICE_CAPABILITIES DeviceCaps)
288 {
289 IO_STATUS_BLOCK StatusBlock;
290 IO_STACK_LOCATION Stack;
291
292 /* Set up the Header */
293 RtlZeroMemory(DeviceCaps, sizeof(DEVICE_CAPABILITIES));
294 DeviceCaps->Size = sizeof(DEVICE_CAPABILITIES);
295 DeviceCaps->Version = 1;
296 DeviceCaps->Address = -1;
297 DeviceCaps->UINumber = -1;
298
299 /* Set up the Stack */
300 RtlZeroMemory(&Stack, sizeof(IO_STACK_LOCATION));
301 Stack.Parameters.DeviceCapabilities.Capabilities = DeviceCaps;
302
303 /* Send the IRP */
304 return IopInitiatePnpIrp(DeviceNode->PhysicalDeviceObject,
305 &StatusBlock,
306 IRP_MN_QUERY_CAPABILITIES,
307 &Stack);
308 }
309
310 static VOID NTAPI
311 IopAsynchronousInvalidateDeviceRelations(
312 IN PDEVICE_OBJECT DeviceObject,
313 IN PVOID InvalidateContext)
314 {
315 PINVALIDATE_DEVICE_RELATION_DATA Data = InvalidateContext;
316
317 IoSynchronousInvalidateDeviceRelations(
318 Data->DeviceObject,
319 Data->Type);
320
321 ObDereferenceObject(Data->DeviceObject);
322 IoFreeWorkItem(Data->WorkItem);
323 ExFreePool(Data);
324 }
325
326 NTSTATUS
327 IopGetSystemPowerDeviceObject(PDEVICE_OBJECT *DeviceObject)
328 {
329 KIRQL OldIrql;
330
331 if (PopSystemPowerDeviceNode)
332 {
333 KeAcquireSpinLock(&IopDeviceTreeLock, &OldIrql);
334 *DeviceObject = PopSystemPowerDeviceNode->PhysicalDeviceObject;
335 KeReleaseSpinLock(&IopDeviceTreeLock, OldIrql);
336
337 return STATUS_SUCCESS;
338 }
339
340 return STATUS_UNSUCCESSFUL;
341 }
342
343 USHORT
344 NTAPI
345 IopGetBusTypeGuidIndex(LPGUID BusTypeGuid)
346 {
347 USHORT i = 0, FoundIndex = 0xFFFF;
348 ULONG NewSize;
349 PVOID NewList;
350
351 /* Acquire the lock */
352 ExAcquireFastMutex(&PnpBusTypeGuidList->Lock);
353
354 /* Loop all entries */
355 while (i < PnpBusTypeGuidList->GuidCount)
356 {
357 /* Try to find a match */
358 if (RtlCompareMemory(BusTypeGuid,
359 &PnpBusTypeGuidList->Guids[i],
360 sizeof(GUID)) == sizeof(GUID))
361 {
362 /* Found it */
363 FoundIndex = i;
364 goto Quickie;
365 }
366 i++;
367 }
368
369 /* Check if we have to grow the list */
370 if (PnpBusTypeGuidList->GuidCount)
371 {
372 /* Calculate the new size */
373 NewSize = sizeof(IO_BUS_TYPE_GUID_LIST) +
374 (sizeof(GUID) * PnpBusTypeGuidList->GuidCount);
375
376 /* Allocate the new copy */
377 NewList = ExAllocatePool(PagedPool, NewSize);
378
379 if (!NewList) {
380 /* Fail */
381 ExFreePool(PnpBusTypeGuidList);
382 goto Quickie;
383 }
384
385 /* Now copy them, decrease the size too */
386 NewSize -= sizeof(GUID);
387 RtlCopyMemory(NewList, PnpBusTypeGuidList, NewSize);
388
389 /* Free the old list */
390 ExFreePool(PnpBusTypeGuidList);
391
392 /* Use the new buffer */
393 PnpBusTypeGuidList = NewList;
394 }
395
396 /* Copy the new GUID */
397 RtlCopyMemory(&PnpBusTypeGuidList->Guids[PnpBusTypeGuidList->GuidCount],
398 BusTypeGuid,
399 sizeof(GUID));
400
401 /* The new entry is the index */
402 FoundIndex = (USHORT)PnpBusTypeGuidList->GuidCount;
403 PnpBusTypeGuidList->GuidCount++;
404
405 Quickie:
406 ExReleaseFastMutex(&PnpBusTypeGuidList->Lock);
407 return FoundIndex;
408 }
409
410 /*
411 * DESCRIPTION
412 * Creates a device node
413 *
414 * ARGUMENTS
415 * ParentNode = Pointer to parent device node
416 * PhysicalDeviceObject = Pointer to PDO for device object. Pass NULL
417 * to have the root device node create one
418 * (eg. for legacy drivers)
419 * DeviceNode = Pointer to storage for created device node
420 *
421 * RETURN VALUE
422 * Status
423 */
424 NTSTATUS
425 IopCreateDeviceNode(PDEVICE_NODE ParentNode,
426 PDEVICE_OBJECT PhysicalDeviceObject,
427 PUNICODE_STRING ServiceName,
428 PDEVICE_NODE *DeviceNode)
429 {
430 PDEVICE_NODE Node;
431 NTSTATUS Status;
432 KIRQL OldIrql;
433 UNICODE_STRING FullServiceName;
434 UNICODE_STRING LegacyPrefix = RTL_CONSTANT_STRING(L"LEGACY_");
435 UNICODE_STRING UnknownDeviceName = RTL_CONSTANT_STRING(L"UNKNOWN");
436 UNICODE_STRING KeyName, ClassName;
437 PUNICODE_STRING ServiceName1;
438 ULONG LegacyValue;
439 #if 0
440 UNICODE_STRING ClassGUID;
441 #endif
442 HANDLE InstanceHandle;
443
444 DPRINT("ParentNode 0x%p PhysicalDeviceObject 0x%p ServiceName %wZ\n",
445 ParentNode, PhysicalDeviceObject, ServiceName);
446
447 Node = (PDEVICE_NODE)ExAllocatePool(NonPagedPool, sizeof(DEVICE_NODE));
448 if (!Node)
449 {
450 return STATUS_INSUFFICIENT_RESOURCES;
451 }
452
453 RtlZeroMemory(Node, sizeof(DEVICE_NODE));
454
455 if (!ServiceName)
456 ServiceName1 = &UnknownDeviceName;
457 else
458 ServiceName1 = ServiceName;
459
460 if (!PhysicalDeviceObject)
461 {
462 FullServiceName.MaximumLength = LegacyPrefix.Length + ServiceName1->Length;
463 FullServiceName.Length = 0;
464 FullServiceName.Buffer = ExAllocatePool(PagedPool, FullServiceName.MaximumLength);
465 if (!FullServiceName.Buffer)
466 {
467 ExFreePool(Node);
468 return STATUS_INSUFFICIENT_RESOURCES;
469 }
470
471 RtlAppendUnicodeStringToString(&FullServiceName, &LegacyPrefix);
472 RtlAppendUnicodeStringToString(&FullServiceName, ServiceName1);
473
474 Status = PnpRootCreateDevice(&FullServiceName, &PhysicalDeviceObject, &Node->InstancePath);
475 if (!NT_SUCCESS(Status))
476 {
477 DPRINT1("PnpRootCreateDevice() failed with status 0x%08X\n", Status);
478 ExFreePool(Node);
479 return Status;
480 }
481
482 /* Create the device key for legacy drivers */
483 Status = IopCreateDeviceKeyPath(&Node->InstancePath, REG_OPTION_VOLATILE, &InstanceHandle);
484 if (!NT_SUCCESS(Status))
485 {
486 ZwClose(InstanceHandle);
487 ExFreePool(Node);
488 ExFreePool(FullServiceName.Buffer);
489 return Status;
490 }
491
492 Node->ServiceName.Buffer = ExAllocatePool(PagedPool, ServiceName1->Length);
493 if (!Node->ServiceName.Buffer)
494 {
495 ZwClose(InstanceHandle);
496 ExFreePool(Node);
497 ExFreePool(FullServiceName.Buffer);
498 return Status;
499 }
500
501 Node->ServiceName.MaximumLength = ServiceName1->Length;
502 Node->ServiceName.Length = 0;
503
504 RtlAppendUnicodeStringToString(&Node->ServiceName, ServiceName1);
505
506 if (ServiceName)
507 {
508 RtlInitUnicodeString(&KeyName, L"Service");
509 Status = ZwSetValueKey(InstanceHandle, &KeyName, 0, REG_SZ, ServiceName->Buffer, ServiceName->Length);
510 }
511
512 if (NT_SUCCESS(Status))
513 {
514 RtlInitUnicodeString(&KeyName, L"Legacy");
515
516 LegacyValue = 1;
517 Status = ZwSetValueKey(InstanceHandle, &KeyName, 0, REG_DWORD, &LegacyValue, sizeof(LegacyValue));
518 if (NT_SUCCESS(Status))
519 {
520 RtlInitUnicodeString(&KeyName, L"Class");
521
522 RtlInitUnicodeString(&ClassName, L"LegacyDriver");
523 Status = ZwSetValueKey(InstanceHandle, &KeyName, 0, REG_SZ, ClassName.Buffer, ClassName.Length);
524 #if 0
525 if (NT_SUCCESS(Status))
526 {
527 RtlInitUnicodeString(&KeyName, L"ClassGUID");
528
529 RtlInitUnicodeString(&ClassGUID, L"{8ECC055D-047F-11D1-A537-0000F8753ED1}");
530 Status = ZwSetValueKey(InstanceHandle, &KeyName, 0, REG_SZ, ClassGUID.Buffer, ClassGUID.Length);
531 }
532 #endif
533 }
534 }
535
536 ZwClose(InstanceHandle);
537 ExFreePool(FullServiceName.Buffer);
538
539 if (!NT_SUCCESS(Status))
540 {
541 ExFreePool(Node);
542 return Status;
543 }
544
545 /* This is for drivers passed on the command line to ntoskrnl.exe */
546 IopDeviceNodeSetFlag(Node, DNF_LEGACY_DRIVER);
547 }
548
549 Node->PhysicalDeviceObject = PhysicalDeviceObject;
550
551 ((PEXTENDED_DEVOBJ_EXTENSION)PhysicalDeviceObject->DeviceObjectExtension)->DeviceNode = Node;
552
553 if (ParentNode)
554 {
555 KeAcquireSpinLock(&IopDeviceTreeLock, &OldIrql);
556 Node->Parent = ParentNode;
557 Node->Sibling = ParentNode->Child;
558 ParentNode->Child = Node;
559 if (ParentNode->LastChild == NULL)
560 ParentNode->LastChild = Node;
561 KeReleaseSpinLock(&IopDeviceTreeLock, OldIrql);
562 Node->Level = ParentNode->Level + 1;
563 }
564
565 PhysicalDeviceObject->Flags &= ~DO_DEVICE_INITIALIZING;
566
567 *DeviceNode = Node;
568
569 return STATUS_SUCCESS;
570 }
571
572 NTSTATUS
573 IopFreeDeviceNode(PDEVICE_NODE DeviceNode)
574 {
575 KIRQL OldIrql;
576 PDEVICE_NODE PrevSibling = NULL;
577
578 /* All children must be deleted before a parent is deleted */
579 ASSERT(!DeviceNode->Child);
580
581 KeAcquireSpinLock(&IopDeviceTreeLock, &OldIrql);
582
583 ASSERT(DeviceNode->PhysicalDeviceObject);
584
585 ObDereferenceObject(DeviceNode->PhysicalDeviceObject);
586
587 /* Get previous sibling */
588 if (DeviceNode->Parent && DeviceNode->Parent->Child != DeviceNode)
589 {
590 PrevSibling = DeviceNode->Parent->Child;
591 while (PrevSibling->Sibling != DeviceNode)
592 PrevSibling = PrevSibling->Sibling;
593 }
594
595 /* Unlink from parent if it exists */
596 if (DeviceNode->Parent)
597 {
598 if (DeviceNode->Parent->LastChild == DeviceNode)
599 {
600 DeviceNode->Parent->LastChild = PrevSibling;
601 if (PrevSibling)
602 PrevSibling->Sibling = NULL;
603 }
604 if (DeviceNode->Parent->Child == DeviceNode)
605 DeviceNode->Parent->Child = DeviceNode->Sibling;
606 }
607
608 /* Unlink from sibling list */
609 if (PrevSibling)
610 PrevSibling->Sibling = DeviceNode->Sibling;
611
612 KeReleaseSpinLock(&IopDeviceTreeLock, OldIrql);
613
614 RtlFreeUnicodeString(&DeviceNode->InstancePath);
615
616 RtlFreeUnicodeString(&DeviceNode->ServiceName);
617
618 if (DeviceNode->ResourceList)
619 {
620 ExFreePool(DeviceNode->ResourceList);
621 }
622
623 if (DeviceNode->ResourceListTranslated)
624 {
625 ExFreePool(DeviceNode->ResourceListTranslated);
626 }
627
628 if (DeviceNode->ResourceRequirements)
629 {
630 ExFreePool(DeviceNode->ResourceRequirements);
631 }
632
633 if (DeviceNode->BootResources)
634 {
635 ExFreePool(DeviceNode->BootResources);
636 }
637
638 ExFreePool(DeviceNode);
639
640 return STATUS_SUCCESS;
641 }
642
643 NTSTATUS
644 NTAPI
645 IopSynchronousCall(IN PDEVICE_OBJECT DeviceObject,
646 IN PIO_STACK_LOCATION IoStackLocation,
647 OUT PVOID *Information)
648 {
649 PIRP Irp;
650 PIO_STACK_LOCATION IrpStack;
651 IO_STATUS_BLOCK IoStatusBlock;
652 KEVENT Event;
653 NTSTATUS Status;
654 PDEVICE_OBJECT TopDeviceObject;
655 PAGED_CODE();
656
657 /* Call the top of the device stack */
658 TopDeviceObject = IoGetAttachedDeviceReference(DeviceObject);
659
660 /* Allocate an IRP */
661 Irp = IoAllocateIrp(TopDeviceObject->StackSize, FALSE);
662 if (!Irp) return STATUS_INSUFFICIENT_RESOURCES;
663
664 /* Initialize to failure */
665 Irp->IoStatus.Status = IoStatusBlock.Status = STATUS_NOT_SUPPORTED;
666 Irp->IoStatus.Information = IoStatusBlock.Information = 0;
667
668 /* Initialize the event */
669 KeInitializeEvent(&Event, SynchronizationEvent, FALSE);
670
671 /* Set them up */
672 Irp->UserIosb = &IoStatusBlock;
673 Irp->UserEvent = &Event;
674
675 /* Queue the IRP */
676 Irp->Tail.Overlay.Thread = PsGetCurrentThread();
677 IoQueueThreadIrp(Irp);
678
679 /* Copy-in the stack */
680 IrpStack = IoGetNextIrpStackLocation(Irp);
681 *IrpStack = *IoStackLocation;
682
683 /* Call the driver */
684 Status = IoCallDriver(TopDeviceObject, Irp);
685 if (Status == STATUS_PENDING)
686 {
687 /* Wait for it */
688 KeWaitForSingleObject(&Event,
689 Executive,
690 KernelMode,
691 FALSE,
692 NULL);
693 Status = IoStatusBlock.Status;
694 }
695
696 /* Return the information */
697 *Information = (PVOID)IoStatusBlock.Information;
698 return Status;
699 }
700
701 NTSTATUS
702 NTAPI
703 IopInitiatePnpIrp(IN PDEVICE_OBJECT DeviceObject,
704 IN OUT PIO_STATUS_BLOCK IoStatusBlock,
705 IN ULONG MinorFunction,
706 IN PIO_STACK_LOCATION Stack OPTIONAL)
707 {
708 IO_STACK_LOCATION IoStackLocation;
709
710 /* Fill out the stack information */
711 RtlZeroMemory(&IoStackLocation, sizeof(IO_STACK_LOCATION));
712 IoStackLocation.MajorFunction = IRP_MJ_PNP;
713 IoStackLocation.MinorFunction = MinorFunction;
714 if (Stack)
715 {
716 /* Copy the rest */
717 RtlCopyMemory(&IoStackLocation.Parameters,
718 &Stack->Parameters,
719 sizeof(Stack->Parameters));
720 }
721
722 /* Do the PnP call */
723 IoStatusBlock->Status = IopSynchronousCall(DeviceObject,
724 &IoStackLocation,
725 (PVOID)&IoStatusBlock->Information);
726 return IoStatusBlock->Status;
727 }
728
729 NTSTATUS
730 IopTraverseDeviceTreeNode(PDEVICETREE_TRAVERSE_CONTEXT Context)
731 {
732 PDEVICE_NODE ParentDeviceNode;
733 PDEVICE_NODE ChildDeviceNode;
734 NTSTATUS Status;
735
736 /* Copy context data so we don't overwrite it in subsequent calls to this function */
737 ParentDeviceNode = Context->DeviceNode;
738
739 /* Call the action routine */
740 Status = (Context->Action)(ParentDeviceNode, Context->Context);
741 if (!NT_SUCCESS(Status))
742 {
743 return Status;
744 }
745
746 /* Traversal of all children nodes */
747 for (ChildDeviceNode = ParentDeviceNode->Child;
748 ChildDeviceNode != NULL;
749 ChildDeviceNode = ChildDeviceNode->Sibling)
750 {
751 /* Pass the current device node to the action routine */
752 Context->DeviceNode = ChildDeviceNode;
753
754 Status = IopTraverseDeviceTreeNode(Context);
755 if (!NT_SUCCESS(Status))
756 {
757 return Status;
758 }
759 }
760
761 return Status;
762 }
763
764
765 NTSTATUS
766 IopTraverseDeviceTree(PDEVICETREE_TRAVERSE_CONTEXT Context)
767 {
768 NTSTATUS Status;
769
770 DPRINT("Context 0x%p\n", Context);
771
772 DPRINT("IopTraverseDeviceTree(DeviceNode 0x%p FirstDeviceNode 0x%p Action %x Context 0x%p)\n",
773 Context->DeviceNode, Context->FirstDeviceNode, Context->Action, Context->Context);
774
775 /* Start from the specified device node */
776 Context->DeviceNode = Context->FirstDeviceNode;
777
778 /* Recursively traverse the device tree */
779 Status = IopTraverseDeviceTreeNode(Context);
780 if (Status == STATUS_UNSUCCESSFUL)
781 {
782 /* The action routine just wanted to terminate the traversal with status
783 code STATUS_SUCCESS */
784 Status = STATUS_SUCCESS;
785 }
786
787 return Status;
788 }
789
790
791 /*
792 * IopCreateDeviceKeyPath
793 *
794 * Creates a registry key
795 *
796 * Parameters
797 * RegistryPath
798 * Name of the key to be created.
799 * Handle
800 * Handle to the newly created key
801 *
802 * Remarks
803 * This method can create nested trees, so parent of RegistryPath can
804 * be not existant, and will be created if needed.
805 */
806 NTSTATUS
807 NTAPI
808 IopCreateDeviceKeyPath(IN PCUNICODE_STRING RegistryPath,
809 IN ULONG CreateOptions,
810 OUT PHANDLE Handle)
811 {
812 UNICODE_STRING EnumU = RTL_CONSTANT_STRING(ENUM_ROOT);
813 HANDLE hParent = NULL, hKey;
814 OBJECT_ATTRIBUTES ObjectAttributes;
815 UNICODE_STRING KeyName;
816 LPCWSTR Current, Last;
817 ULONG dwLength;
818 NTSTATUS Status;
819
820 /* Assume failure */
821 *Handle = NULL;
822
823 /* Open root key for device instances */
824 Status = IopOpenRegistryKeyEx(&hParent, NULL, &EnumU, KEY_CREATE_SUB_KEY);
825 if (!NT_SUCCESS(Status))
826 {
827 DPRINT1("ZwOpenKey('%wZ') failed with status 0x%08lx\n", &EnumU, Status);
828 return Status;
829 }
830
831 Current = KeyName.Buffer = RegistryPath->Buffer;
832 Last = &RegistryPath->Buffer[RegistryPath->Length / sizeof(WCHAR)];
833
834 /* Go up to the end of the string */
835 while (Current <= Last)
836 {
837 if (Current != Last && *Current != '\\')
838 {
839 /* Not the end of the string and not a separator */
840 Current++;
841 continue;
842 }
843
844 /* Prepare relative key name */
845 dwLength = (ULONG_PTR)Current - (ULONG_PTR)KeyName.Buffer;
846 KeyName.MaximumLength = KeyName.Length = dwLength;
847 DPRINT("Create '%wZ'\n", &KeyName);
848
849 /* Open key */
850 InitializeObjectAttributes(&ObjectAttributes,
851 &KeyName,
852 OBJ_CASE_INSENSITIVE,
853 hParent,
854 NULL);
855 Status = ZwCreateKey(&hKey,
856 Current == Last ? KEY_ALL_ACCESS : KEY_CREATE_SUB_KEY,
857 &ObjectAttributes,
858 0,
859 NULL,
860 CreateOptions,
861 NULL);
862
863 /* Close parent key handle, we don't need it anymore */
864 if (hParent)
865 ZwClose(hParent);
866
867 /* Key opening/creating failed? */
868 if (!NT_SUCCESS(Status))
869 {
870 DPRINT1("ZwCreateKey('%wZ') failed with status 0x%08lx\n", &KeyName, Status);
871 return Status;
872 }
873
874 /* Check if it is the end of the string */
875 if (Current == Last)
876 {
877 /* Yes, return success */
878 *Handle = hKey;
879 return STATUS_SUCCESS;
880 }
881
882 /* Start with this new parent key */
883 hParent = hKey;
884 Current++;
885 KeyName.Buffer = (LPWSTR)Current;
886 }
887
888 return STATUS_UNSUCCESSFUL;
889 }
890
891 NTSTATUS
892 IopSetDeviceInstanceData(HANDLE InstanceKey,
893 PDEVICE_NODE DeviceNode)
894 {
895 OBJECT_ATTRIBUTES ObjectAttributes;
896 UNICODE_STRING KeyName;
897 HANDLE LogConfKey;
898 ULONG ResCount;
899 ULONG ResultLength;
900 NTSTATUS Status;
901 HANDLE ControlHandle;
902
903 DPRINT("IopSetDeviceInstanceData() called\n");
904
905 /* Create the 'LogConf' key */
906 RtlInitUnicodeString(&KeyName, L"LogConf");
907 InitializeObjectAttributes(&ObjectAttributes,
908 &KeyName,
909 OBJ_CASE_INSENSITIVE,
910 InstanceKey,
911 NULL);
912 Status = ZwCreateKey(&LogConfKey,
913 KEY_ALL_ACCESS,
914 &ObjectAttributes,
915 0,
916 NULL,
917 0,
918 NULL);
919 if (NT_SUCCESS(Status))
920 {
921 /* Set 'BootConfig' value */
922 if (DeviceNode->BootResources != NULL)
923 {
924 ResCount = DeviceNode->BootResources->Count;
925 if (ResCount != 0)
926 {
927 RtlInitUnicodeString(&KeyName, L"BootConfig");
928 Status = ZwSetValueKey(LogConfKey,
929 &KeyName,
930 0,
931 REG_RESOURCE_LIST,
932 DeviceNode->BootResources,
933 IopCalculateResourceListSize(DeviceNode->BootResources));
934 }
935 }
936
937 /* Set 'BasicConfigVector' value */
938 if (DeviceNode->ResourceRequirements != NULL &&
939 DeviceNode->ResourceRequirements->ListSize != 0)
940 {
941 RtlInitUnicodeString(&KeyName, L"BasicConfigVector");
942 Status = ZwSetValueKey(LogConfKey,
943 &KeyName,
944 0,
945 REG_RESOURCE_REQUIREMENTS_LIST,
946 DeviceNode->ResourceRequirements,
947 DeviceNode->ResourceRequirements->ListSize);
948 }
949
950 ZwClose(LogConfKey);
951 }
952
953 /* Set the 'ConfigFlags' value */
954 RtlInitUnicodeString(&KeyName, L"ConfigFlags");
955 Status = ZwQueryValueKey(InstanceKey,
956 &KeyName,
957 KeyValueBasicInformation,
958 NULL,
959 0,
960 &ResultLength);
961 if (Status == STATUS_OBJECT_NAME_NOT_FOUND)
962 {
963 /* Write the default value */
964 ULONG DefaultConfigFlags = 0;
965 Status = ZwSetValueKey(InstanceKey,
966 &KeyName,
967 0,
968 REG_DWORD,
969 &DefaultConfigFlags,
970 sizeof(DefaultConfigFlags));
971 }
972
973 /* Create the 'Control' key */
974 RtlInitUnicodeString(&KeyName, L"Control");
975 InitializeObjectAttributes(&ObjectAttributes,
976 &KeyName,
977 OBJ_CASE_INSENSITIVE,
978 InstanceKey,
979 NULL);
980 Status = ZwCreateKey(&ControlHandle, 0, &ObjectAttributes, 0, NULL, REG_OPTION_VOLATILE, NULL);
981
982 if (NT_SUCCESS(Status))
983 ZwClose(ControlHandle);
984
985 DPRINT("IopSetDeviceInstanceData() done\n");
986
987 return Status;
988 }
989
990 /*
991 * IopGetParentIdPrefix
992 *
993 * Retrieve (or create) a string which identifies a device.
994 *
995 * Parameters
996 * DeviceNode
997 * Pointer to device node.
998 * ParentIdPrefix
999 * Pointer to the string where is returned the parent node identifier
1000 *
1001 * Remarks
1002 * If the return code is STATUS_SUCCESS, the ParentIdPrefix string is
1003 * valid and its Buffer field is NULL-terminated. The caller needs to
1004 * to free the string with RtlFreeUnicodeString when it is no longer
1005 * needed.
1006 */
1007
1008 NTSTATUS
1009 IopGetParentIdPrefix(PDEVICE_NODE DeviceNode,
1010 PUNICODE_STRING ParentIdPrefix)
1011 {
1012 ULONG KeyNameBufferLength;
1013 PKEY_VALUE_PARTIAL_INFORMATION ParentIdPrefixInformation = NULL;
1014 UNICODE_STRING KeyName;
1015 UNICODE_STRING KeyValue;
1016 UNICODE_STRING ValueName;
1017 HANDLE hKey = NULL;
1018 ULONG crc32;
1019 NTSTATUS Status;
1020
1021 /* HACK: As long as some devices have a NULL device
1022 * instance path, the following test is required :(
1023 */
1024 if (DeviceNode->Parent->InstancePath.Length == 0)
1025 {
1026 DPRINT1("Parent of %wZ has NULL Instance path, please report!\n",
1027 &DeviceNode->InstancePath);
1028 return STATUS_UNSUCCESSFUL;
1029 }
1030
1031 /* 1. Try to retrieve ParentIdPrefix from registry */
1032 KeyNameBufferLength = FIELD_OFFSET(KEY_VALUE_PARTIAL_INFORMATION, Data[0]) + MAX_PATH * sizeof(WCHAR);
1033 ParentIdPrefixInformation = ExAllocatePool(PagedPool, KeyNameBufferLength + sizeof(WCHAR));
1034 if (!ParentIdPrefixInformation)
1035 {
1036 Status = STATUS_INSUFFICIENT_RESOURCES;
1037 goto cleanup;
1038 }
1039
1040
1041 KeyName.Buffer = ExAllocatePool(PagedPool, (49 * sizeof(WCHAR)) + DeviceNode->Parent->InstancePath.Length);
1042 if (!KeyName.Buffer)
1043 {
1044 Status = STATUS_INSUFFICIENT_RESOURCES;
1045 goto cleanup;
1046 }
1047 KeyName.Length = 0;
1048 KeyName.MaximumLength = (49 * sizeof(WCHAR)) + DeviceNode->Parent->InstancePath.Length;
1049
1050 RtlAppendUnicodeToString(&KeyName, L"\\Registry\\Machine\\System\\CurrentControlSet\\Enum\\");
1051 RtlAppendUnicodeStringToString(&KeyName, &DeviceNode->Parent->InstancePath);
1052
1053 Status = IopOpenRegistryKeyEx(&hKey, NULL, &KeyName, KEY_QUERY_VALUE | KEY_SET_VALUE);
1054 if (!NT_SUCCESS(Status))
1055 goto cleanup;
1056 RtlInitUnicodeString(&ValueName, L"ParentIdPrefix");
1057 Status = ZwQueryValueKey(
1058 hKey, &ValueName,
1059 KeyValuePartialInformation, ParentIdPrefixInformation,
1060 KeyNameBufferLength, &KeyNameBufferLength);
1061 if (NT_SUCCESS(Status))
1062 {
1063 if (ParentIdPrefixInformation->Type != REG_SZ)
1064 Status = STATUS_UNSUCCESSFUL;
1065 else
1066 {
1067 KeyValue.Length = KeyValue.MaximumLength = (USHORT)ParentIdPrefixInformation->DataLength;
1068 KeyValue.Buffer = (PWSTR)ParentIdPrefixInformation->Data;
1069 }
1070 goto cleanup;
1071 }
1072 if (Status != STATUS_OBJECT_NAME_NOT_FOUND)
1073 {
1074 KeyValue.Length = KeyValue.MaximumLength = (USHORT)ParentIdPrefixInformation->DataLength;
1075 KeyValue.Buffer = (PWSTR)ParentIdPrefixInformation->Data;
1076 goto cleanup;
1077 }
1078
1079 /* 2. Create the ParentIdPrefix value */
1080 crc32 = RtlComputeCrc32(0,
1081 (PUCHAR)DeviceNode->Parent->InstancePath.Buffer,
1082 DeviceNode->Parent->InstancePath.Length);
1083
1084 swprintf((PWSTR)ParentIdPrefixInformation->Data, L"%lx&%lx", DeviceNode->Parent->Level, crc32);
1085 RtlInitUnicodeString(&KeyValue, (PWSTR)ParentIdPrefixInformation->Data);
1086
1087 /* 3. Try to write the ParentIdPrefix to registry */
1088 Status = ZwSetValueKey(hKey,
1089 &ValueName,
1090 0,
1091 REG_SZ,
1092 (PVOID)KeyValue.Buffer,
1093 (wcslen(KeyValue.Buffer) + 1) * sizeof(WCHAR));
1094
1095 cleanup:
1096 if (NT_SUCCESS(Status))
1097 {
1098 /* Duplicate the string to return it */
1099 Status = RtlDuplicateUnicodeString(RTL_DUPLICATE_UNICODE_STRING_NULL_TERMINATE, &KeyValue, ParentIdPrefix);
1100 }
1101 ExFreePool(ParentIdPrefixInformation);
1102 RtlFreeUnicodeString(&KeyName);
1103 if (hKey != NULL)
1104 ZwClose(hKey);
1105 return Status;
1106 }
1107
1108
1109 /*
1110 * IopActionInterrogateDeviceStack
1111 *
1112 * Retrieve information for all (direct) child nodes of a parent node.
1113 *
1114 * Parameters
1115 * DeviceNode
1116 * Pointer to device node.
1117 * Context
1118 * Pointer to parent node to retrieve child node information for.
1119 *
1120 * Remarks
1121 * We only return a status code indicating an error (STATUS_UNSUCCESSFUL)
1122 * when we reach a device node which is not a direct child of the device
1123 * node for which we retrieve information of child nodes for. Any errors
1124 * that occur is logged instead so that all child services have a chance
1125 * of being interrogated.
1126 */
1127
1128 NTSTATUS
1129 IopActionInterrogateDeviceStack(PDEVICE_NODE DeviceNode,
1130 PVOID Context)
1131 {
1132 IO_STATUS_BLOCK IoStatusBlock;
1133 PDEVICE_NODE ParentDeviceNode;
1134 WCHAR InstancePath[MAX_PATH];
1135 IO_STACK_LOCATION Stack;
1136 NTSTATUS Status;
1137 PWSTR Ptr;
1138 USHORT Length;
1139 USHORT TotalLength;
1140 ULONG RequiredLength;
1141 LCID LocaleId;
1142 HANDLE InstanceKey = NULL;
1143 UNICODE_STRING ValueName;
1144 UNICODE_STRING ParentIdPrefix = { 0, 0, NULL };
1145 DEVICE_CAPABILITIES DeviceCapabilities;
1146
1147 DPRINT("IopActionInterrogateDeviceStack(%p, %p)\n", DeviceNode, Context);
1148 DPRINT("PDO 0x%p\n", DeviceNode->PhysicalDeviceObject);
1149
1150 ParentDeviceNode = (PDEVICE_NODE)Context;
1151
1152 /*
1153 * We are called for the parent too, but we don't need to do special
1154 * handling for this node
1155 */
1156
1157 if (DeviceNode == ParentDeviceNode)
1158 {
1159 DPRINT("Success\n");
1160 return STATUS_SUCCESS;
1161 }
1162
1163 /*
1164 * Make sure this device node is a direct child of the parent device node
1165 * that is given as an argument
1166 */
1167
1168 if (DeviceNode->Parent != ParentDeviceNode)
1169 {
1170 /* Stop the traversal immediately and indicate successful operation */
1171 DPRINT("Stop\n");
1172 return STATUS_UNSUCCESSFUL;
1173 }
1174
1175 /* Get Locale ID */
1176 Status = ZwQueryDefaultLocale(FALSE, &LocaleId);
1177 if (!NT_SUCCESS(Status))
1178 {
1179 DPRINT("ZwQueryDefaultLocale() failed with status 0x%lx\n", Status);
1180 return Status;
1181 }
1182
1183 /*
1184 * FIXME: For critical errors, cleanup and disable device, but always
1185 * return STATUS_SUCCESS.
1186 */
1187
1188 DPRINT("Sending IRP_MN_QUERY_ID.BusQueryDeviceID to device stack\n");
1189
1190 Stack.Parameters.QueryId.IdType = BusQueryDeviceID;
1191 Status = IopInitiatePnpIrp(DeviceNode->PhysicalDeviceObject,
1192 &IoStatusBlock,
1193 IRP_MN_QUERY_ID,
1194 &Stack);
1195 if (NT_SUCCESS(Status))
1196 {
1197 /* Copy the device id string */
1198 wcscpy(InstancePath, (PWSTR)IoStatusBlock.Information);
1199
1200 /*
1201 * FIXME: Check for valid characters, if there is invalid characters
1202 * then bugcheck.
1203 */
1204 }
1205 else
1206 {
1207 DPRINT("IopInitiatePnpIrp() failed (Status %x)\n", Status);
1208 }
1209
1210 DPRINT("Sending IRP_MN_QUERY_CAPABILITIES to device stack\n");
1211
1212 Status = IopQueryDeviceCapabilities(DeviceNode, &DeviceCapabilities);
1213 if (!NT_SUCCESS(Status))
1214 {
1215 DPRINT("IopInitiatePnpIrp() failed (Status 0x%08lx)\n", Status);
1216 }
1217
1218 DeviceNode->CapabilityFlags = *(PULONG)((ULONG_PTR)&DeviceCapabilities + 4);
1219
1220 if (!DeviceCapabilities.UniqueID)
1221 {
1222 /* Device has not a unique ID. We need to prepend parent bus unique identifier */
1223 DPRINT("Instance ID is not unique\n");
1224 Status = IopGetParentIdPrefix(DeviceNode, &ParentIdPrefix);
1225 if (!NT_SUCCESS(Status))
1226 {
1227 DPRINT("IopGetParentIdPrefix() failed (Status 0x%08lx)\n", Status);
1228 }
1229 }
1230
1231 DPRINT("Sending IRP_MN_QUERY_ID.BusQueryInstanceID to device stack\n");
1232
1233 Stack.Parameters.QueryId.IdType = BusQueryInstanceID;
1234 Status = IopInitiatePnpIrp(DeviceNode->PhysicalDeviceObject,
1235 &IoStatusBlock,
1236 IRP_MN_QUERY_ID,
1237 &Stack);
1238 if (NT_SUCCESS(Status))
1239 {
1240 /* Append the instance id string */
1241 wcscat(InstancePath, L"\\");
1242 if (ParentIdPrefix.Length > 0)
1243 {
1244 /* Add information from parent bus device to InstancePath */
1245 wcscat(InstancePath, ParentIdPrefix.Buffer);
1246 if (IoStatusBlock.Information && *(PWSTR)IoStatusBlock.Information)
1247 wcscat(InstancePath, L"&");
1248 }
1249 if (IoStatusBlock.Information)
1250 wcscat(InstancePath, (PWSTR)IoStatusBlock.Information);
1251
1252 /*
1253 * FIXME: Check for valid characters, if there is invalid characters
1254 * then bugcheck
1255 */
1256 }
1257 else
1258 {
1259 DPRINT("IopInitiatePnpIrp() failed (Status %x)\n", Status);
1260 }
1261 RtlFreeUnicodeString(&ParentIdPrefix);
1262
1263 if (!RtlCreateUnicodeString(&DeviceNode->InstancePath, InstancePath))
1264 {
1265 DPRINT("No resources\n");
1266 /* FIXME: Cleanup and disable device */
1267 }
1268
1269 DPRINT("InstancePath is %S\n", DeviceNode->InstancePath.Buffer);
1270
1271 /*
1272 * Create registry key for the instance id, if it doesn't exist yet
1273 */
1274 Status = IopCreateDeviceKeyPath(&DeviceNode->InstancePath, 0, &InstanceKey);
1275 if (!NT_SUCCESS(Status))
1276 {
1277 DPRINT1("Failed to create the instance key! (Status %lx)\n", Status);
1278 }
1279
1280 {
1281 /* Set 'Capabilities' value */
1282 RtlInitUnicodeString(&ValueName, L"Capabilities");
1283 Status = ZwSetValueKey(InstanceKey,
1284 &ValueName,
1285 0,
1286 REG_DWORD,
1287 (PVOID)&DeviceNode->CapabilityFlags,
1288 sizeof(ULONG));
1289
1290 /* Set 'UINumber' value */
1291 if (DeviceCapabilities.UINumber != MAXULONG)
1292 {
1293 RtlInitUnicodeString(&ValueName, L"UINumber");
1294 Status = ZwSetValueKey(InstanceKey,
1295 &ValueName,
1296 0,
1297 REG_DWORD,
1298 &DeviceCapabilities.UINumber,
1299 sizeof(ULONG));
1300 }
1301 }
1302
1303 DPRINT("Sending IRP_MN_QUERY_ID.BusQueryHardwareIDs to device stack\n");
1304
1305 Stack.Parameters.QueryId.IdType = BusQueryHardwareIDs;
1306 Status = IopInitiatePnpIrp(DeviceNode->PhysicalDeviceObject,
1307 &IoStatusBlock,
1308 IRP_MN_QUERY_ID,
1309 &Stack);
1310 if (NT_SUCCESS(Status))
1311 {
1312 /*
1313 * FIXME: Check for valid characters, if there is invalid characters
1314 * then bugcheck.
1315 */
1316 TotalLength = 0;
1317 Ptr = (PWSTR)IoStatusBlock.Information;
1318 DPRINT("Hardware IDs:\n");
1319 while (*Ptr)
1320 {
1321 DPRINT(" %S\n", Ptr);
1322 Length = wcslen(Ptr) + 1;
1323
1324 Ptr += Length;
1325 TotalLength += Length;
1326 }
1327 DPRINT("TotalLength: %hu\n", TotalLength);
1328 DPRINT("\n");
1329
1330 RtlInitUnicodeString(&ValueName, L"HardwareID");
1331 Status = ZwSetValueKey(InstanceKey,
1332 &ValueName,
1333 0,
1334 REG_MULTI_SZ,
1335 (PVOID)IoStatusBlock.Information,
1336 (TotalLength + 1) * sizeof(WCHAR));
1337 if (!NT_SUCCESS(Status))
1338 {
1339 DPRINT1("ZwSetValueKey() failed (Status %lx)\n", Status);
1340 }
1341 }
1342 else
1343 {
1344 DPRINT("IopInitiatePnpIrp() failed (Status %x)\n", Status);
1345 }
1346
1347 DPRINT("Sending IRP_MN_QUERY_ID.BusQueryCompatibleIDs to device stack\n");
1348
1349 Stack.Parameters.QueryId.IdType = BusQueryCompatibleIDs;
1350 Status = IopInitiatePnpIrp(
1351 DeviceNode->PhysicalDeviceObject,
1352 &IoStatusBlock,
1353 IRP_MN_QUERY_ID,
1354 &Stack);
1355 if (NT_SUCCESS(Status) && IoStatusBlock.Information)
1356 {
1357 /*
1358 * FIXME: Check for valid characters, if there is invalid characters
1359 * then bugcheck.
1360 */
1361 TotalLength = 0;
1362 Ptr = (PWSTR)IoStatusBlock.Information;
1363 DPRINT("Compatible IDs:\n");
1364 while (*Ptr)
1365 {
1366 DPRINT(" %S\n", Ptr);
1367 Length = wcslen(Ptr) + 1;
1368
1369 Ptr += Length;
1370 TotalLength += Length;
1371 }
1372 DPRINT("TotalLength: %hu\n", TotalLength);
1373 DPRINT("\n");
1374
1375 RtlInitUnicodeString(&ValueName, L"CompatibleIDs");
1376 Status = ZwSetValueKey(InstanceKey,
1377 &ValueName,
1378 0,
1379 REG_MULTI_SZ,
1380 (PVOID)IoStatusBlock.Information,
1381 (TotalLength + 1) * sizeof(WCHAR));
1382 if (!NT_SUCCESS(Status))
1383 {
1384 DPRINT1("ZwSetValueKey() failed (Status %lx) or no Compatible ID returned\n", Status);
1385 }
1386 }
1387 else
1388 {
1389 DPRINT("IopInitiatePnpIrp() failed (Status %x)\n", Status);
1390 }
1391
1392 DPRINT("Sending IRP_MN_QUERY_DEVICE_TEXT.DeviceTextDescription to device stack\n");
1393
1394 Stack.Parameters.QueryDeviceText.DeviceTextType = DeviceTextDescription;
1395 Stack.Parameters.QueryDeviceText.LocaleId = LocaleId;
1396 Status = IopInitiatePnpIrp(
1397 DeviceNode->PhysicalDeviceObject,
1398 &IoStatusBlock,
1399 IRP_MN_QUERY_DEVICE_TEXT,
1400 &Stack);
1401 /* This key is mandatory, so even if the Irp fails, we still write it */
1402 RtlInitUnicodeString(&ValueName, L"DeviceDesc");
1403 if (ZwQueryValueKey(InstanceKey, &ValueName, KeyValueBasicInformation, NULL, 0, &RequiredLength) == STATUS_OBJECT_NAME_NOT_FOUND)
1404 {
1405 if (NT_SUCCESS(Status) &&
1406 IoStatusBlock.Information &&
1407 (*(PWSTR)IoStatusBlock.Information != 0))
1408 {
1409 /* This key is overriden when a driver is installed. Don't write the
1410 * new description if another one already exists */
1411 Status = ZwSetValueKey(InstanceKey,
1412 &ValueName,
1413 0,
1414 REG_SZ,
1415 (PVOID)IoStatusBlock.Information,
1416 (wcslen((PWSTR)IoStatusBlock.Information) + 1) * sizeof(WCHAR));
1417 }
1418 else
1419 {
1420 UNICODE_STRING DeviceDesc = RTL_CONSTANT_STRING(L"Unknown device");
1421 DPRINT("Driver didn't return DeviceDesc (Status 0x%08lx), so place unknown device there\n", Status);
1422
1423 Status = ZwSetValueKey(InstanceKey,
1424 &ValueName,
1425 0,
1426 REG_SZ,
1427 DeviceDesc.Buffer,
1428 DeviceDesc.MaximumLength);
1429
1430 if (!NT_SUCCESS(Status))
1431 {
1432 DPRINT1("ZwSetValueKey() failed (Status 0x%lx)\n", Status);
1433 }
1434
1435 }
1436 }
1437
1438 DPRINT("Sending IRP_MN_QUERY_DEVICE_TEXT.DeviceTextLocation to device stack\n");
1439
1440 Stack.Parameters.QueryDeviceText.DeviceTextType = DeviceTextLocationInformation;
1441 Stack.Parameters.QueryDeviceText.LocaleId = LocaleId;
1442 Status = IopInitiatePnpIrp(
1443 DeviceNode->PhysicalDeviceObject,
1444 &IoStatusBlock,
1445 IRP_MN_QUERY_DEVICE_TEXT,
1446 &Stack);
1447 if (NT_SUCCESS(Status) && IoStatusBlock.Information)
1448 {
1449 DPRINT("LocationInformation: %S\n", (PWSTR)IoStatusBlock.Information);
1450 RtlInitUnicodeString(&ValueName, L"LocationInformation");
1451 Status = ZwSetValueKey(InstanceKey,
1452 &ValueName,
1453 0,
1454 REG_SZ,
1455 (PVOID)IoStatusBlock.Information,
1456 (wcslen((PWSTR)IoStatusBlock.Information) + 1) * sizeof(WCHAR));
1457 if (!NT_SUCCESS(Status))
1458 {
1459 DPRINT1("ZwSetValueKey() failed (Status %lx)\n", Status);
1460 }
1461 }
1462 else
1463 {
1464 DPRINT("IopInitiatePnpIrp() failed (Status %x) or IoStatusBlock.Information=NULL\n", Status);
1465 }
1466
1467 DPRINT("Sending IRP_MN_QUERY_BUS_INFORMATION to device stack\n");
1468
1469 Status = IopInitiatePnpIrp(
1470 DeviceNode->PhysicalDeviceObject,
1471 &IoStatusBlock,
1472 IRP_MN_QUERY_BUS_INFORMATION,
1473 NULL);
1474 if (NT_SUCCESS(Status) && IoStatusBlock.Information)
1475 {
1476 PPNP_BUS_INFORMATION BusInformation =
1477 (PPNP_BUS_INFORMATION)IoStatusBlock.Information;
1478
1479 DeviceNode->ChildBusNumber = BusInformation->BusNumber;
1480 DeviceNode->ChildInterfaceType = BusInformation->LegacyBusType;
1481 DeviceNode->ChildBusTypeIndex = IopGetBusTypeGuidIndex(&BusInformation->BusTypeGuid);
1482 ExFreePool(BusInformation);
1483 }
1484 else
1485 {
1486 DPRINT("IopInitiatePnpIrp() failed (Status %x) or IoStatusBlock.Information=NULL\n", Status);
1487
1488 DeviceNode->ChildBusNumber = 0xFFFFFFF0;
1489 DeviceNode->ChildInterfaceType = InterfaceTypeUndefined;
1490 DeviceNode->ChildBusTypeIndex = -1;
1491 }
1492
1493 DPRINT("Sending IRP_MN_QUERY_RESOURCES to device stack\n");
1494
1495 Status = IopInitiatePnpIrp(
1496 DeviceNode->PhysicalDeviceObject,
1497 &IoStatusBlock,
1498 IRP_MN_QUERY_RESOURCES,
1499 NULL);
1500 if (NT_SUCCESS(Status) && IoStatusBlock.Information)
1501 {
1502 DeviceNode->BootResources =
1503 (PCM_RESOURCE_LIST)IoStatusBlock.Information;
1504 IopDeviceNodeSetFlag(DeviceNode, DNF_HAS_BOOT_CONFIG);
1505 }
1506 else
1507 {
1508 DPRINT("IopInitiatePnpIrp() failed (Status %x) or IoStatusBlock.Information=NULL\n", Status);
1509 DeviceNode->BootResources = NULL;
1510 }
1511
1512 DPRINT("Sending IRP_MN_QUERY_RESOURCE_REQUIREMENTS to device stack\n");
1513
1514 Status = IopInitiatePnpIrp(
1515 DeviceNode->PhysicalDeviceObject,
1516 &IoStatusBlock,
1517 IRP_MN_QUERY_RESOURCE_REQUIREMENTS,
1518 NULL);
1519 if (NT_SUCCESS(Status))
1520 {
1521 DeviceNode->ResourceRequirements =
1522 (PIO_RESOURCE_REQUIREMENTS_LIST)IoStatusBlock.Information;
1523 }
1524 else
1525 {
1526 DPRINT("IopInitiatePnpIrp() failed (Status %08lx)\n", Status);
1527 DeviceNode->ResourceRequirements = NULL;
1528 }
1529
1530 if (InstanceKey != NULL)
1531 {
1532 IopSetDeviceInstanceData(InstanceKey, DeviceNode);
1533 }
1534
1535 ZwClose(InstanceKey);
1536
1537 IopDeviceNodeSetFlag(DeviceNode, DNF_PROCESSED);
1538
1539 if (!IopDeviceNodeHasFlag(DeviceNode, DNF_LEGACY_DRIVER))
1540 {
1541 /* Report the device to the user-mode pnp manager */
1542 IopQueueTargetDeviceEvent(&GUID_DEVICE_ENUMERATED,
1543 &DeviceNode->InstancePath);
1544 }
1545
1546 return STATUS_SUCCESS;
1547 }
1548
1549
1550 NTSTATUS
1551 IopEnumerateDevice(
1552 IN PDEVICE_OBJECT DeviceObject)
1553 {
1554 PDEVICE_NODE DeviceNode = IopGetDeviceNode(DeviceObject);
1555 DEVICETREE_TRAVERSE_CONTEXT Context;
1556 PDEVICE_RELATIONS DeviceRelations;
1557 PDEVICE_OBJECT ChildDeviceObject;
1558 IO_STATUS_BLOCK IoStatusBlock;
1559 PDEVICE_NODE ChildDeviceNode;
1560 IO_STACK_LOCATION Stack;
1561 NTSTATUS Status;
1562 ULONG i;
1563
1564 DPRINT("DeviceObject 0x%p\n", DeviceObject);
1565
1566 DPRINT("Sending GUID_DEVICE_ARRIVAL\n");
1567
1568 /* Report the device to the user-mode pnp manager */
1569 IopQueueTargetDeviceEvent(&GUID_DEVICE_ARRIVAL,
1570 &DeviceNode->InstancePath);
1571
1572 DPRINT("Sending IRP_MN_QUERY_DEVICE_RELATIONS to device stack\n");
1573
1574 Stack.Parameters.QueryDeviceRelations.Type = BusRelations;
1575
1576 Status = IopInitiatePnpIrp(
1577 DeviceObject,
1578 &IoStatusBlock,
1579 IRP_MN_QUERY_DEVICE_RELATIONS,
1580 &Stack);
1581 if (!NT_SUCCESS(Status) || Status == STATUS_PENDING)
1582 {
1583 DPRINT("IopInitiatePnpIrp() failed with status 0x%08lx\n", Status);
1584 return Status;
1585 }
1586
1587 DeviceRelations = (PDEVICE_RELATIONS)IoStatusBlock.Information;
1588
1589 if (!DeviceRelations)
1590 {
1591 DPRINT("No PDOs\n");
1592 return STATUS_UNSUCCESSFUL;
1593 }
1594
1595 DPRINT("Got %u PDOs\n", DeviceRelations->Count);
1596
1597 /*
1598 * Create device nodes for all discovered devices
1599 */
1600 for (i = 0; i < DeviceRelations->Count; i++)
1601 {
1602 ChildDeviceObject = DeviceRelations->Objects[i];
1603 ASSERT((ChildDeviceObject->Flags & DO_DEVICE_INITIALIZING) == 0);
1604
1605 ChildDeviceNode = IopGetDeviceNode(ChildDeviceObject);
1606 if (!ChildDeviceNode)
1607 {
1608 /* One doesn't exist, create it */
1609 Status = IopCreateDeviceNode(
1610 DeviceNode,
1611 ChildDeviceObject,
1612 NULL,
1613 &ChildDeviceNode);
1614 if (NT_SUCCESS(Status))
1615 {
1616 /* Mark the node as enumerated */
1617 ChildDeviceNode->Flags |= DNF_ENUMERATED;
1618
1619 /* Mark the DO as bus enumerated */
1620 ChildDeviceObject->Flags |= DO_BUS_ENUMERATED_DEVICE;
1621 }
1622 else
1623 {
1624 /* Ignore this DO */
1625 DPRINT1("IopCreateDeviceNode() failed with status 0x%08x. Skipping PDO %u\n", Status, i);
1626 ObDereferenceObject(ChildDeviceNode);
1627 }
1628 }
1629 else
1630 {
1631 /* Mark it as enumerated */
1632 ChildDeviceNode->Flags |= DNF_ENUMERATED;
1633 ObDereferenceObject(ChildDeviceObject);
1634 }
1635 }
1636 ExFreePool(DeviceRelations);
1637
1638 /*
1639 * Retrieve information about all discovered children from the bus driver
1640 */
1641 IopInitDeviceTreeTraverseContext(
1642 &Context,
1643 DeviceNode,
1644 IopActionInterrogateDeviceStack,
1645 DeviceNode);
1646
1647 Status = IopTraverseDeviceTree(&Context);
1648 if (!NT_SUCCESS(Status))
1649 {
1650 DPRINT("IopTraverseDeviceTree() failed with status 0x%08lx\n", Status);
1651 return Status;
1652 }
1653
1654 /*
1655 * Retrieve configuration from the registry for discovered children
1656 */
1657 IopInitDeviceTreeTraverseContext(
1658 &Context,
1659 DeviceNode,
1660 IopActionConfigureChildServices,
1661 DeviceNode);
1662
1663 Status = IopTraverseDeviceTree(&Context);
1664 if (!NT_SUCCESS(Status))
1665 {
1666 DPRINT("IopTraverseDeviceTree() failed with status 0x%08lx\n", Status);
1667 return Status;
1668 }
1669
1670 /*
1671 * Initialize services for discovered children.
1672 */
1673 Status = IopInitializePnpServices(DeviceNode);
1674 if (!NT_SUCCESS(Status))
1675 {
1676 DPRINT("IopInitializePnpServices() failed with status 0x%08lx\n", Status);
1677 return Status;
1678 }
1679
1680 DPRINT("IopEnumerateDevice() finished\n");
1681 return STATUS_SUCCESS;
1682 }
1683
1684
1685 /*
1686 * IopActionConfigureChildServices
1687 *
1688 * Retrieve configuration for all (direct) child nodes of a parent node.
1689 *
1690 * Parameters
1691 * DeviceNode
1692 * Pointer to device node.
1693 * Context
1694 * Pointer to parent node to retrieve child node configuration for.
1695 *
1696 * Remarks
1697 * We only return a status code indicating an error (STATUS_UNSUCCESSFUL)
1698 * when we reach a device node which is not a direct child of the device
1699 * node for which we configure child services for. Any errors that occur is
1700 * logged instead so that all child services have a chance of beeing
1701 * configured.
1702 */
1703
1704 NTSTATUS
1705 IopActionConfigureChildServices(PDEVICE_NODE DeviceNode,
1706 PVOID Context)
1707 {
1708 RTL_QUERY_REGISTRY_TABLE QueryTable[3];
1709 PDEVICE_NODE ParentDeviceNode;
1710 PUNICODE_STRING Service;
1711 UNICODE_STRING ClassGUID;
1712 NTSTATUS Status;
1713 DEVICE_CAPABILITIES DeviceCaps;
1714
1715 DPRINT("IopActionConfigureChildServices(%p, %p)\n", DeviceNode, Context);
1716
1717 ParentDeviceNode = (PDEVICE_NODE)Context;
1718
1719 /*
1720 * We are called for the parent too, but we don't need to do special
1721 * handling for this node
1722 */
1723 if (DeviceNode == ParentDeviceNode)
1724 {
1725 DPRINT("Success\n");
1726 return STATUS_SUCCESS;
1727 }
1728
1729 /*
1730 * Make sure this device node is a direct child of the parent device node
1731 * that is given as an argument
1732 */
1733 if (DeviceNode->Parent != ParentDeviceNode)
1734 {
1735 /* Stop the traversal immediately and indicate successful operation */
1736 DPRINT("Stop\n");
1737 return STATUS_UNSUCCESSFUL;
1738 }
1739
1740 if (!IopDeviceNodeHasFlag(DeviceNode, DNF_DISABLED))
1741 {
1742 WCHAR RegKeyBuffer[MAX_PATH];
1743 UNICODE_STRING RegKey;
1744
1745 RegKey.Length = 0;
1746 RegKey.MaximumLength = sizeof(RegKeyBuffer);
1747 RegKey.Buffer = RegKeyBuffer;
1748
1749 /*
1750 * Retrieve configuration from Enum key
1751 */
1752
1753 Service = &DeviceNode->ServiceName;
1754
1755 RtlZeroMemory(QueryTable, sizeof(QueryTable));
1756 RtlInitUnicodeString(Service, NULL);
1757 RtlInitUnicodeString(&ClassGUID, NULL);
1758
1759 QueryTable[0].Name = L"Service";
1760 QueryTable[0].Flags = RTL_QUERY_REGISTRY_DIRECT;
1761 QueryTable[0].EntryContext = Service;
1762
1763 QueryTable[1].Name = L"ClassGUID";
1764 QueryTable[1].Flags = RTL_QUERY_REGISTRY_DIRECT;
1765 QueryTable[1].EntryContext = &ClassGUID;
1766 QueryTable[1].DefaultType = REG_SZ;
1767 QueryTable[1].DefaultData = L"";
1768 QueryTable[1].DefaultLength = 0;
1769
1770 RtlAppendUnicodeToString(&RegKey, L"\\Registry\\Machine\\System\\CurrentControlSet\\Enum\\");
1771 RtlAppendUnicodeStringToString(&RegKey, &DeviceNode->InstancePath);
1772
1773 Status = RtlQueryRegistryValues(RTL_REGISTRY_ABSOLUTE,
1774 RegKey.Buffer, QueryTable, NULL, NULL);
1775
1776 if (!NT_SUCCESS(Status))
1777 {
1778 /* FIXME: Log the error */
1779 DPRINT("Could not retrieve configuration for device %wZ (Status 0x%08x)\n",
1780 &DeviceNode->InstancePath, Status);
1781 IopDeviceNodeSetFlag(DeviceNode, DNF_DISABLED);
1782 return STATUS_SUCCESS;
1783 }
1784
1785 if (Service->Buffer == NULL)
1786 {
1787 if (NT_SUCCESS(IopQueryDeviceCapabilities(DeviceNode, &DeviceCaps)) &&
1788 DeviceCaps.RawDeviceOK)
1789 {
1790 DPRINT1("%wZ is using parent bus driver (%wZ)\n", &DeviceNode->InstancePath, &ParentDeviceNode->ServiceName);
1791
1792 DeviceNode->ServiceName.Length = 0;
1793 DeviceNode->ServiceName.MaximumLength = 0;
1794 DeviceNode->ServiceName.Buffer = NULL;
1795 }
1796 else if (ClassGUID.Length != 0)
1797 {
1798 /* Device has a ClassGUID value, but no Service value.
1799 * Suppose it is using the NULL driver, so state the
1800 * device is started */
1801 DPRINT1("%wZ is using NULL driver\n", &DeviceNode->InstancePath);
1802 IopDeviceNodeSetFlag(DeviceNode, DNF_STARTED);
1803 }
1804 else
1805 {
1806 IopDeviceNodeSetFlag(DeviceNode, DNF_DISABLED);
1807 }
1808 return STATUS_SUCCESS;
1809 }
1810
1811 DPRINT("Got Service %S\n", Service->Buffer);
1812 }
1813
1814 return STATUS_SUCCESS;
1815 }
1816
1817 /*
1818 * IopActionInitChildServices
1819 *
1820 * Initialize the service for all (direct) child nodes of a parent node
1821 *
1822 * Parameters
1823 * DeviceNode
1824 * Pointer to device node.
1825 * Context
1826 * Pointer to parent node to initialize child node services for.
1827 *
1828 * Remarks
1829 * If the driver image for a service is not loaded and initialized
1830 * it is done here too. We only return a status code indicating an
1831 * error (STATUS_UNSUCCESSFUL) when we reach a device node which is
1832 * not a direct child of the device node for which we initialize
1833 * child services for. Any errors that occur is logged instead so
1834 * that all child services have a chance of being initialized.
1835 */
1836
1837 NTSTATUS
1838 IopActionInitChildServices(PDEVICE_NODE DeviceNode,
1839 PVOID Context)
1840 {
1841 PDEVICE_NODE ParentDeviceNode;
1842 NTSTATUS Status;
1843 BOOLEAN BootDrivers = !PnpSystemInit;
1844
1845 DPRINT("IopActionInitChildServices(%p, %p)\n", DeviceNode, Context);
1846
1847 ParentDeviceNode = (PDEVICE_NODE)Context;
1848
1849 /*
1850 * We are called for the parent too, but we don't need to do special
1851 * handling for this node
1852 */
1853 if (DeviceNode == ParentDeviceNode)
1854 {
1855 DPRINT("Success\n");
1856 return STATUS_SUCCESS;
1857 }
1858
1859 /*
1860 * Make sure this device node is a direct child of the parent device node
1861 * that is given as an argument
1862 */
1863 #if 0
1864 if (DeviceNode->Parent != ParentDeviceNode)
1865 {
1866 /*
1867 * Stop the traversal immediately and indicate unsuccessful operation
1868 */
1869 DPRINT("Stop\n");
1870 return STATUS_UNSUCCESSFUL;
1871 }
1872 #endif
1873 if (IopDeviceNodeHasFlag(DeviceNode, DNF_STARTED) ||
1874 IopDeviceNodeHasFlag(DeviceNode, DNF_ADDED) ||
1875 IopDeviceNodeHasFlag(DeviceNode, DNF_DISABLED))
1876 return STATUS_SUCCESS;
1877
1878 if (DeviceNode->ServiceName.Buffer == NULL)
1879 {
1880 /* We don't need to worry about loading the driver because we're
1881 * being driven in raw mode so our parent must be loaded to get here */
1882 Status = IopStartDevice(DeviceNode);
1883 if (!NT_SUCCESS(Status))
1884 {
1885 DPRINT1("IopStartDevice(%wZ) failed with status 0x%08x\n",
1886 &DeviceNode->InstancePath, Status);
1887 }
1888 }
1889 else
1890 {
1891 PLDR_DATA_TABLE_ENTRY ModuleObject;
1892 PDRIVER_OBJECT DriverObject;
1893
1894 /* Get existing DriverObject pointer (in case the driver has
1895 already been loaded and initialized) */
1896 Status = IopGetDriverObject(
1897 &DriverObject,
1898 &DeviceNode->ServiceName,
1899 FALSE);
1900
1901 if (!NT_SUCCESS(Status))
1902 {
1903 /* Driver is not initialized, try to load it */
1904 Status = IopLoadServiceModule(&DeviceNode->ServiceName, &ModuleObject);
1905
1906 if (NT_SUCCESS(Status) || Status == STATUS_IMAGE_ALREADY_LOADED)
1907 {
1908 /* STATUS_IMAGE_ALREADY_LOADED means this driver
1909 was loaded by the bootloader */
1910 if ((Status != STATUS_IMAGE_ALREADY_LOADED) ||
1911 (Status == STATUS_IMAGE_ALREADY_LOADED && !DriverObject))
1912 {
1913 /* Initialize the driver */
1914 Status = IopInitializeDriverModule(DeviceNode, ModuleObject,
1915 &DeviceNode->ServiceName, FALSE, &DriverObject);
1916 }
1917 else
1918 {
1919 Status = STATUS_SUCCESS;
1920 }
1921 }
1922 else
1923 {
1924 DPRINT1("IopLoadServiceModule(%wZ) failed with status 0x%08x\n",
1925 &DeviceNode->ServiceName, Status);
1926 }
1927 }
1928
1929 /* Driver is loaded and initialized at this point */
1930 if (NT_SUCCESS(Status))
1931 {
1932 /* Initialize the device, including all filters */
1933 Status = PipCallDriverAddDevice(DeviceNode, FALSE, DriverObject);
1934 }
1935 else
1936 {
1937 /*
1938 * Don't disable when trying to load only boot drivers
1939 */
1940 if (!BootDrivers)
1941 {
1942 IopDeviceNodeSetFlag(DeviceNode, DNF_DISABLED);
1943 IopDeviceNodeSetFlag(DeviceNode, DNF_START_FAILED);
1944 /* FIXME: Log the error (possibly in IopInitializeDeviceNodeService) */
1945 DPRINT1("Initialization of service %S failed (Status %x)\n",
1946 DeviceNode->ServiceName.Buffer, Status);
1947 }
1948 }
1949 }
1950
1951 return STATUS_SUCCESS;
1952 }
1953
1954 /*
1955 * IopInitializePnpServices
1956 *
1957 * Initialize services for discovered children
1958 *
1959 * Parameters
1960 * DeviceNode
1961 * Top device node to start initializing services.
1962 *
1963 * Return Value
1964 * Status
1965 */
1966 NTSTATUS
1967 IopInitializePnpServices(IN PDEVICE_NODE DeviceNode)
1968 {
1969 DEVICETREE_TRAVERSE_CONTEXT Context;
1970
1971 DPRINT("IopInitializePnpServices(%p)\n", DeviceNode);
1972
1973 IopInitDeviceTreeTraverseContext(
1974 &Context,
1975 DeviceNode,
1976 IopActionInitChildServices,
1977 DeviceNode);
1978
1979 return IopTraverseDeviceTree(&Context);
1980 }
1981
1982 static NTSTATUS INIT_FUNCTION
1983 IopEnumerateDetectedDevices(
1984 IN HANDLE hBaseKey,
1985 IN PUNICODE_STRING RelativePath OPTIONAL,
1986 IN HANDLE hRootKey,
1987 IN BOOLEAN EnumerateSubKeys,
1988 IN PCM_FULL_RESOURCE_DESCRIPTOR ParentBootResources,
1989 IN ULONG ParentBootResourcesLength)
1990 {
1991 UNICODE_STRING IdentifierU = RTL_CONSTANT_STRING(L"Identifier");
1992 UNICODE_STRING HardwareIDU = RTL_CONSTANT_STRING(L"HardwareID");
1993 UNICODE_STRING ConfigurationDataU = RTL_CONSTANT_STRING(L"Configuration Data");
1994 UNICODE_STRING BootConfigU = RTL_CONSTANT_STRING(L"BootConfig");
1995 UNICODE_STRING LogConfU = RTL_CONSTANT_STRING(L"LogConf");
1996 OBJECT_ATTRIBUTES ObjectAttributes;
1997 HANDLE hDevicesKey = NULL;
1998 HANDLE hDeviceKey = NULL;
1999 HANDLE hLevel1Key, hLevel2Key = NULL, hLogConf;
2000 UNICODE_STRING Level2NameU;
2001 WCHAR Level2Name[5];
2002 ULONG IndexDevice = 0;
2003 ULONG IndexSubKey;
2004 PKEY_BASIC_INFORMATION pDeviceInformation = NULL;
2005 ULONG DeviceInfoLength = sizeof(KEY_BASIC_INFORMATION) + 50 * sizeof(WCHAR);
2006 PKEY_VALUE_PARTIAL_INFORMATION pValueInformation = NULL;
2007 ULONG ValueInfoLength = sizeof(KEY_VALUE_PARTIAL_INFORMATION) + 50 * sizeof(WCHAR);
2008 UNICODE_STRING DeviceName, ValueName;
2009 ULONG RequiredSize;
2010 PCM_FULL_RESOURCE_DESCRIPTOR BootResources = NULL;
2011 ULONG BootResourcesLength;
2012 NTSTATUS Status;
2013
2014 const UNICODE_STRING IdentifierPci = RTL_CONSTANT_STRING(L"PCI");
2015 UNICODE_STRING HardwareIdPci = RTL_CONSTANT_STRING(L"*PNP0A03\0");
2016 static ULONG DeviceIndexPci = 0;
2017 const UNICODE_STRING IdentifierSerial = RTL_CONSTANT_STRING(L"SerialController");
2018 UNICODE_STRING HardwareIdSerial = RTL_CONSTANT_STRING(L"*PNP0501\0");
2019 static ULONG DeviceIndexSerial = 0;
2020 const UNICODE_STRING IdentifierKeyboard = RTL_CONSTANT_STRING(L"KeyboardController");
2021 UNICODE_STRING HardwareIdKeyboard = RTL_CONSTANT_STRING(L"*PNP0303\0");
2022 static ULONG DeviceIndexKeyboard = 0;
2023 const UNICODE_STRING IdentifierMouse = RTL_CONSTANT_STRING(L"PointerController");
2024 UNICODE_STRING HardwareIdMouse = RTL_CONSTANT_STRING(L"*PNP0F13\0");
2025 static ULONG DeviceIndexMouse = 0;
2026 const UNICODE_STRING IdentifierParallel = RTL_CONSTANT_STRING(L"ParallelController");
2027 UNICODE_STRING HardwareIdParallel = RTL_CONSTANT_STRING(L"*PNP0400\0");
2028 static ULONG DeviceIndexParallel = 0;
2029 const UNICODE_STRING IdentifierFloppy = RTL_CONSTANT_STRING(L"FloppyDiskPeripheral");
2030 UNICODE_STRING HardwareIdFloppy = RTL_CONSTANT_STRING(L"*PNP0700\0");
2031 static ULONG DeviceIndexFloppy = 0;
2032 const UNICODE_STRING IdentifierIsa = RTL_CONSTANT_STRING(L"ISA");
2033 UNICODE_STRING HardwareIdIsa = RTL_CONSTANT_STRING(L"*PNP0A00\0");
2034 static ULONG DeviceIndexIsa = 0;
2035 UNICODE_STRING HardwareIdKey;
2036 PUNICODE_STRING pHardwareId;
2037 ULONG DeviceIndex = 0;
2038 PUCHAR CmResourceList;
2039 ULONG ListCount;
2040
2041 if (RelativePath)
2042 {
2043 Status = IopOpenRegistryKeyEx(&hDevicesKey, hBaseKey, RelativePath, KEY_ENUMERATE_SUB_KEYS);
2044 if (!NT_SUCCESS(Status))
2045 {
2046 DPRINT("ZwOpenKey() failed with status 0x%08lx\n", Status);
2047 goto cleanup;
2048 }
2049 }
2050 else
2051 hDevicesKey = hBaseKey;
2052
2053 pDeviceInformation = ExAllocatePool(PagedPool, DeviceInfoLength);
2054 if (!pDeviceInformation)
2055 {
2056 DPRINT("ExAllocatePool() failed\n");
2057 Status = STATUS_NO_MEMORY;
2058 goto cleanup;
2059 }
2060
2061 pValueInformation = ExAllocatePool(PagedPool, ValueInfoLength);
2062 if (!pValueInformation)
2063 {
2064 DPRINT("ExAllocatePool() failed\n");
2065 Status = STATUS_NO_MEMORY;
2066 goto cleanup;
2067 }
2068
2069 while (TRUE)
2070 {
2071 Status = ZwEnumerateKey(hDevicesKey, IndexDevice, KeyBasicInformation, pDeviceInformation, DeviceInfoLength, &RequiredSize);
2072 if (Status == STATUS_NO_MORE_ENTRIES)
2073 break;
2074 else if (Status == STATUS_BUFFER_OVERFLOW || Status == STATUS_BUFFER_TOO_SMALL)
2075 {
2076 ExFreePool(pDeviceInformation);
2077 DeviceInfoLength = RequiredSize;
2078 pDeviceInformation = ExAllocatePool(PagedPool, DeviceInfoLength);
2079 if (!pDeviceInformation)
2080 {
2081 DPRINT("ExAllocatePool() failed\n");
2082 Status = STATUS_NO_MEMORY;
2083 goto cleanup;
2084 }
2085 Status = ZwEnumerateKey(hDevicesKey, IndexDevice, KeyBasicInformation, pDeviceInformation, DeviceInfoLength, &RequiredSize);
2086 }
2087 if (!NT_SUCCESS(Status))
2088 {
2089 DPRINT("ZwEnumerateKey() failed with status 0x%08lx\n", Status);
2090 goto cleanup;
2091 }
2092 IndexDevice++;
2093
2094 /* Open device key */
2095 DeviceName.Length = DeviceName.MaximumLength = (USHORT)pDeviceInformation->NameLength;
2096 DeviceName.Buffer = pDeviceInformation->Name;
2097
2098 Status = IopOpenRegistryKeyEx(&hDeviceKey, hDevicesKey, &DeviceName,
2099 KEY_QUERY_VALUE + (EnumerateSubKeys ? KEY_ENUMERATE_SUB_KEYS : 0));
2100 if (!NT_SUCCESS(Status))
2101 {
2102 DPRINT("ZwOpenKey() failed with status 0x%08lx\n", Status);
2103 goto cleanup;
2104 }
2105
2106 /* Read boot resources, and add then to parent ones */
2107 Status = ZwQueryValueKey(hDeviceKey, &ConfigurationDataU, KeyValuePartialInformation, pValueInformation, ValueInfoLength, &RequiredSize);
2108 if (Status == STATUS_BUFFER_OVERFLOW || Status == STATUS_BUFFER_TOO_SMALL)
2109 {
2110 ExFreePool(pValueInformation);
2111 ValueInfoLength = RequiredSize;
2112 pValueInformation = ExAllocatePool(PagedPool, ValueInfoLength);
2113 if (!pValueInformation)
2114 {
2115 DPRINT("ExAllocatePool() failed\n");
2116 ZwDeleteKey(hLevel2Key);
2117 Status = STATUS_NO_MEMORY;
2118 goto cleanup;
2119 }
2120 Status = ZwQueryValueKey(hDeviceKey, &ConfigurationDataU, KeyValuePartialInformation, pValueInformation, ValueInfoLength, &RequiredSize);
2121 }
2122 if (Status == STATUS_OBJECT_NAME_NOT_FOUND)
2123 {
2124 BootResources = ParentBootResources;
2125 BootResourcesLength = ParentBootResourcesLength;
2126 }
2127 else if (!NT_SUCCESS(Status))
2128 {
2129 DPRINT("ZwQueryValueKey() failed with status 0x%08lx\n", Status);
2130 goto nextdevice;
2131 }
2132 else if (pValueInformation->Type != REG_FULL_RESOURCE_DESCRIPTOR)
2133 {
2134 DPRINT("Wrong registry type: got 0x%lx, expected 0x%lx\n", pValueInformation->Type, REG_FULL_RESOURCE_DESCRIPTOR);
2135 goto nextdevice;
2136 }
2137 else
2138 {
2139 static const ULONG Header = FIELD_OFFSET(CM_FULL_RESOURCE_DESCRIPTOR, PartialResourceList.PartialDescriptors);
2140
2141 /* Concatenate current resources and parent ones */
2142 if (ParentBootResourcesLength == 0)
2143 BootResourcesLength = pValueInformation->DataLength;
2144 else
2145 BootResourcesLength = ParentBootResourcesLength
2146 + pValueInformation->DataLength
2147 - Header;
2148 BootResources = ExAllocatePool(PagedPool, BootResourcesLength);
2149 if (!BootResources)
2150 {
2151 DPRINT("ExAllocatePool() failed\n");
2152 goto nextdevice;
2153 }
2154 if (ParentBootResourcesLength < sizeof(CM_FULL_RESOURCE_DESCRIPTOR))
2155 {
2156 RtlCopyMemory(BootResources, pValueInformation->Data, pValueInformation->DataLength);
2157 }
2158 else if (ParentBootResources->PartialResourceList.PartialDescriptors[ParentBootResources->PartialResourceList.Count - 1].Type == CmResourceTypeDeviceSpecific)
2159 {
2160 RtlCopyMemory(BootResources, pValueInformation->Data, pValueInformation->DataLength);
2161 RtlCopyMemory(
2162 (PVOID)((ULONG_PTR)BootResources + pValueInformation->DataLength),
2163 (PVOID)((ULONG_PTR)ParentBootResources + Header),
2164 ParentBootResourcesLength - Header);
2165 BootResources->PartialResourceList.Count += ParentBootResources->PartialResourceList.Count;
2166 }
2167 else
2168 {
2169 RtlCopyMemory(BootResources, pValueInformation->Data, Header);
2170 RtlCopyMemory(
2171 (PVOID)((ULONG_PTR)BootResources + Header),
2172 (PVOID)((ULONG_PTR)ParentBootResources + Header),
2173 ParentBootResourcesLength - Header);
2174 RtlCopyMemory(
2175 (PVOID)((ULONG_PTR)BootResources + ParentBootResourcesLength),
2176 pValueInformation->Data + Header,
2177 pValueInformation->DataLength - Header);
2178 BootResources->PartialResourceList.Count += ParentBootResources->PartialResourceList.Count;
2179 }
2180 }
2181
2182 if (EnumerateSubKeys)
2183 {
2184 IndexSubKey = 0;
2185 while (TRUE)
2186 {
2187 Status = ZwEnumerateKey(hDeviceKey, IndexSubKey, KeyBasicInformation, pDeviceInformation, DeviceInfoLength, &RequiredSize);
2188 if (Status == STATUS_NO_MORE_ENTRIES)
2189 break;
2190 else if (Status == STATUS_BUFFER_OVERFLOW || Status == STATUS_BUFFER_TOO_SMALL)
2191 {
2192 ExFreePool(pDeviceInformation);
2193 DeviceInfoLength = RequiredSize;
2194 pDeviceInformation = ExAllocatePool(PagedPool, DeviceInfoLength);
2195 if (!pDeviceInformation)
2196 {
2197 DPRINT("ExAllocatePool() failed\n");
2198 Status = STATUS_NO_MEMORY;
2199 goto cleanup;
2200 }
2201 Status = ZwEnumerateKey(hDeviceKey, IndexSubKey, KeyBasicInformation, pDeviceInformation, DeviceInfoLength, &RequiredSize);
2202 }
2203 if (!NT_SUCCESS(Status))
2204 {
2205 DPRINT("ZwEnumerateKey() failed with status 0x%08lx\n", Status);
2206 goto cleanup;
2207 }
2208 IndexSubKey++;
2209 DeviceName.Length = DeviceName.MaximumLength = (USHORT)pDeviceInformation->NameLength;
2210 DeviceName.Buffer = pDeviceInformation->Name;
2211
2212 Status = IopEnumerateDetectedDevices(
2213 hDeviceKey,
2214 &DeviceName,
2215 hRootKey,
2216 TRUE,
2217 BootResources,
2218 BootResourcesLength);
2219 if (!NT_SUCCESS(Status))
2220 goto cleanup;
2221 }
2222 }
2223
2224 /* Read identifier */
2225 Status = ZwQueryValueKey(hDeviceKey, &IdentifierU, KeyValuePartialInformation, pValueInformation, ValueInfoLength, &RequiredSize);
2226 if (Status == STATUS_BUFFER_OVERFLOW || Status == STATUS_BUFFER_TOO_SMALL)
2227 {
2228 ExFreePool(pValueInformation);
2229 ValueInfoLength = RequiredSize;
2230 pValueInformation = ExAllocatePool(PagedPool, ValueInfoLength);
2231 if (!pValueInformation)
2232 {
2233 DPRINT("ExAllocatePool() failed\n");
2234 Status = STATUS_NO_MEMORY;
2235 goto cleanup;
2236 }
2237 Status = ZwQueryValueKey(hDeviceKey, &IdentifierU, KeyValuePartialInformation, pValueInformation, ValueInfoLength, &RequiredSize);
2238 }
2239 if (!NT_SUCCESS(Status))
2240 {
2241 if (Status != STATUS_OBJECT_NAME_NOT_FOUND)
2242 {
2243 DPRINT("ZwQueryValueKey() failed with status 0x%08lx\n", Status);
2244 goto nextdevice;
2245 }
2246 ValueName.Length = ValueName.MaximumLength = 0;
2247 }
2248 else if (pValueInformation->Type != REG_SZ)
2249 {
2250 DPRINT("Wrong registry type: got 0x%lx, expected 0x%lx\n", pValueInformation->Type, REG_SZ);
2251 goto nextdevice;
2252 }
2253 else
2254 {
2255 /* Assign hardware id to this device */
2256 ValueName.Length = ValueName.MaximumLength = (USHORT)pValueInformation->DataLength;
2257 ValueName.Buffer = (PWCHAR)pValueInformation->Data;
2258 if (ValueName.Length >= sizeof(WCHAR) && ValueName.Buffer[ValueName.Length / sizeof(WCHAR) - 1] == UNICODE_NULL)
2259 ValueName.Length -= sizeof(WCHAR);
2260 }
2261
2262 if (RelativePath && RtlCompareUnicodeString(RelativePath, &IdentifierSerial, FALSE) == 0)
2263 {
2264 pHardwareId = &HardwareIdSerial;
2265 DeviceIndex = DeviceIndexSerial++;
2266 }
2267 else if (RelativePath && RtlCompareUnicodeString(RelativePath, &IdentifierKeyboard, FALSE) == 0)
2268 {
2269 pHardwareId = &HardwareIdKeyboard;
2270 DeviceIndex = DeviceIndexKeyboard++;
2271 }
2272 else if (RelativePath && RtlCompareUnicodeString(RelativePath, &IdentifierMouse, FALSE) == 0)
2273 {
2274 pHardwareId = &HardwareIdMouse;
2275 DeviceIndex = DeviceIndexMouse++;
2276 }
2277 else if (RelativePath && RtlCompareUnicodeString(RelativePath, &IdentifierParallel, FALSE) == 0)
2278 {
2279 pHardwareId = &HardwareIdParallel;
2280 DeviceIndex = DeviceIndexParallel++;
2281 }
2282 else if (RelativePath && RtlCompareUnicodeString(RelativePath, &IdentifierFloppy, FALSE) == 0)
2283 {
2284 pHardwareId = &HardwareIdFloppy;
2285 DeviceIndex = DeviceIndexFloppy++;
2286 }
2287 else if (NT_SUCCESS(Status))
2288 {
2289 /* Try to also match the device identifier */
2290 if (RtlCompareUnicodeString(&ValueName, &IdentifierPci, FALSE) == 0)
2291 {
2292 pHardwareId = &HardwareIdPci;
2293 DeviceIndex = DeviceIndexPci++;
2294 }
2295 else if (RtlCompareUnicodeString(&ValueName, &IdentifierIsa, FALSE) == 0)
2296 {
2297 pHardwareId = &HardwareIdIsa;
2298 DeviceIndex = DeviceIndexIsa++;
2299 }
2300 else
2301 {
2302 DPRINT("Unknown device '%wZ'\n", &ValueName);
2303 goto nextdevice;
2304 }
2305 }
2306 else
2307 {
2308 /* Unknown key path */
2309 DPRINT("Unknown key path '%wZ'\n", RelativePath);
2310 goto nextdevice;
2311 }
2312
2313 /* Prepare hardware id key (hardware id value without final \0) */
2314 HardwareIdKey = *pHardwareId;
2315 HardwareIdKey.Length -= sizeof(UNICODE_NULL);
2316
2317 /* Add the detected device to Root key */
2318 InitializeObjectAttributes(&ObjectAttributes, &HardwareIdKey, OBJ_KERNEL_HANDLE, hRootKey, NULL);
2319 Status = ZwCreateKey(
2320 &hLevel1Key,
2321 KEY_CREATE_SUB_KEY,
2322 &ObjectAttributes,
2323 0,
2324 NULL,
2325 REG_OPTION_NON_VOLATILE,
2326 NULL);
2327 if (!NT_SUCCESS(Status))
2328 {
2329 DPRINT("ZwCreateKey() failed with status 0x%08lx\n", Status);
2330 goto nextdevice;
2331 }
2332 swprintf(Level2Name, L"%04lu", DeviceIndex);
2333 RtlInitUnicodeString(&Level2NameU, Level2Name);
2334 InitializeObjectAttributes(&ObjectAttributes, &Level2NameU, OBJ_KERNEL_HANDLE, hLevel1Key, NULL);
2335 Status = ZwCreateKey(
2336 &hLevel2Key,
2337 KEY_SET_VALUE | KEY_CREATE_SUB_KEY,
2338 &ObjectAttributes,
2339 0,
2340 NULL,
2341 REG_OPTION_NON_VOLATILE,
2342 NULL);
2343 ZwClose(hLevel1Key);
2344 if (!NT_SUCCESS(Status))
2345 {
2346 DPRINT("ZwCreateKey() failed with status 0x%08lx\n", Status);
2347 goto nextdevice;
2348 }
2349 DPRINT("Found %wZ #%lu (%wZ)\n", &ValueName, DeviceIndex, &HardwareIdKey);
2350 Status = ZwSetValueKey(hLevel2Key, &HardwareIDU, 0, REG_MULTI_SZ, pHardwareId->Buffer, pHardwareId->MaximumLength);
2351 if (!NT_SUCCESS(Status))
2352 {
2353 DPRINT("ZwSetValueKey() failed with status 0x%08lx\n", Status);
2354 ZwDeleteKey(hLevel2Key);
2355 goto nextdevice;
2356 }
2357 /* Create 'LogConf' subkey */
2358 InitializeObjectAttributes(&ObjectAttributes, &LogConfU, OBJ_KERNEL_HANDLE, hLevel2Key, NULL);
2359 Status = ZwCreateKey(
2360 &hLogConf,
2361 KEY_SET_VALUE,
2362 &ObjectAttributes,
2363 0,
2364 NULL,
2365 REG_OPTION_VOLATILE,
2366 NULL);
2367 if (!NT_SUCCESS(Status))
2368 {
2369 DPRINT("ZwCreateKey() failed with status 0x%08lx\n", Status);
2370 ZwDeleteKey(hLevel2Key);
2371 goto nextdevice;
2372 }
2373 if (BootResourcesLength >= sizeof(CM_FULL_RESOURCE_DESCRIPTOR))
2374 {
2375 CmResourceList = ExAllocatePool(PagedPool, BootResourcesLength + sizeof(ULONG));
2376 if (!CmResourceList)
2377 {
2378 ZwClose(hLogConf);
2379 ZwDeleteKey(hLevel2Key);
2380 goto nextdevice;
2381 }
2382
2383 /* Add the list count (1st member of CM_RESOURCE_LIST) */
2384 ListCount = 1;
2385 RtlCopyMemory(CmResourceList,
2386 &ListCount,
2387 sizeof(ULONG));
2388
2389 /* Now add the actual list (2nd member of CM_RESOURCE_LIST) */
2390 RtlCopyMemory(CmResourceList + sizeof(ULONG),
2391 BootResources,
2392 BootResourcesLength);
2393
2394 /* Save boot resources to 'LogConf\BootConfig' */
2395 Status = ZwSetValueKey(hLogConf, &BootConfigU, 0, REG_RESOURCE_LIST, CmResourceList, BootResourcesLength + sizeof(ULONG));
2396 if (!NT_SUCCESS(Status))
2397 {
2398 DPRINT("ZwSetValueKey() failed with status 0x%08lx\n", Status);
2399 ZwClose(hLogConf);
2400 ZwDeleteKey(hLevel2Key);
2401 goto nextdevice;
2402 }
2403 }
2404 ZwClose(hLogConf);
2405
2406 nextdevice:
2407 if (BootResources && BootResources != ParentBootResources)
2408 {
2409 ExFreePool(BootResources);
2410 BootResources = NULL;
2411 }
2412 if (hLevel2Key)
2413 {
2414 ZwClose(hLevel2Key);
2415 hLevel2Key = NULL;
2416 }
2417 if (hDeviceKey)
2418 {
2419 ZwClose(hDeviceKey);
2420 hDeviceKey = NULL;
2421 }
2422 }
2423
2424 Status = STATUS_SUCCESS;
2425
2426 cleanup:
2427 if (hDevicesKey && hDevicesKey != hBaseKey)
2428 ZwClose(hDevicesKey);
2429 if (hDeviceKey)
2430 ZwClose(hDeviceKey);
2431 if (pDeviceInformation)
2432 ExFreePool(pDeviceInformation);
2433 if (pValueInformation)
2434 ExFreePool(pValueInformation);
2435 return Status;
2436 }
2437
2438 static BOOLEAN INIT_FUNCTION
2439 IopIsAcpiComputer(VOID)
2440 {
2441 #ifndef ENABLE_ACPI
2442 return FALSE;
2443 #else
2444 UNICODE_STRING MultiKeyPathU = RTL_CONSTANT_STRING(L"\\Registry\\Machine\\HARDWARE\\DESCRIPTION\\System\\MultifunctionAdapter");
2445 UNICODE_STRING IdentifierU = RTL_CONSTANT_STRING(L"Identifier");
2446 UNICODE_STRING AcpiBiosIdentifier = RTL_CONSTANT_STRING(L"ACPI BIOS");
2447 OBJECT_ATTRIBUTES ObjectAttributes;
2448 PKEY_BASIC_INFORMATION pDeviceInformation = NULL;
2449 ULONG DeviceInfoLength = sizeof(KEY_BASIC_INFORMATION) + 50 * sizeof(WCHAR);
2450 PKEY_VALUE_PARTIAL_INFORMATION pValueInformation = NULL;
2451 ULONG ValueInfoLength = sizeof(KEY_VALUE_PARTIAL_INFORMATION) + 50 * sizeof(WCHAR);
2452 ULONG RequiredSize;
2453 ULONG IndexDevice = 0;
2454 UNICODE_STRING DeviceName, ValueName;
2455 HANDLE hDevicesKey = NULL;
2456 HANDLE hDeviceKey = NULL;
2457 NTSTATUS Status;
2458 BOOLEAN ret = FALSE;
2459
2460 InitializeObjectAttributes(&ObjectAttributes, &MultiKeyPathU, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, NULL, NULL);
2461 Status = ZwOpenKey(&hDevicesKey, KEY_ENUMERATE_SUB_KEYS, &ObjectAttributes);
2462 if (!NT_SUCCESS(Status))
2463 {
2464 DPRINT("ZwOpenKey() failed with status 0x%08lx\n", Status);
2465 goto cleanup;
2466 }
2467
2468 pDeviceInformation = ExAllocatePool(PagedPool, DeviceInfoLength);
2469 if (!pDeviceInformation)
2470 {
2471 DPRINT("ExAllocatePool() failed\n");
2472 Status = STATUS_NO_MEMORY;
2473 goto cleanup;
2474 }
2475
2476 pValueInformation = ExAllocatePool(PagedPool, ValueInfoLength);
2477 if (!pDeviceInformation)
2478 {
2479 DPRINT("ExAllocatePool() failed\n");
2480 Status = STATUS_NO_MEMORY;
2481 goto cleanup;
2482 }
2483
2484 while (TRUE)
2485 {
2486 Status = ZwEnumerateKey(hDevicesKey, IndexDevice, KeyBasicInformation, pDeviceInformation, DeviceInfoLength, &RequiredSize);
2487 if (Status == STATUS_NO_MORE_ENTRIES)
2488 break;
2489 else if (Status == STATUS_BUFFER_OVERFLOW || Status == STATUS_BUFFER_TOO_SMALL)
2490 {
2491 ExFreePool(pDeviceInformation);
2492 DeviceInfoLength = RequiredSize;
2493 pDeviceInformation = ExAllocatePool(PagedPool, DeviceInfoLength);
2494 if (!pDeviceInformation)
2495 {
2496 DPRINT("ExAllocatePool() failed\n");
2497 Status = STATUS_NO_MEMORY;
2498 goto cleanup;
2499 }
2500 Status = ZwEnumerateKey(hDevicesKey, IndexDevice, KeyBasicInformation, pDeviceInformation, DeviceInfoLength, &RequiredSize);
2501 }
2502 if (!NT_SUCCESS(Status))
2503 {
2504 DPRINT("ZwEnumerateKey() failed with status 0x%08lx\n", Status);
2505 goto cleanup;
2506 }
2507 IndexDevice++;
2508
2509 /* Open device key */
2510 DeviceName.Length = DeviceName.MaximumLength = pDeviceInformation->NameLength;
2511 DeviceName.Buffer = pDeviceInformation->Name;
2512 InitializeObjectAttributes(&ObjectAttributes, &DeviceName, OBJ_KERNEL_HANDLE, hDevicesKey, NULL);
2513 Status = ZwOpenKey(
2514 &hDeviceKey,
2515 KEY_QUERY_VALUE,
2516 &ObjectAttributes);
2517 if (!NT_SUCCESS(Status))
2518 {
2519 DPRINT("ZwOpenKey() failed with status 0x%08lx\n", Status);
2520 goto cleanup;
2521 }
2522
2523 /* Read identifier */
2524 Status = ZwQueryValueKey(hDeviceKey, &IdentifierU, KeyValuePartialInformation, pValueInformation, ValueInfoLength, &RequiredSize);
2525 if (Status == STATUS_BUFFER_OVERFLOW || Status == STATUS_BUFFER_TOO_SMALL)
2526 {
2527 ExFreePool(pValueInformation);
2528 ValueInfoLength = RequiredSize;
2529 pValueInformation = ExAllocatePool(PagedPool, ValueInfoLength);
2530 if (!pValueInformation)
2531 {
2532 DPRINT("ExAllocatePool() failed\n");
2533 Status = STATUS_NO_MEMORY;
2534 goto cleanup;
2535 }
2536 Status = ZwQueryValueKey(hDeviceKey, &IdentifierU, KeyValuePartialInformation, pValueInformation, ValueInfoLength, &RequiredSize);
2537 }
2538 if (!NT_SUCCESS(Status))
2539 {
2540 DPRINT("ZwQueryValueKey() failed with status 0x%08lx\n", Status);
2541 goto nextdevice;
2542 }
2543 else if (pValueInformation->Type != REG_SZ)
2544 {
2545 DPRINT("Wrong registry type: got 0x%lx, expected 0x%lx\n", pValueInformation->Type, REG_SZ);
2546 goto nextdevice;
2547 }
2548
2549 ValueName.Length = ValueName.MaximumLength = pValueInformation->DataLength;
2550 ValueName.Buffer = (PWCHAR)pValueInformation->Data;
2551 if (ValueName.Length >= sizeof(WCHAR) && ValueName.Buffer[ValueName.Length / sizeof(WCHAR) - 1] == UNICODE_NULL)
2552 ValueName.Length -= sizeof(WCHAR);
2553 if (RtlCompareUnicodeString(&ValueName, &AcpiBiosIdentifier, FALSE) == 0)
2554 {
2555 DPRINT("Found ACPI BIOS\n");
2556 ret = TRUE;
2557 goto cleanup;
2558 }
2559
2560 nextdevice:
2561 ZwClose(hDeviceKey);
2562 hDeviceKey = NULL;
2563 }
2564
2565 cleanup:
2566 if (pDeviceInformation)
2567 ExFreePool(pDeviceInformation);
2568 if (pValueInformation)
2569 ExFreePool(pValueInformation);
2570 if (hDevicesKey)
2571 ZwClose(hDevicesKey);
2572 if (hDeviceKey)
2573 ZwClose(hDeviceKey);
2574 return ret;
2575 #endif
2576 }
2577
2578 NTSTATUS
2579 NTAPI
2580 IopUpdateRootKey(VOID)
2581 {
2582 UNICODE_STRING EnumU = RTL_CONSTANT_STRING(L"\\Registry\\Machine\\SYSTEM\\CurrentControlSet\\Enum");
2583 UNICODE_STRING RootPathU = RTL_CONSTANT_STRING(L"Root");
2584 UNICODE_STRING MultiKeyPathU = RTL_CONSTANT_STRING(L"\\Registry\\Machine\\HARDWARE\\DESCRIPTION\\System\\MultifunctionAdapter");
2585 UNICODE_STRING DeviceDescU = RTL_CONSTANT_STRING(L"DeviceDesc");
2586 UNICODE_STRING HardwareIDU = RTL_CONSTANT_STRING(L"HardwareID");
2587 UNICODE_STRING LogConfU = RTL_CONSTANT_STRING(L"LogConf");
2588 UNICODE_STRING HalAcpiDevice = RTL_CONSTANT_STRING(L"ACPI_HAL");
2589 UNICODE_STRING HalAcpiId = RTL_CONSTANT_STRING(L"0000");
2590 UNICODE_STRING HalAcpiDeviceDesc = RTL_CONSTANT_STRING(L"HAL ACPI");
2591 UNICODE_STRING HalAcpiHardwareID = RTL_CONSTANT_STRING(L"*PNP0C08\0");
2592 OBJECT_ATTRIBUTES ObjectAttributes;
2593 HANDLE hEnum, hRoot, hHalAcpiDevice, hHalAcpiId, hLogConf;
2594 NTSTATUS Status;
2595
2596 InitializeObjectAttributes(&ObjectAttributes, &EnumU, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, NULL, NULL);
2597 Status = ZwCreateKey(&hEnum, KEY_CREATE_SUB_KEY, &ObjectAttributes, 0, NULL, 0, NULL);
2598 if (!NT_SUCCESS(Status))
2599 {
2600 DPRINT1("ZwCreateKey() failed with status 0x%08lx\n", Status);
2601 return Status;
2602 }
2603
2604 InitializeObjectAttributes(&ObjectAttributes, &RootPathU, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, hEnum, NULL);
2605 Status = ZwCreateKey(&hRoot, KEY_CREATE_SUB_KEY, &ObjectAttributes, 0, NULL, 0, NULL);
2606 ZwClose(hEnum);
2607 if (!NT_SUCCESS(Status))
2608 {
2609 DPRINT1("ZwOpenKey() failed with status 0x%08lx\n", Status);
2610 return Status;
2611 }
2612
2613 if (IopIsAcpiComputer())
2614 {
2615 InitializeObjectAttributes(&ObjectAttributes, &HalAcpiDevice, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, hRoot, NULL);
2616 Status = ZwCreateKey(&hHalAcpiDevice, KEY_CREATE_SUB_KEY, &ObjectAttributes, 0, NULL, 0, NULL);
2617 ZwClose(hRoot);
2618 if (!NT_SUCCESS(Status))
2619 return Status;
2620 InitializeObjectAttributes(&ObjectAttributes, &HalAcpiId, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, hHalAcpiDevice, NULL);
2621 Status = ZwCreateKey(&hHalAcpiId, KEY_CREATE_SUB_KEY, &ObjectAttributes, 0, NULL, 0, NULL);
2622 ZwClose(hHalAcpiDevice);
2623 if (!NT_SUCCESS(Status))
2624 return Status;
2625 Status = ZwSetValueKey(hHalAcpiId, &DeviceDescU, 0, REG_SZ, HalAcpiDeviceDesc.Buffer, HalAcpiDeviceDesc.MaximumLength);
2626 if (NT_SUCCESS(Status))
2627 Status = ZwSetValueKey(hHalAcpiId, &HardwareIDU, 0, REG_MULTI_SZ, HalAcpiHardwareID.Buffer, HalAcpiHardwareID.MaximumLength);
2628 if (NT_SUCCESS(Status))
2629 {
2630 InitializeObjectAttributes(&ObjectAttributes, &LogConfU, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, hHalAcpiId, NULL);
2631 Status = ZwCreateKey(&hLogConf, 0, &ObjectAttributes, 0, NULL, REG_OPTION_VOLATILE, NULL);
2632 if (NT_SUCCESS(Status))
2633 ZwClose(hLogConf);
2634 }
2635 ZwClose(hHalAcpiId);
2636 return Status;
2637 }
2638 else
2639 {
2640 Status = IopOpenRegistryKeyEx(&hEnum, NULL, &MultiKeyPathU, KEY_ENUMERATE_SUB_KEYS);
2641 if (!NT_SUCCESS(Status))
2642 {
2643 /* Nothing to do, don't return with an error status */
2644 DPRINT("ZwOpenKey() failed with status 0x%08lx\n", Status);
2645 ZwClose(hRoot);
2646 return STATUS_SUCCESS;
2647 }
2648 Status = IopEnumerateDetectedDevices(
2649 hEnum,
2650 NULL,
2651 hRoot,
2652 TRUE,
2653 NULL,
2654 0);
2655 ZwClose(hEnum);
2656 ZwClose(hRoot);
2657 return Status;
2658 }
2659 }
2660
2661 NTSTATUS
2662 NTAPI
2663 IopOpenRegistryKeyEx(PHANDLE KeyHandle,
2664 HANDLE ParentKey,
2665 PUNICODE_STRING Name,
2666 ACCESS_MASK DesiredAccess)
2667 {
2668 OBJECT_ATTRIBUTES ObjectAttributes;
2669 NTSTATUS Status;
2670
2671 PAGED_CODE();
2672
2673 *KeyHandle = NULL;
2674
2675 InitializeObjectAttributes(&ObjectAttributes,
2676 Name,
2677 OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
2678 ParentKey,
2679 NULL);
2680
2681 Status = ZwOpenKey(KeyHandle, DesiredAccess, &ObjectAttributes);
2682
2683 return Status;
2684 }
2685
2686 NTSTATUS
2687 NTAPI
2688 IopCreateRegistryKeyEx(OUT PHANDLE Handle,
2689 IN HANDLE RootHandle OPTIONAL,
2690 IN PUNICODE_STRING KeyName,
2691 IN ACCESS_MASK DesiredAccess,
2692 IN ULONG CreateOptions,
2693 OUT PULONG Disposition OPTIONAL)
2694 {
2695 OBJECT_ATTRIBUTES ObjectAttributes;
2696 ULONG KeyDisposition, RootHandleIndex = 0, i = 1, NestedCloseLevel = 0, Length;
2697 HANDLE HandleArray[2];
2698 BOOLEAN Recursing = TRUE;
2699 PWCHAR pp, p, p1;
2700 UNICODE_STRING KeyString;
2701 NTSTATUS Status = STATUS_SUCCESS;
2702 PAGED_CODE();
2703
2704 /* P1 is start, pp is end */
2705 p1 = KeyName->Buffer;
2706 pp = (PVOID)((ULONG_PTR)p1 + KeyName->Length);
2707
2708 /* Create the target key */
2709 InitializeObjectAttributes(&ObjectAttributes,
2710 KeyName,
2711 OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
2712 RootHandle,
2713 NULL);
2714 Status = ZwCreateKey(&HandleArray[i],
2715 DesiredAccess,
2716 &ObjectAttributes,
2717 0,
2718 NULL,
2719 CreateOptions,
2720 &KeyDisposition);
2721
2722 /* Now we check if this failed */
2723 if ((Status == STATUS_OBJECT_NAME_NOT_FOUND) && (RootHandle))
2724 {
2725 /* Target key failed, so we'll need to create its parent. Setup array */
2726 HandleArray[0] = NULL;
2727 HandleArray[1] = RootHandle;
2728
2729 /* Keep recursing for each missing parent */
2730 while (Recursing)
2731 {
2732 /* And if we're deep enough, close the last handle */
2733 if (NestedCloseLevel > 1) ZwClose(HandleArray[RootHandleIndex]);
2734
2735 /* We're setup to ping-pong between the two handle array entries */
2736 RootHandleIndex = i;
2737 i = (i + 1) & 1;
2738
2739 /* Clear the one we're attempting to open now */
2740 HandleArray[i] = NULL;
2741
2742 /* Process the parent key name */
2743 for (p = p1; ((p < pp) && (*p != OBJ_NAME_PATH_SEPARATOR)); p++);
2744 Length = (p - p1) * sizeof(WCHAR);
2745
2746 /* Is there a parent name? */
2747 if (Length)
2748 {
2749 /* Build the unicode string for it */
2750 KeyString.Buffer = p1;
2751 KeyString.Length = KeyString.MaximumLength = Length;
2752
2753 /* Now try opening the parent */
2754 InitializeObjectAttributes(&ObjectAttributes,
2755 &KeyString,
2756 OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
2757 HandleArray[RootHandleIndex],
2758 NULL);
2759 Status = ZwCreateKey(&HandleArray[i],
2760 DesiredAccess,
2761 &ObjectAttributes,
2762 0,
2763 NULL,
2764 CreateOptions,
2765 &KeyDisposition);
2766 if (NT_SUCCESS(Status))
2767 {
2768 /* It worked, we have one more handle */
2769 NestedCloseLevel++;
2770 }
2771 else
2772 {
2773 /* Parent key creation failed, abandon loop */
2774 Recursing = FALSE;
2775 continue;
2776 }
2777 }
2778 else
2779 {
2780 /* We don't have a parent name, probably corrupted key name */
2781 Status = STATUS_INVALID_PARAMETER;
2782 Recursing = FALSE;
2783 continue;
2784 }
2785
2786 /* Now see if there's more parents to create */
2787 p1 = p + 1;
2788 if ((p == pp) || (p1 == pp))
2789 {
2790 /* We're done, hopefully successfully, so stop */
2791 Recursing = FALSE;
2792 }
2793 }
2794
2795 /* Outer loop check for handle nesting that requires closing the top handle */
2796 if (NestedCloseLevel > 1) ZwClose(HandleArray[RootHandleIndex]);
2797 }
2798
2799 /* Check if we broke out of the loop due to success */
2800 if (NT_SUCCESS(Status))
2801 {
2802 /* Return the target handle (we closed all the parent ones) and disposition */
2803 *Handle = HandleArray[i];
2804 if (Disposition) *Disposition = KeyDisposition;
2805 }
2806
2807 /* Return the success state */
2808 return Status;
2809 }
2810
2811 NTSTATUS
2812 NTAPI
2813 IopGetRegistryValue(IN HANDLE Handle,
2814 IN PWSTR ValueName,
2815 OUT PKEY_VALUE_FULL_INFORMATION *Information)
2816 {
2817 UNICODE_STRING ValueString;
2818 NTSTATUS Status;
2819 PKEY_VALUE_FULL_INFORMATION FullInformation;
2820 ULONG Size;
2821 PAGED_CODE();
2822
2823 RtlInitUnicodeString(&ValueString, ValueName);
2824
2825 Status = ZwQueryValueKey(Handle,
2826 &ValueString,
2827 KeyValueFullInformation,
2828 NULL,
2829 0,
2830 &Size);
2831 if ((Status != STATUS_BUFFER_OVERFLOW) &&
2832 (Status != STATUS_BUFFER_TOO_SMALL))
2833 {
2834 return Status;
2835 }
2836
2837 FullInformation = ExAllocatePool(NonPagedPool, Size);
2838 if (!FullInformation) return STATUS_INSUFFICIENT_RESOURCES;
2839
2840 Status = ZwQueryValueKey(Handle,
2841 &ValueString,
2842 KeyValueFullInformation,
2843 FullInformation,
2844 Size,
2845 &Size);
2846 if (!NT_SUCCESS(Status))
2847 {
2848 ExFreePool(FullInformation);
2849 return Status;
2850 }
2851
2852 *Information = FullInformation;
2853 return STATUS_SUCCESS;
2854 }
2855
2856 RTL_GENERIC_COMPARE_RESULTS
2857 NTAPI
2858 PiCompareInstancePath(IN PRTL_AVL_TABLE Table,
2859 IN PVOID FirstStruct,
2860 IN PVOID SecondStruct)
2861 {
2862 /* FIXME: TODO */
2863 ASSERT(FALSE);
2864 return 0;
2865 }
2866
2867 //
2868 // The allocation function is called by the generic table package whenever
2869 // it needs to allocate memory for the table.
2870 //
2871
2872 PVOID
2873 NTAPI
2874 PiAllocateGenericTableEntry(IN PRTL_AVL_TABLE Table,
2875 IN CLONG ByteSize)
2876 {
2877 /* FIXME: TODO */
2878 ASSERT(FALSE);
2879 return NULL;
2880 }
2881
2882 VOID
2883 NTAPI
2884 PiFreeGenericTableEntry(IN PRTL_AVL_TABLE Table,
2885 IN PVOID Buffer)
2886 {
2887 /* FIXME: TODO */
2888 ASSERT(FALSE);
2889 }
2890
2891 VOID
2892 NTAPI
2893 PpInitializeDeviceReferenceTable(VOID)
2894 {
2895 /* Setup the guarded mutex and AVL table */
2896 KeInitializeGuardedMutex(&PpDeviceReferenceTableLock);
2897 RtlInitializeGenericTableAvl(
2898 &PpDeviceReferenceTable,
2899 (PRTL_AVL_COMPARE_ROUTINE)PiCompareInstancePath,
2900 (PRTL_AVL_ALLOCATE_ROUTINE)PiAllocateGenericTableEntry,
2901 (PRTL_AVL_FREE_ROUTINE)PiFreeGenericTableEntry,
2902 NULL);
2903 }
2904
2905 BOOLEAN
2906 NTAPI
2907 PiInitPhase0(VOID)
2908 {
2909 /* Initialize the resource when accessing device registry data */
2910 ExInitializeResourceLite(&PpRegistryDeviceResource);
2911
2912 /* Setup the device reference AVL table */
2913 PpInitializeDeviceReferenceTable();
2914 return TRUE;
2915 }
2916
2917 BOOLEAN
2918 NTAPI
2919 PpInitSystem(VOID)
2920 {
2921 /* Check the initialization phase */
2922 switch (ExpInitializationPhase)
2923 {
2924 case 0:
2925
2926 /* Do Phase 0 */
2927 return PiInitPhase0();
2928
2929 case 1:
2930
2931 /* Do Phase 1 */
2932 return TRUE;
2933 //return PiInitPhase1();
2934
2935 default:
2936
2937 /* Don't know any other phase! Bugcheck! */
2938 KeBugCheck(UNEXPECTED_INITIALIZATION_CALL);
2939 return FALSE;
2940 }
2941 }
2942
2943 LONG IopNumberDeviceNodes;
2944
2945 PDEVICE_NODE
2946 NTAPI
2947 PipAllocateDeviceNode(IN PDEVICE_OBJECT PhysicalDeviceObject)
2948 {
2949 PDEVICE_NODE DeviceNode;
2950 PAGED_CODE();
2951
2952 /* Allocate it */
2953 DeviceNode = ExAllocatePoolWithTag(NonPagedPool, sizeof(DEVICE_NODE), 'donD');
2954 if (!DeviceNode) return DeviceNode;
2955
2956 /* Statistics */
2957 InterlockedIncrement(&IopNumberDeviceNodes);
2958
2959 /* Set it up */
2960 RtlZeroMemory(DeviceNode, sizeof(DEVICE_NODE));
2961 DeviceNode->InterfaceType = InterfaceTypeUndefined;
2962 DeviceNode->BusNumber = -1;
2963 DeviceNode->ChildInterfaceType = InterfaceTypeUndefined;
2964 DeviceNode->ChildBusNumber = -1;
2965 DeviceNode->ChildBusTypeIndex = -1;
2966 // KeInitializeEvent(&DeviceNode->EnumerationMutex, SynchronizationEvent, TRUE);
2967 InitializeListHead(&DeviceNode->DeviceArbiterList);
2968 InitializeListHead(&DeviceNode->DeviceTranslatorList);
2969 InitializeListHead(&DeviceNode->TargetDeviceNotify);
2970 InitializeListHead(&DeviceNode->DockInfo.ListEntry);
2971 InitializeListHead(&DeviceNode->PendedSetInterfaceState);
2972
2973 /* Check if there is a PDO */
2974 if (PhysicalDeviceObject)
2975 {
2976 /* Link it and remove the init flag */
2977 DeviceNode->PhysicalDeviceObject = PhysicalDeviceObject;
2978 ((PEXTENDED_DEVOBJ_EXTENSION)PhysicalDeviceObject->DeviceObjectExtension)->DeviceNode = DeviceNode;
2979 PhysicalDeviceObject->Flags &= ~DO_DEVICE_INITIALIZING;
2980 }
2981
2982 /* Return the node */
2983 return DeviceNode;
2984 }
2985
2986 /* PUBLIC FUNCTIONS **********************************************************/
2987
2988 /*
2989 * @implemented
2990 */
2991 NTSTATUS
2992 NTAPI
2993 IoGetDeviceProperty(IN PDEVICE_OBJECT DeviceObject,
2994 IN DEVICE_REGISTRY_PROPERTY DeviceProperty,
2995 IN ULONG BufferLength,
2996 OUT PVOID PropertyBuffer,
2997 OUT PULONG ResultLength)
2998 {
2999 PDEVICE_NODE DeviceNode = IopGetDeviceNode(DeviceObject);
3000 DEVICE_CAPABILITIES DeviceCaps;
3001 ULONG Length;
3002 PVOID Data = NULL;
3003 PWSTR Ptr;
3004 NTSTATUS Status;
3005 POBJECT_NAME_INFORMATION ObjectNameInfo = NULL;
3006 ULONG RequiredLength, ObjectNameInfoLength;
3007
3008 DPRINT("IoGetDeviceProperty(0x%p %d)\n", DeviceObject, DeviceProperty);
3009
3010 *ResultLength = 0;
3011
3012 if (DeviceNode == NULL)
3013 return STATUS_INVALID_DEVICE_REQUEST;
3014
3015 switch (DeviceProperty)
3016 {
3017 case DevicePropertyBusNumber:
3018 Length = sizeof(ULONG);
3019 Data = &DeviceNode->ChildBusNumber;
3020 break;
3021
3022 /* Complete, untested */
3023 case DevicePropertyBusTypeGuid:
3024 /* Sanity check */
3025 if ((DeviceNode->ChildBusTypeIndex != 0xFFFF) &&
3026 (DeviceNode->ChildBusTypeIndex < PnpBusTypeGuidList->GuidCount))
3027 {
3028 /* Return the GUID */
3029 *ResultLength = sizeof(GUID);
3030
3031 /* Check if the buffer given was large enough */
3032 if (BufferLength < *ResultLength)
3033 {
3034 return STATUS_BUFFER_TOO_SMALL;
3035 }
3036
3037 /* Copy the GUID */
3038 RtlCopyMemory(PropertyBuffer,
3039 &(PnpBusTypeGuidList->Guids[DeviceNode->ChildBusTypeIndex]),
3040 sizeof(GUID));
3041 return STATUS_SUCCESS;
3042 }
3043 else
3044 {
3045 return STATUS_OBJECT_NAME_NOT_FOUND;
3046 }
3047 break;
3048
3049 case DevicePropertyLegacyBusType:
3050 Length = sizeof(INTERFACE_TYPE);
3051 Data = &DeviceNode->ChildInterfaceType;
3052 break;
3053
3054 case DevicePropertyAddress:
3055 /* Query the device caps */
3056 Status = IopQueryDeviceCapabilities(DeviceNode, &DeviceCaps);
3057 if (NT_SUCCESS(Status) && (DeviceCaps.Address != MAXULONG))
3058 {
3059 /* Return length */
3060 *ResultLength = sizeof(ULONG);
3061
3062 /* Check if the buffer given was large enough */
3063 if (BufferLength < *ResultLength)
3064 {
3065 return STATUS_BUFFER_TOO_SMALL;
3066 }
3067
3068 /* Return address */
3069 *(PULONG)PropertyBuffer = DeviceCaps.Address;
3070 return STATUS_SUCCESS;
3071 }
3072 else
3073 {
3074 return STATUS_OBJECT_NAME_NOT_FOUND;
3075 }
3076 break;
3077
3078 // case DevicePropertyUINumber:
3079 // if (DeviceNode->CapabilityFlags == NULL)
3080 // return STATUS_INVALID_DEVICE_REQUEST;
3081 // Length = sizeof(ULONG);
3082 // Data = &DeviceNode->CapabilityFlags->UINumber;
3083 // break;
3084
3085 case DevicePropertyClassName:
3086 case DevicePropertyClassGuid:
3087 case DevicePropertyDriverKeyName:
3088 case DevicePropertyManufacturer:
3089 case DevicePropertyFriendlyName:
3090 case DevicePropertyHardwareID:
3091 case DevicePropertyCompatibleIDs:
3092 case DevicePropertyDeviceDescription:
3093 case DevicePropertyLocationInformation:
3094 case DevicePropertyUINumber:
3095 {
3096 LPCWSTR RegistryPropertyName;
3097 UNICODE_STRING EnumRoot = RTL_CONSTANT_STRING(ENUM_ROOT);
3098 UNICODE_STRING ValueName;
3099 KEY_VALUE_PARTIAL_INFORMATION *ValueInformation;
3100 ULONG ValueInformationLength;
3101 HANDLE KeyHandle, EnumRootHandle;
3102 NTSTATUS Status;
3103
3104 switch (DeviceProperty)
3105 {
3106 case DevicePropertyClassName:
3107 RegistryPropertyName = L"Class"; break;
3108 case DevicePropertyClassGuid:
3109 RegistryPropertyName = L"ClassGuid"; break;
3110 case DevicePropertyDriverKeyName:
3111 RegistryPropertyName = L"Driver"; break;
3112 case DevicePropertyManufacturer:
3113 RegistryPropertyName = L"Mfg"; break;
3114 case DevicePropertyFriendlyName:
3115 RegistryPropertyName = L"FriendlyName"; break;
3116 case DevicePropertyHardwareID:
3117 RegistryPropertyName = L"HardwareID"; break;
3118 case DevicePropertyCompatibleIDs:
3119 RegistryPropertyName = L"CompatibleIDs"; break;
3120 case DevicePropertyDeviceDescription:
3121 RegistryPropertyName = L"DeviceDesc"; break;
3122 case DevicePropertyLocationInformation:
3123 RegistryPropertyName = L"LocationInformation"; break;
3124 case DevicePropertyUINumber:
3125 RegistryPropertyName = L"UINumber"; break;
3126 default:
3127 /* Should not happen */
3128 ASSERT(FALSE);
3129 return STATUS_UNSUCCESSFUL;
3130 }
3131
3132 DPRINT("Registry property %S\n", RegistryPropertyName);
3133
3134 /* Open Enum key */
3135 Status = IopOpenRegistryKeyEx(&EnumRootHandle, NULL,
3136 &EnumRoot, KEY_READ);
3137 if (!NT_SUCCESS(Status))
3138 {
3139 DPRINT1("Error opening ENUM_ROOT, Status=0x%08x\n", Status);
3140 return Status;
3141 }
3142
3143 /* Open instance key */
3144 Status = IopOpenRegistryKeyEx(&KeyHandle, EnumRootHandle,
3145 &DeviceNode->InstancePath, KEY_READ);
3146 if (!NT_SUCCESS(Status))
3147 {
3148 DPRINT1("Error opening InstancePath, Status=0x%08x\n", Status);
3149 ZwClose(EnumRootHandle);
3150 return Status;
3151 }
3152
3153 /* Allocate buffer to read as much data as required by the caller */
3154 ValueInformationLength = FIELD_OFFSET(KEY_VALUE_PARTIAL_INFORMATION,
3155 Data[0]) + BufferLength;
3156 ValueInformation = ExAllocatePool(PagedPool, ValueInformationLength);
3157 if (!ValueInformation)
3158 {
3159 ZwClose(KeyHandle);
3160 return STATUS_INSUFFICIENT_RESOURCES;
3161 }
3162
3163 /* Read the value */
3164 RtlInitUnicodeString(&ValueName, RegistryPropertyName);
3165 Status = ZwQueryValueKey(KeyHandle, &ValueName,
3166 KeyValuePartialInformation, ValueInformation,
3167 ValueInformationLength,
3168 &ValueInformationLength);
3169 ZwClose(KeyHandle);
3170
3171 /* Return data */
3172 *ResultLength = ValueInformation->DataLength;
3173
3174 if (!NT_SUCCESS(Status))
3175 {
3176 ExFreePool(ValueInformation);
3177 if (Status == STATUS_BUFFER_OVERFLOW)
3178 return STATUS_BUFFER_TOO_SMALL;
3179 DPRINT1("Problem: Status=0x%08x, ResultLength = %d\n", Status, *ResultLength);
3180 return Status;
3181 }
3182
3183 /* FIXME: Verify the value (NULL-terminated, correct format). */
3184 RtlCopyMemory(PropertyBuffer, ValueInformation->Data,
3185 ValueInformation->DataLength);
3186 ExFreePool(ValueInformation);
3187
3188 return STATUS_SUCCESS;
3189 }
3190
3191 case DevicePropertyBootConfiguration:
3192 Length = 0;
3193 if (DeviceNode->BootResources->Count != 0)
3194 {
3195 Length = IopCalculateResourceListSize(DeviceNode->BootResources);
3196 }
3197 Data = DeviceNode->BootResources;
3198 break;
3199
3200 /* FIXME: use a translated boot configuration instead */
3201 case DevicePropertyBootConfigurationTranslated:
3202 Length = 0;
3203 if (DeviceNode->BootResources->Count != 0)
3204 {
3205 Length = IopCalculateResourceListSize(DeviceNode->BootResources);
3206 }
3207 Data = DeviceNode->BootResources;
3208 break;
3209
3210 case DevicePropertyEnumeratorName:
3211 /* A buffer overflow can't happen here, since InstancePath
3212 * always contains the enumerator name followed by \\ */
3213 Ptr = wcschr(DeviceNode->InstancePath.Buffer, L'\\');
3214 ASSERT(Ptr);
3215 Length = (Ptr - DeviceNode->InstancePath.Buffer) * sizeof(WCHAR);
3216 Data = DeviceNode->InstancePath.Buffer;
3217 break;
3218
3219 case DevicePropertyPhysicalDeviceObjectName:
3220 Status = ObQueryNameString(DeviceNode->PhysicalDeviceObject,
3221 NULL,
3222 0,
3223 &RequiredLength);
3224 if (Status == STATUS_SUCCESS)
3225 {
3226 Length = 0;
3227 Data = L"";
3228 }
3229 else if (Status == STATUS_INFO_LENGTH_MISMATCH)
3230 {
3231 ObjectNameInfoLength = RequiredLength;
3232 ObjectNameInfo = ExAllocatePool(PagedPool, ObjectNameInfoLength);
3233 if (!ObjectNameInfo)
3234 return STATUS_INSUFFICIENT_RESOURCES;
3235
3236 Status = ObQueryNameString(DeviceNode->PhysicalDeviceObject,
3237 ObjectNameInfo,
3238 ObjectNameInfoLength,
3239 &RequiredLength);
3240 if (NT_SUCCESS(Status))
3241 {
3242 Length = ObjectNameInfo->Name.Length;
3243 Data = ObjectNameInfo->Name.Buffer;
3244 }
3245 else
3246 return Status;
3247 }
3248 else
3249 return Status;
3250 break;
3251
3252 default:
3253 return STATUS_INVALID_PARAMETER_2;
3254 }
3255
3256 /* Prepare returned values */
3257 *ResultLength = Length;
3258 if (BufferLength < Length)
3259 {
3260 if (ObjectNameInfo != NULL)
3261 ExFreePool(ObjectNameInfo);
3262