fix typo
[reactos.git] / reactos / ntoskrnl / io / pnpmgr / pnpmgr.c
index 96b282a..54a595f 100644 (file)
 #define NDEBUG
 #include <internal/debug.h>
 
+//#define ENABLE_ACPI
+
 /* GLOBALS *******************************************************************/
 
+#define ENUM_ROOT L"\\Registry\\Machine\\System\\CurrentControlSet\\Enum"
+
 PDEVICE_NODE IopRootDeviceNode;
 KSPIN_LOCK IopDeviceTreeLock;
+ERESOURCE PpRegistryDeviceResource;
+KGUARDED_MUTEX PpDeviceReferenceTableLock;
+RTL_AVL_TABLE PpDeviceReferenceTable;
+
+extern ULONG ExpInitializationPhase;
 
 /* DATA **********************************************************************/
 
@@ -32,19 +41,29 @@ PIO_BUS_TYPE_GUID_LIST IopBusTypeGuidList = NULL;
 
 typedef struct _INVALIDATE_DEVICE_RELATION_DATA
 {
+    PDEVICE_OBJECT DeviceObject;
     DEVICE_RELATION_TYPE Type;
     PIO_WORKITEM WorkItem;
-    PKEVENT Event;
-    NTSTATUS Status;
 } INVALIDATE_DEVICE_RELATION_DATA, *PINVALIDATE_DEVICE_RELATION_DATA;
 
-static VOID NTAPI
-IopInvalidateDeviceRelations(
+VOID
+NTAPI
+IoSynchronousInvalidateDeviceRelations(
     IN PDEVICE_OBJECT DeviceObject,
-    IN PVOID InvalidateContext);
+    IN DEVICE_RELATION_TYPE Type);
+
 
 /* FUNCTIONS *****************************************************************/
 
+static NTSTATUS
+IopAssignDeviceResources(
+   IN PDEVICE_NODE DeviceNode,
+   OUT ULONG *pRequiredSize);
+static NTSTATUS
+IopTranslateDeviceResources(
+   IN PDEVICE_NODE DeviceNode,
+   IN ULONG RequiredSize);
+
 PDEVICE_NODE
 FASTCALL
 IopGetDeviceNode(PDEVICE_OBJECT DeviceObject)
@@ -59,57 +78,60 @@ IopInitializeDevice(PDEVICE_NODE DeviceNode,
 {
    PDEVICE_OBJECT Fdo;
    NTSTATUS Status;
-   BOOLEAN IsPnpDriver = FALSE;
 
-   if (DriverObject->DriverExtension->AddDevice)
+   if (!DriverObject->DriverExtension->AddDevice)
+      return STATUS_SUCCESS;
+
+   /* This is a Plug and Play driver */
+   DPRINT("Plug and Play driver found\n");
+   ASSERT(DeviceNode->PhysicalDeviceObject);
+
+   /* Check if this plug-and-play driver is used as a legacy one for this device node */
+   if (IopDeviceNodeHasFlag(DeviceNode, DNF_LEGACY_DRIVER))
    {
-      /* This is a Plug and Play driver */
-      DPRINT("Plug and Play driver found\n");
+      IopDeviceNodeSetFlag(DeviceNode, DNF_ADDED);
+      return STATUS_SUCCESS;
+   }
 
-      ASSERT(DeviceNode->PhysicalDeviceObject);
+   DPRINT("Calling %wZ->AddDevice(%wZ)\n",
+      &DriverObject->DriverName,
+      &DeviceNode->InstancePath);
+   Status = DriverObject->DriverExtension->AddDevice(
+      DriverObject, DeviceNode->PhysicalDeviceObject);
+   if (!NT_SUCCESS(Status))
+   {
+      IopDeviceNodeSetFlag(DeviceNode, DNF_DISABLED);
+      return Status;
+   }
 
-      DPRINT("Calling driver AddDevice entrypoint at %08lx\n",
-         DriverObject->DriverExtension->AddDevice);
+   /* Check if driver added a FDO above the PDO */
+   Fdo = IoGetAttachedDeviceReference(DeviceNode->PhysicalDeviceObject);
+   if (Fdo == DeviceNode->PhysicalDeviceObject)
+   {
+      /* FIXME: What do we do? Unload the driver or just disable the device? */
+      DPRINT1("An FDO was not attached\n");
+      IopDeviceNodeSetFlag(DeviceNode, DNF_DISABLED);
+      return STATUS_UNSUCCESSFUL;
+   }
 
-      IsPnpDriver = !IopDeviceNodeHasFlag(DeviceNode, DNF_LEGACY_DRIVER);
-      Status = DriverObject->DriverExtension->AddDevice(
-         DriverObject, IsPnpDriver ? DeviceNode->PhysicalDeviceObject : NULL);
+   /* Check if we have a ACPI device (needed for power management) */
+   if (Fdo->DeviceType == FILE_DEVICE_ACPI)
+   {
+      static BOOLEAN SystemPowerDeviceNodeCreated = FALSE;
 
-      if (!NT_SUCCESS(Status))
+      /* There can be only one system power device */
+      if (!SystemPowerDeviceNodeCreated)
       {
-         return Status;
+         PopSystemPowerDeviceNode = DeviceNode;
+         ObReferenceObject(PopSystemPowerDeviceNode);
+         SystemPowerDeviceNodeCreated = TRUE;
       }
+   }
 
-      if (IsPnpDriver)
-      {
-         Fdo = IoGetAttachedDeviceReference(DeviceNode->PhysicalDeviceObject);
-
-         if (Fdo == DeviceNode->PhysicalDeviceObject)
-         {
-            /* FIXME: What do we do? Unload the driver or just disable the device? */
-            DbgPrint("An FDO was not attached\n");
-            IopDeviceNodeSetFlag(DeviceNode, DNF_DISABLED);
-            return STATUS_UNSUCCESSFUL;
-         }
-
-         if (Fdo->DeviceType == FILE_DEVICE_ACPI)
-         {
-            static BOOLEAN SystemPowerDeviceNodeCreated = FALSE;
-
-            /* There can be only one system power device */
-            if (!SystemPowerDeviceNodeCreated)
-            {
-               PopSystemPowerDeviceNode = DeviceNode;
-               SystemPowerDeviceNodeCreated = TRUE;
-            }
-         }
-
-         ObDereferenceObject(Fdo);
-      }
+   ObDereferenceObject(Fdo);
 
-      IopDeviceNodeSetFlag(DeviceNode, DNF_ADDED);
-      IopDeviceNodeSetFlag(DeviceNode, DNF_NEED_ENUMERATION_ONLY);
-   }
+   IopDeviceNodeSetFlag(DeviceNode, DNF_ADDED);
+   IopDeviceNodeSetFlag(DeviceNode, DNF_NEED_ENUMERATION_ONLY);
 
    return STATUS_SUCCESS;
 }
@@ -120,31 +142,77 @@ IopStartDevice(
 {
    IO_STATUS_BLOCK IoStatusBlock;
    IO_STACK_LOCATION Stack;
+   ULONG RequiredLength;
    PDEVICE_OBJECT Fdo;
    NTSTATUS Status;
 
-   DPRINT("Sending IRP_MN_START_DEVICE to driver\n");
-
    Fdo = IoGetAttachedDeviceReference(DeviceNode->PhysicalDeviceObject);
+
+   IopDeviceNodeSetFlag(DeviceNode, DNF_ASSIGNING_RESOURCES);
+   DPRINT("Sending IRP_MN_FILTER_RESOURCE_REQUIREMENTS to device stack\n");
+   Stack.Parameters.FilterResourceRequirements.IoResourceRequirementList = DeviceNode->ResourceRequirements;
+   Status = IopInitiatePnpIrp(
+      Fdo,
+      &IoStatusBlock,
+      IRP_MN_FILTER_RESOURCE_REQUIREMENTS,
+      &Stack);
+   if (!NT_SUCCESS(Status) && Status != STATUS_NOT_SUPPORTED)
+   {
+      DPRINT("IopInitiatePnpIrp(IRP_MN_FILTER_RESOURCE_REQUIREMENTS) failed\n");
+      return Status;
+   }
+   DeviceNode->ResourceRequirements = Stack.Parameters.FilterResourceRequirements.IoResourceRequirementList;
+
+   Status = IopAssignDeviceResources(DeviceNode, &RequiredLength);
+   if (NT_SUCCESS(Status))
+   {
+      Status = IopTranslateDeviceResources(DeviceNode, RequiredLength);
+      if (NT_SUCCESS(Status))
+      {
+         IopDeviceNodeSetFlag(DeviceNode, DNF_RESOURCE_ASSIGNED);
+      }
+      else
+      {
+         DPRINT("IopTranslateDeviceResources() failed (Status 0x%08lx)\n", Status);
+      }
+   }
+   else
+   {
+      DPRINT("IopAssignDeviceResources() failed (Status 0x%08lx)\n", Status);
+   }
+   IopDeviceNodeClearFlag(DeviceNode, DNF_ASSIGNING_RESOURCES);
+
+   DPRINT("Sending IRP_MN_START_DEVICE to driver\n");
    Stack.Parameters.StartDevice.AllocatedResources = DeviceNode->ResourceList;
    Stack.Parameters.StartDevice.AllocatedResourcesTranslated = DeviceNode->ResourceListTranslated;
 
+   /*
+    * Windows NT Drivers receive IRP_MN_START_DEVICE in a critical region and
+    * actually _depend_ on this!. This is because NT will lock the Device Node
+    * with an ERESOURCE, which of course requires APCs to be disabled.
+    */
+   KeEnterCriticalRegion();
+
    Status = IopInitiatePnpIrp(
       Fdo,
       &IoStatusBlock,
       IRP_MN_START_DEVICE,
       &Stack);
 
+   KeLeaveCriticalRegion();
+
    if (!NT_SUCCESS(Status))
    {
       DPRINT("IopInitiatePnpIrp() failed\n");
    }
    else
    {
-         if (IopDeviceNodeHasFlag(DeviceNode, DNF_NEED_ENUMERATION_ONLY))
+      if (IopDeviceNodeHasFlag(DeviceNode, DNF_NEED_ENUMERATION_ONLY))
       {
          DPRINT("Device needs enumeration, invalidating bus relations\n");
-         IoInvalidateDeviceRelations(DeviceNode->PhysicalDeviceObject, BusRelations);
+         /* Invalidate device relations synchronously
+            (otherwise there will be dirty read of DeviceNode) */
+         IoSynchronousInvalidateDeviceRelations(DeviceNode->PhysicalDeviceObject, BusRelations);
          IopDeviceNodeClearFlag(DeviceNode, DNF_NEED_ENUMERATION_ONLY);
       }
    }
@@ -183,37 +251,20 @@ IopQueryDeviceCapabilities(PDEVICE_NODE DeviceNode,
                             &Stack);
 }
 
-/*
- * @implemented
- */
-VOID
-NTAPI
-IoInvalidateDeviceRelations(
+static VOID NTAPI
+IopAsynchronousInvalidateDeviceRelations(
     IN PDEVICE_OBJECT DeviceObject,
-    IN DEVICE_RELATION_TYPE Type)
+    IN PVOID InvalidateContext)
 {
-    PIO_WORKITEM WorkItem;
-    PINVALIDATE_DEVICE_RELATION_DATA Data;
-
-    Data = ExAllocatePool(PagedPool, sizeof(INVALIDATE_DEVICE_RELATION_DATA));
-    if (!Data)
-        return;
-    WorkItem = IoAllocateWorkItem(DeviceObject);
-    if (!WorkItem)
-    {
-        ExFreePool(Data);
-        return;
-    }
+    PINVALIDATE_DEVICE_RELATION_DATA Data = InvalidateContext;
 
-    Data->Type = Type;
-    Data->WorkItem = WorkItem;
-    Data->Event = NULL;
+    IoSynchronousInvalidateDeviceRelations(
+        Data->DeviceObject,
+        Data->Type);
 
-    IoQueueWorkItem(
-        WorkItem,
-        IopInvalidateDeviceRelations,
-        DelayedWorkQueue,
-        Data);
+    ObDereferenceObject(Data->WorkItem);
+    IoFreeWorkItem(Data->WorkItem);
+    ExFreePool(Data);
 }
 
 /*
@@ -221,13 +272,12 @@ IoInvalidateDeviceRelations(
  */
 VOID
 NTAPI
-IoSynchronousInvalidateDeviceRelations(
+IoInvalidateDeviceRelations(
     IN PDEVICE_OBJECT DeviceObject,
     IN DEVICE_RELATION_TYPE Type)
 {
     PIO_WORKITEM WorkItem;
     PINVALIDATE_DEVICE_RELATION_DATA Data;
-    KEVENT Event;
 
     Data = ExAllocatePool(PagedPool, sizeof(INVALIDATE_DEVICE_RELATION_DATA));
     if (!Data)
@@ -239,19 +289,16 @@ IoSynchronousInvalidateDeviceRelations(
         return;
     }
 
-    KeInitializeEvent(&Event, NotificationEvent, FALSE);
+    ObReferenceObject(DeviceObject);
+    Data->DeviceObject = DeviceObject;
     Data->Type = Type;
     Data->WorkItem = WorkItem;
-    Data->Event = &Event;
 
     IoQueueWorkItem(
         WorkItem,
-        IopInvalidateDeviceRelations,
+        IopAsynchronousInvalidateDeviceRelations,
         DelayedWorkQueue,
         Data);
-
-    KeWaitForSingleObject(&Event, Executive, KernelMode, FALSE, NULL);
-    ExFreePool(Data);
 }
 
 /*
@@ -265,31 +312,33 @@ IoGetDeviceProperty(IN PDEVICE_OBJECT DeviceObject,
                     OUT PVOID PropertyBuffer,
                     OUT PULONG ResultLength)
 {
-   PDEVICE_NODE DeviceNode = IopGetDeviceNode(DeviceObject);
-   DEVICE_CAPABILITIES DeviceCaps;
-   ULONG Length;
-   PVOID Data = NULL;
-   PWSTR Ptr;
-   NTSTATUS Status;
+    PDEVICE_NODE DeviceNode = IopGetDeviceNode(DeviceObject);
+    DEVICE_CAPABILITIES DeviceCaps;
+    ULONG Length;
+    PVOID Data = NULL;
+    PWSTR Ptr;
+    NTSTATUS Status;
 
-   DPRINT("IoGetDeviceProperty(0x%p %d)\n", DeviceObject, DeviceProperty);
+    DPRINT("IoGetDeviceProperty(0x%p %d)\n", DeviceObject, DeviceProperty);
 
-   if (DeviceNode == NULL)
-      return STATUS_INVALID_DEVICE_REQUEST;
+    *ResultLength = 0;
 
-   switch (DeviceProperty)
-   {
-      case DevicePropertyBusNumber:
-         Length = sizeof(ULONG);
-         Data = &DeviceNode->ChildBusNumber;
-         break;
+    if (DeviceNode == NULL)
+        return STATUS_INVALID_DEVICE_REQUEST;
 
-      /* Complete, untested */
-      case DevicePropertyBusTypeGuid:
-         /* Sanity check */
-         if ((DeviceNode->ChildBusTypeIndex != 0xFFFF) && 
-             (DeviceNode->ChildBusTypeIndex < IopBusTypeGuidList->GuidCount))
-         {
+    switch (DeviceProperty)
+    {
+    case DevicePropertyBusNumber:
+        Length = sizeof(ULONG);
+        Data = &DeviceNode->ChildBusNumber;
+        break;
+
+        /* Complete, untested */
+    case DevicePropertyBusTypeGuid:
+        /* Sanity check */
+        if ((DeviceNode->ChildBusTypeIndex != 0xFFFF) &&
+            (DeviceNode->ChildBusTypeIndex < IopBusTypeGuidList->GuidCount))
+        {
             /* Return the GUID */
             *ResultLength = sizeof(GUID);
 
@@ -300,45 +349,45 @@ IoGetDeviceProperty(IN PDEVICE_OBJECT DeviceObject,
             }
 
             /* Copy the GUID */
-            RtlCopyMemory(PropertyBuffer, 
-                          &(IopBusTypeGuidList->Guids[DeviceNode->ChildBusTypeIndex]),
-                          sizeof(GUID));
+            RtlCopyMemory(PropertyBuffer,
+                &(IopBusTypeGuidList->Guids[DeviceNode->ChildBusTypeIndex]),
+                sizeof(GUID));
             return STATUS_SUCCESS;
-         }
-         else
-         {
+        }
+        else
+        {
             return STATUS_OBJECT_NAME_NOT_FOUND;
-         }
-         break;
+        }
+        break;
 
-      case DevicePropertyLegacyBusType:
-         Length = sizeof(INTERFACE_TYPE);
-         Data = &DeviceNode->ChildInterfaceType;
-         break;
+    case DevicePropertyLegacyBusType:
+        Length = sizeof(INTERFACE_TYPE);
+        Data = &DeviceNode->ChildInterfaceType;
+        break;
 
-      case DevicePropertyAddress:
-         /* Query the device caps */
-         Status = IopQueryDeviceCapabilities(DeviceNode, &DeviceCaps);
-         if (NT_SUCCESS(Status) && (DeviceCaps.Address != (ULONG)-1))
-         {
+    case DevicePropertyAddress:
+        /* Query the device caps */
+        Status = IopQueryDeviceCapabilities(DeviceNode, &DeviceCaps);
+        if (NT_SUCCESS(Status) && (DeviceCaps.Address != (ULONG)-1))
+        {
             /* Return length */
             *ResultLength = sizeof(ULONG);
 
             /* Check if the buffer given was large enough */
             if (BufferLength < *ResultLength)
             {
-               return STATUS_BUFFER_TOO_SMALL;
+                return STATUS_BUFFER_TOO_SMALL;
             }
 
             /* Return address */
             *(PULONG)PropertyBuffer = DeviceCaps.Address;
             return STATUS_SUCCESS;
-         }
-         else
-         {
+        }
+        else
+        {
             return STATUS_OBJECT_NAME_NOT_FOUND;
-         }
-         break;
+        }
+        break;
 
 //    case DevicePropertyUINumber:
 //      if (DeviceNode->CapabilityFlags == NULL)
@@ -347,161 +396,165 @@ IoGetDeviceProperty(IN PDEVICE_OBJECT DeviceObject,
 //      Data = &DeviceNode->CapabilityFlags->UINumber;
 //      break;
 
-      case DevicePropertyClassName:
-      case DevicePropertyClassGuid:
-      case DevicePropertyDriverKeyName:
-      case DevicePropertyManufacturer:
-      case DevicePropertyFriendlyName:
-      case DevicePropertyHardwareID:
-      case DevicePropertyCompatibleIDs:
-      case DevicePropertyDeviceDescription:
-      case DevicePropertyLocationInformation:
-      case DevicePropertyUINumber:
-      {
-         LPWSTR RegistryPropertyName, KeyNameBuffer;
-         UNICODE_STRING KeyName, ValueName;
-         OBJECT_ATTRIBUTES ObjectAttributes;
-         KEY_VALUE_PARTIAL_INFORMATION *ValueInformation;
-         ULONG ValueInformationLength;
-         HANDLE KeyHandle;
-         NTSTATUS Status;
-
-         switch (DeviceProperty)
-         {
+    case DevicePropertyClassName:
+    case DevicePropertyClassGuid:
+    case DevicePropertyDriverKeyName:
+    case DevicePropertyManufacturer:
+    case DevicePropertyFriendlyName:
+    case DevicePropertyHardwareID:
+    case DevicePropertyCompatibleIDs:
+    case DevicePropertyDeviceDescription:
+    case DevicePropertyLocationInformation:
+    case DevicePropertyUINumber:
+        {
+            LPCWSTR RegistryPropertyName;
+            UNICODE_STRING EnumRoot = RTL_CONSTANT_STRING(ENUM_ROOT);
+            UNICODE_STRING ValueName;
+            OBJECT_ATTRIBUTES ObjectAttributes;
+            KEY_VALUE_PARTIAL_INFORMATION *ValueInformation;
+            ULONG ValueInformationLength;
+            HANDLE KeyHandle, EnumRootHandle;
+            NTSTATUS Status;
+
+            switch (DeviceProperty)
+            {
             case DevicePropertyClassName:
-               RegistryPropertyName = L"Class"; break;
+                RegistryPropertyName = L"Class"; break;
             case DevicePropertyClassGuid:
-               RegistryPropertyName = L"ClassGuid"; break;
+                RegistryPropertyName = L"ClassGuid"; break;
             case DevicePropertyDriverKeyName:
-               RegistryPropertyName = L"Driver"; break;
+                RegistryPropertyName = L"Driver"; break;
             case DevicePropertyManufacturer:
-               RegistryPropertyName = L"Mfg"; break;
+                RegistryPropertyName = L"Mfg"; break;
             case DevicePropertyFriendlyName:
-               RegistryPropertyName = L"FriendlyName"; break;
+                RegistryPropertyName = L"FriendlyName"; break;
             case DevicePropertyHardwareID:
-               RegistryPropertyName = L"HardwareID"; break;
+                RegistryPropertyName = L"HardwareID"; break;
             case DevicePropertyCompatibleIDs:
-               RegistryPropertyName = L"CompatibleIDs"; break;
+                RegistryPropertyName = L"CompatibleIDs"; break;
             case DevicePropertyDeviceDescription:
-               RegistryPropertyName = L"DeviceDesc"; break;
+                RegistryPropertyName = L"DeviceDesc"; break;
             case DevicePropertyLocationInformation:
-               RegistryPropertyName = L"LocationInformation"; break;
+                RegistryPropertyName = L"LocationInformation"; break;
             case DevicePropertyUINumber:
-               RegistryPropertyName = L"UINumber"; break;
+                RegistryPropertyName = L"UINumber"; break;
             default:
-               RegistryPropertyName = NULL; break;
-         }
+                /* Should not happen */
+                ASSERT(FALSE);
+                return STATUS_UNSUCCESSFUL;
+            }
 
-         KeyNameBuffer = ExAllocatePool(PagedPool,
-            (49 * sizeof(WCHAR)) + DeviceNode->InstancePath.Length);
+            DPRINT("Registry property %S\n", RegistryPropertyName);
 
-         DPRINT("KeyNameBuffer: 0x%p, value %S\n", KeyNameBuffer, RegistryPropertyName);
+            /* Open Enum key */
+            InitializeObjectAttributes(&ObjectAttributes, &EnumRoot,
+                OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, NULL, NULL);
+            Status = ZwOpenKey(&EnumRootHandle, 0, &ObjectAttributes);
+            if (!NT_SUCCESS(Status))
+            {
+                DPRINT1("Error opening ENUM_ROOT, Status=0x%08x\n", Status);
+                return Status;
+            }
 
-         if (KeyNameBuffer == NULL)
-            return STATUS_INSUFFICIENT_RESOURCES;
+            /* Open instance key */
+            InitializeObjectAttributes(&ObjectAttributes, &DeviceNode->InstancePath,
+                OBJ_CASE_INSENSITIVE, EnumRootHandle, NULL);
 
-         wcscpy(KeyNameBuffer, L"\\Registry\\Machine\\System\\CurrentControlSet\\Enum\\");
-         wcscat(KeyNameBuffer, DeviceNode->InstancePath.Buffer);
-         RtlInitUnicodeString(&KeyName, KeyNameBuffer);
-         InitializeObjectAttributes(&ObjectAttributes, &KeyName,
-                                    OBJ_CASE_INSENSITIVE, NULL, NULL);
+            Status = ZwOpenKey(&KeyHandle, KEY_READ, &ObjectAttributes);
+            if (!NT_SUCCESS(Status))
+            {
+                DPRINT1("Error opening InstancePath, Status=0x%08x\n", Status);
+                return Status;
+            }
 
-         Status = ZwOpenKey(&KeyHandle, KEY_READ, &ObjectAttributes);
-         ExFreePool(KeyNameBuffer);
-         if (!NT_SUCCESS(Status))
-            return Status;
+            /* Allocate buffer to read as much data as required by the caller */
+            ValueInformationLength = FIELD_OFFSET(KEY_VALUE_PARTIAL_INFORMATION,
+                Data[0]) + BufferLength;
+            ValueInformation = ExAllocatePool(PagedPool, ValueInformationLength);
+            if (!ValueInformation)
+            {
+                ZwClose(KeyHandle);
+                return STATUS_INSUFFICIENT_RESOURCES;
+            }
 
-         RtlInitUnicodeString(&ValueName, RegistryPropertyName);
-         ValueInformationLength = FIELD_OFFSET(KEY_VALUE_PARTIAL_INFORMATION,
-                                               Data[0]) + BufferLength;
-         ValueInformation = ExAllocatePool(PagedPool, ValueInformationLength);
-         if (ValueInformation == NULL)
-         {
+            /* Read the value */
+            RtlInitUnicodeString(&ValueName, RegistryPropertyName);
+            Status = ZwQueryValueKey(KeyHandle, &ValueName,
+                KeyValuePartialInformation, ValueInformation,
+                ValueInformationLength,
+                &ValueInformationLength);
             ZwClose(KeyHandle);
-            return STATUS_INSUFFICIENT_RESOURCES;
-         }
-
-         Status = ZwQueryValueKey(KeyHandle, &ValueName,
-                                  KeyValuePartialInformation, ValueInformation,
-                                  ValueInformationLength,
-                                  &ValueInformationLength);
-         *ResultLength = ValueInformation->DataLength;
-         ZwClose(KeyHandle);
-
-         if (!NT_SUCCESS(Status))
-         {
-            ExFreePool(ValueInformation);
-            if (Status == STATUS_BUFFER_OVERFLOW)
-               return STATUS_BUFFER_TOO_SMALL;
-            else
-               return Status;
-         }
-
-         /* FIXME: Verify the value (NULL-terminated, correct format). */
 
-         RtlCopyMemory(PropertyBuffer, ValueInformation->Data,
-                       ValueInformation->DataLength);
-         ExFreePool(ValueInformation);
-
-         return STATUS_SUCCESS;
-      }
+            /* Return data */
+            *ResultLength = ValueInformation->DataLength;
 
-   case DevicePropertyBootConfiguration:
-      Length = 0;
-      if (DeviceNode->BootResources->Count != 0)
-      {
-         Length = CM_RESOURCE_LIST_SIZE(DeviceNode->BootResources);
-      }
-      Data = &DeviceNode->BootResources;
-      break;
+            if (!NT_SUCCESS(Status))
+            {
+                DPRINT1("Problem: Status=0x%08x, ResultLength = %d\n", Status, *ResultLength);
+                ExFreePool(ValueInformation);
+                if (Status == STATUS_BUFFER_OVERFLOW)
+                    return STATUS_BUFFER_TOO_SMALL;
+                else
+                    return Status;
+            }
 
-   /* FIXME: use a translated boot configuration instead */
-   case DevicePropertyBootConfigurationTranslated:
-      Length = 0;
-      if (DeviceNode->BootResources->Count != 0)
-      {
-         Length = CM_RESOURCE_LIST_SIZE(DeviceNode->BootResources);
-      }
-      Data = &DeviceNode->BootResources;
-      break;
+            /* FIXME: Verify the value (NULL-terminated, correct format). */
+            RtlCopyMemory(PropertyBuffer, ValueInformation->Data,
+                ValueInformation->DataLength);
+            ExFreePool(ValueInformation);
 
-   case DevicePropertyEnumeratorName:
-      Ptr = wcschr(DeviceNode->InstancePath.Buffer, L'\\');
-      if (Ptr != NULL)
-      {
-         Length = (ULONG)((ULONG_PTR)Ptr - (ULONG_PTR)DeviceNode->InstancePath.Buffer) + sizeof(WCHAR);
-         Data = DeviceNode->InstancePath.Buffer;
-      }
-      else
-      {
-         Length = 0;
-         Data = NULL;
-      }
-      break;
+            return STATUS_SUCCESS;
+        }
 
-   case DevicePropertyPhysicalDeviceObjectName:
-      Length = DeviceNode->InstancePath.Length + sizeof(WCHAR);
-      Data = DeviceNode->InstancePath.Buffer;
-      break;
+    case DevicePropertyBootConfiguration:
+        Length = 0;
+        if (DeviceNode->BootResources->Count != 0)
+        {
+            Length = CM_RESOURCE_LIST_SIZE(DeviceNode->BootResources);
+        }
+        Data = &DeviceNode->BootResources;
+        break;
 
-   default:
-      return STATUS_INVALID_PARAMETER_2;
-  }
+        /* FIXME: use a translated boot configuration instead */
+    case DevicePropertyBootConfigurationTranslated:
+        Length = 0;
+        if (DeviceNode->BootResources->Count != 0)
+        {
+            Length = CM_RESOURCE_LIST_SIZE(DeviceNode->BootResources);
+        }
+        Data = &DeviceNode->BootResources;
+        break;
+
+    case DevicePropertyEnumeratorName:
+        /* A buffer overflow can't happen here, since InstancePath
+        * always contains the enumerator name followed by \\ */
+        Ptr = wcschr(DeviceNode->InstancePath.Buffer, L'\\');
+        ASSERT(Ptr);
+        Length = (Ptr - DeviceNode->InstancePath.Buffer + 1) * sizeof(WCHAR);
+        Data = DeviceNode->InstancePath.Buffer;
+        break;
+
+    case DevicePropertyPhysicalDeviceObjectName:
+        /* InstancePath buffer is NULL terminated, so we can do this */
+        Length = DeviceNode->InstancePath.MaximumLength;
+        Data = DeviceNode->InstancePath.Buffer;
+        break;
+
+    default:
+        return STATUS_INVALID_PARAMETER_2;
+    }
 
-  *ResultLength = Length;
-  if (BufferLength < Length)
-     return STATUS_BUFFER_TOO_SMALL;
-  RtlCopyMemory(PropertyBuffer, Data, Length);
+    /* Prepare returned values */
+    *ResultLength = Length;
+    if (BufferLength < Length)
+        return STATUS_BUFFER_TOO_SMALL;
+    RtlCopyMemory(PropertyBuffer, Data, Length);
 
-  /* Terminate the string */
-  if (DeviceProperty == DevicePropertyEnumeratorName
-     || DeviceProperty == DevicePropertyPhysicalDeviceObjectName)
-  {
-     Ptr = (PWSTR)PropertyBuffer;
-     Ptr[(Length / sizeof(WCHAR)) - 1] = 0;
-  }
+    /* NULL terminate the string (if required) */
+    if (DeviceProperty == DevicePropertyEnumeratorName)
+        ((LPWSTR)PropertyBuffer)[Length / sizeof(WCHAR)] = UNICODE_NULL;
 
-  return STATUS_SUCCESS;
+    return STATUS_SUCCESS;
 }
 
 /*
@@ -704,7 +757,7 @@ IopGetBusTypeGuidIndex(LPGUID BusTypeGuid)
    USHORT i = 0, FoundIndex = 0xFFFF;
    ULONG NewSize;
    PVOID NewList;
-    
+
    /* Acquire the lock */
    ExAcquireFastMutex(&IopBusTypeGuidList->Lock);
 
@@ -775,14 +828,15 @@ Quickie:
 NTSTATUS
 IopCreateDeviceNode(PDEVICE_NODE ParentNode,
                     PDEVICE_OBJECT PhysicalDeviceObject,
+                    PUNICODE_STRING ServiceName,
                     PDEVICE_NODE *DeviceNode)
 {
    PDEVICE_NODE Node;
    NTSTATUS Status;
    KIRQL OldIrql;
 
-   DPRINT("ParentNode 0x%p PhysicalDeviceObject 0x%p\n",
-      ParentNode, PhysicalDeviceObject);
+   DPRINT("ParentNode 0x%p PhysicalDeviceObject 0x%p ServiceName %wZ\n",
+      ParentNode, PhysicalDeviceObject, ServiceName);
 
    Node = (PDEVICE_NODE)ExAllocatePool(NonPagedPool, sizeof(DEVICE_NODE));
    if (!Node)
@@ -794,9 +848,10 @@ IopCreateDeviceNode(PDEVICE_NODE ParentNode,
 
    if (!PhysicalDeviceObject)
    {
-      Status = PnpRootCreateDevice(&PhysicalDeviceObject);
+      Status = PnpRootCreateDevice(ServiceName, &PhysicalDeviceObject);
       if (!NT_SUCCESS(Status))
       {
+         DPRINT1("PnpRootCreateDevice() failed with status 0x%08X\n", Status);
          ExFreePool(Node);
          return Status;
       }
@@ -922,9 +977,8 @@ IopInitiatePnpIrp(PDEVICE_OBJECT DeviceObject,
       &Event,
       IoStatusBlock);
 
-   /* PNP IRPs are always initialized with a status code of
-   STATUS_NOT_IMPLEMENTED */
-   Irp->IoStatus.Status = STATUS_NOT_IMPLEMENTED;
+   /* PNP IRPs are initialized with a status code of STATUS_NOT_SUPPORTED */
+   Irp->IoStatus.Status = STATUS_NOT_SUPPORTED;
    Irp->IoStatus.Information = 0;
 
    IrpSp = IoGetNextIrpStackLocation(Irp);
@@ -1016,82 +1070,110 @@ IopTraverseDeviceTree(PDEVICETREE_TRAVERSE_CONTEXT Context)
 }
 
 
-static
+/*
+ * IopCreateDeviceKeyPath
+ *
+ * Creates a registry key
+ *
+ * Parameters
+ *    RegistryPath
+ *        Name of the key to be created.
+ *    Handle
+ *        Handle to the newly created key
+ *
+ * Remarks
+ *     This method can create nested trees, so parent of RegistryPath can
+ *     be not existant, and will be created if needed.
+ */
 NTSTATUS
-IopCreateDeviceKeyPath(PWSTR Path,
-                       PHANDLE Handle)
+NTAPI
+IopCreateDeviceKeyPath(IN PCUNICODE_STRING RegistryPath,
+                       OUT PHANDLE Handle)
 {
-   OBJECT_ATTRIBUTES ObjectAttributes;
-   WCHAR KeyBuffer[MAX_PATH];
-   UNICODE_STRING KeyName;
-   HANDLE KeyHandle;
-   NTSTATUS Status;
-   PWCHAR Current;
-   PWCHAR Next;
+    UNICODE_STRING EnumU = RTL_CONSTANT_STRING(ENUM_ROOT);
+    HANDLE hParent = NULL, hKey;
+    OBJECT_ATTRIBUTES ObjectAttributes;
+    UNICODE_STRING KeyName;
+    LPCWSTR Current, Last;
+    ULONG dwLength;
+    NTSTATUS Status;
 
-   *Handle = NULL;
+    /* Assume failure */
+    *Handle = NULL;
 
-   if (_wcsnicmp(Path, L"\\Registry\\", 10) != 0)
-   {
-      return STATUS_INVALID_PARAMETER;
-   }
+    /* Open root key for device instances */
+    InitializeObjectAttributes(&ObjectAttributes,
+                               &EnumU,
+                               OBJ_CASE_INSENSITIVE,
+                               NULL,
+                               NULL);
+    Status = ZwOpenKey(&hParent,
+                       KEY_CREATE_SUB_KEY,
+                       &ObjectAttributes);
+    if (!NT_SUCCESS(Status))
+    {
+        DPRINT1("ZwOpenKey('%wZ') failed with status 0x%08lx\n", &EnumU, Status);
+        return Status;
+    }
 
-   wcsncpy (KeyBuffer, Path, MAX_PATH-1);
+    Current = KeyName.Buffer = RegistryPath->Buffer;
+    Last = &RegistryPath->Buffer[RegistryPath->Length / sizeof(WCHAR)];
 
-   /* Skip \\Registry\\ */
-   Current = KeyBuffer;
-   Current = wcschr (Current, L'\\') + 1;
-   Current = wcschr (Current, L'\\') + 1;
+    /* Go up to the end of the string */
+    while (Current <= Last)
+    {
+        if (Current != Last && *Current != '\\')
+        {
+            /* Not the end of the string and not a separator */
+            Current++;
+            continue;
+        }
 
-   while (TRUE)
-   {
-      Next = wcschr (Current, L'\\');
-      if (Next == NULL)
-      {
-         /* The end */
-      }
-      else
-      {
-         *Next = 0;
-      }
+        /* Prepare relative key name */
+        dwLength = (ULONG_PTR)Current - (ULONG_PTR)KeyName.Buffer;
+        KeyName.MaximumLength = KeyName.Length = dwLength;
+        DPRINT("Create '%wZ'\n", &KeyName);
 
-      RtlInitUnicodeString (&KeyName, KeyBuffer);
-      InitializeObjectAttributes (&ObjectAttributes,
-                                  &KeyName,
-                                  OBJ_CASE_INSENSITIVE,
-                                  NULL,
-                                  NULL);
+        /* Open key */
+        InitializeObjectAttributes(&ObjectAttributes,
+                                   &KeyName,
+                                   OBJ_CASE_INSENSITIVE,
+                                   hParent,
+                                   NULL);
+        Status = ZwCreateKey(&hKey,
+                             Current == Last ? KEY_ALL_ACCESS : KEY_CREATE_SUB_KEY,
+                             &ObjectAttributes,
+                             0,
+                             NULL,
+                             0,
+                             NULL);
 
-      DPRINT("Create '%S'\n", KeyName.Buffer);
+        /* Close parent key handle, we don't need it anymore */
+        if (hParent)
+            ZwClose(hParent);
 
-      Status = ZwCreateKey (&KeyHandle,
-                            KEY_ALL_ACCESS,
-                            &ObjectAttributes,
-                            0,
-                            NULL,
-                            0,
-                            NULL);
-      if (!NT_SUCCESS (Status))
-      {
-         DPRINT ("ZwCreateKey() failed with status %x\n", Status);
-         return Status;
-      }
+        /* Key opening/creating failed? */
+        if (!NT_SUCCESS(Status))
+        {
+            DPRINT1("ZwCreateKey('%wZ') failed with status 0x%08lx\n", &KeyName, Status);
+            return Status;
+        }
 
-      if (Next == NULL)
-      {
-         *Handle = KeyHandle;
-         return STATUS_SUCCESS;
-      }
-      else
-      {
-         ZwClose (KeyHandle);
-         *Next = L'\\';
-      }
+        /* Check if it is the end of the string */
+        if (Current == Last)
+        {
+            /* Yes, return success */
+            *Handle = hKey;
+            return STATUS_SUCCESS;
+        }
 
-      Current = Next + 1;
-   }
+        /* Start with this new parent key */
+        hParent = hKey;
+        Current++;
+        KeyName.Buffer = (LPWSTR)Current;
+    }
 
-   return STATUS_UNSUCCESSFUL;
+    return STATUS_UNSUCCESSFUL;
 }
 
 
@@ -1179,41 +1261,6 @@ IopSetDeviceInstanceData(HANDLE InstanceKey,
                            sizeof(DefaultConfigFlags));
   }
 
-#if 0
-  if (DeviceNode->PhysicalDeviceObject != NULL)
-  {
-    /* Create the 'Control' key */
-    RtlInitUnicodeString(&KeyName,
-                        L"Control");
-    InitializeObjectAttributes(&ObjectAttributes,
-                              &KeyName,
-                              OBJ_CASE_INSENSITIVE | OBJ_OPENIF,
-                              InstanceKey,
-                              NULL);
-    Status = ZwCreateKey(&LogConfKey,
-                        KEY_ALL_ACCESS,
-                        &ObjectAttributes,
-                        0,
-                        NULL,
-                        REG_OPTION_VOLATILE,
-                        NULL);
-    if (NT_SUCCESS(Status))
-    {
-      ULONG Reference = (ULONG)DeviceNode->PhysicalDeviceObject;
-      RtlInitUnicodeString(&KeyName,
-                          L"DeviceReference");
-      Status = ZwSetValueKey(LogConfKey,
-                            &KeyName,
-                            0,
-                            REG_DWORD,
-                            &Reference,
-                            sizeof(PVOID));
-
-      ZwClose(LogConfKey);
-    }
-  }
-#endif
-
   DPRINT("IopSetDeviceInstanceData() done\n");
 
   return STATUS_SUCCESS;
@@ -1246,8 +1293,6 @@ IopAssignDeviceResources(
     * Actually, use the BootResources if provided, else the resource list #0
     */
 
-   IopDeviceNodeSetFlag(DeviceNode, DNF_ASSIGNING_RESOURCES);
-
    if (DeviceNode->BootResources)
    {
       /* Browse the boot resources to know if we have some custom structures */
@@ -1255,11 +1300,6 @@ IopAssignDeviceResources(
       for (i = 0; i < DeviceNode->BootResources->Count; i++)
       {
          pPartialResourceList = &DeviceNode->BootResources->List[i].PartialResourceList;
-         if (pPartialResourceList->Version != 1 || pPartialResourceList->Revision != 1)
-         {
-            Status = STATUS_REVISION_MISMATCH;
-            goto ByeBye;
-         }
          Size += FIELD_OFFSET(CM_FULL_RESOURCE_DESCRIPTOR, PartialResourceList.PartialDescriptors)
             + pPartialResourceList->Count * sizeof(CM_PARTIAL_RESOURCE_DESCRIPTOR);
          for (j = 0; j < pPartialResourceList->Count; j++)
@@ -1282,8 +1322,6 @@ IopAssignDeviceResources(
    }
 
    /* Ok, here, we have to use the device requirement list */
-   IopDeviceNodeSetFlag(DeviceNode, DNF_ASSIGNING_RESOURCES);
-
    ResourceList = &DeviceNode->ResourceRequirements->List[0];
    if (ResourceList->Version != 1 || ResourceList->Revision != 1)
    {
@@ -1584,7 +1622,11 @@ IopGetParentIdPrefix(PDEVICE_NODE DeviceNode,
     * instance path, the following test is required :(
     */
    if (DeviceNode->Parent->InstancePath.Length == 0)
+   {
+      DPRINT1("Parent of %wZ has NULL Instance path, please report!\n",
+          &DeviceNode->InstancePath);
       return STATUS_UNSUCCESSFUL;
+   }
 
    /* 1. Try to retrieve ParentIdPrefix from registry */
    KeyNameBufferLength = FIELD_OFFSET(KEY_VALUE_PARTIAL_INFORMATION, Data[0]) + MAX_PATH * sizeof(WCHAR);
@@ -1831,7 +1873,7 @@ IopActionInterrogateDeviceStack(PDEVICE_NODE DeviceNode,
       (49 * sizeof(WCHAR)) + DeviceNode->InstancePath.Length);
    wcscpy(KeyBuffer, L"\\Registry\\Machine\\System\\CurrentControlSet\\Enum\\");
    wcscat(KeyBuffer, DeviceNode->InstancePath.Buffer);
-   Status = IopCreateDeviceKeyPath(KeyBuffer, &InstanceKey);
+   Status = IopCreateDeviceKeyPath(/*KeyBuffer*/&DeviceNode->InstancePath, &InstanceKey);
    ExFreePool(KeyBuffer);
    if (!NT_SUCCESS(Status))
    {
@@ -1951,7 +1993,6 @@ IopActionInterrogateDeviceStack(PDEVICE_NODE DeviceNode,
       DPRINT("IopInitiatePnpIrp() failed (Status %x)\n", Status);
    }
 
-
    DPRINT("Sending IRP_MN_QUERY_DEVICE_TEXT.DeviceTextDescription to device stack\n");
 
    Stack.Parameters.QueryDeviceText.DeviceTextType = DeviceTextDescription;
@@ -2102,33 +2143,168 @@ IopActionInterrogateDeviceStack(PDEVICE_NODE DeviceNode,
 
    ZwClose(InstanceKey);
 
-   IopDeviceNodeSetFlag(DeviceNode, DNF_ASSIGNING_RESOURCES);
-   Status = IopAssignDeviceResources(DeviceNode, &RequiredLength);
-   if (NT_SUCCESS(Status))
-   {
-      Status = IopTranslateDeviceResources(DeviceNode, RequiredLength);
-      if (NT_SUCCESS(Status))
-      {
-         IopDeviceNodeSetFlag(DeviceNode, DNF_RESOURCE_ASSIGNED);
-      }
-      else
-      {
-         DPRINT("IopTranslateDeviceResources() failed (Status 0x08lx)\n", Status);
-      }
-   }
-   else
+   IopDeviceNodeSetFlag(DeviceNode, DNF_PROCESSED);
+
+   if (!IopDeviceNodeHasFlag(DeviceNode, DNF_LEGACY_DRIVER))
    {
-      DPRINT("IopAssignDeviceResources() failed (Status 0x08lx)\n", Status);
+      /* Report the device to the user-mode pnp manager */
+      IopQueueTargetDeviceEvent(&GUID_DEVICE_ARRIVAL,
+                                &DeviceNode->InstancePath);
    }
-   IopDeviceNodeClearFlag(DeviceNode, DNF_ASSIGNING_RESOURCES);
 
-   DeviceNode->Flags |= DNF_PROCESSED;
+   return STATUS_SUCCESS;
+}
 
-   /* Report the device to the user-mode pnp manager */
-   IopQueueTargetDeviceEvent(&GUID_DEVICE_ARRIVAL,
-                             &DeviceNode->InstancePath);
+/*
+ * @implemented
+ */
+VOID
+NTAPI
+IoSynchronousInvalidateDeviceRelations(
+    IN PDEVICE_OBJECT DeviceObject,
+    IN DEVICE_RELATION_TYPE Type)
+{
+    PDEVICE_NODE DeviceNode = IopGetDeviceNode(DeviceObject);
+    DEVICETREE_TRAVERSE_CONTEXT Context;
+    PDEVICE_RELATIONS DeviceRelations;
+    IO_STATUS_BLOCK IoStatusBlock;
+    PDEVICE_NODE ChildDeviceNode;
+    IO_STACK_LOCATION Stack;
+    BOOLEAN BootDrivers;
+    OBJECT_ATTRIBUTES ObjectAttributes;
+    UNICODE_STRING LinkName = RTL_CONSTANT_STRING(L"\\SystemRoot");
+    HANDLE Handle;
+    NTSTATUS Status;
+    ULONG i;
 
-   return STATUS_SUCCESS;
+    DPRINT("DeviceObject 0x%p\n", DeviceObject);
+
+    DPRINT("Sending IRP_MN_QUERY_DEVICE_RELATIONS to device stack\n");
+
+    Stack.Parameters.QueryDeviceRelations.Type = Type;
+
+    Status = IopInitiatePnpIrp(
+        DeviceObject,
+        &IoStatusBlock,
+        IRP_MN_QUERY_DEVICE_RELATIONS,
+        &Stack);
+    if (!NT_SUCCESS(Status))
+    {
+        DPRINT("IopInitiatePnpIrp() failed with status 0x%08lx\n", Status);
+        return;
+    }
+
+    DeviceRelations = (PDEVICE_RELATIONS)IoStatusBlock.Information;
+
+    if (!DeviceRelations || DeviceRelations->Count <= 0)
+    {
+        DPRINT("No PDOs\n");
+        if (DeviceRelations)
+        {
+            ExFreePool(DeviceRelations);
+        }
+        return;
+    }
+
+    DPRINT("Got %d PDOs\n", DeviceRelations->Count);
+
+    /*
+     * Create device nodes for all discovered devices
+     */
+    for (i = 0; i < DeviceRelations->Count; i++)
+    {
+        if (IopGetDeviceNode(DeviceRelations->Objects[i]) != NULL)
+        {
+            ObDereferenceObject(DeviceRelations->Objects[i]);
+            continue;
+        }
+        Status = IopCreateDeviceNode(
+            DeviceNode,
+            DeviceRelations->Objects[i],
+            NULL,
+            &ChildDeviceNode);
+        DeviceNode->Flags |= DNF_ENUMERATED;
+        if (!NT_SUCCESS(Status))
+        {
+            DPRINT("No resources\n");
+            for (i = 0; i < DeviceRelations->Count; i++)
+                ObDereferenceObject(DeviceRelations->Objects[i]);
+            ExFreePool(DeviceRelations);
+            return;
+        }
+    }
+    ExFreePool(DeviceRelations);
+
+    /*
+     * Retrieve information about all discovered children from the bus driver
+     */
+    IopInitDeviceTreeTraverseContext(
+        &Context,
+        DeviceNode,
+        IopActionInterrogateDeviceStack,
+        DeviceNode);
+
+    Status = IopTraverseDeviceTree(&Context);
+    if (!NT_SUCCESS(Status))
+    {
+        DPRINT("IopTraverseDeviceTree() failed with status 0x%08lx\n", Status);
+        return;
+    }
+
+    /*
+     * Retrieve configuration from the registry for discovered children
+     */
+    IopInitDeviceTreeTraverseContext(
+        &Context,
+        DeviceNode,
+        IopActionConfigureChildServices,
+        DeviceNode);
+
+    Status = IopTraverseDeviceTree(&Context);
+    if (!NT_SUCCESS(Status))
+    {
+        DPRINT("IopTraverseDeviceTree() failed with status 0x%08lx\n", Status);
+        return;
+    }
+
+    /*
+     * Get the state of the system boot. If the \\SystemRoot link isn't
+     * created yet, we will assume that it's possible to load only boot
+     * drivers.
+     */
+    InitializeObjectAttributes(
+        &ObjectAttributes,
+        &LinkName,
+        0,
+        NULL,
+        NULL);
+    Status = ZwOpenFile(
+        &Handle,
+        FILE_ALL_ACCESS,
+        &ObjectAttributes,
+        &IoStatusBlock,
+        0,
+        0);
+     if (NT_SUCCESS(Status))
+     {
+         BootDrivers = FALSE;
+         ZwClose(Handle);
+     }
+     else
+         BootDrivers = TRUE;
+
+    /*
+     * Initialize services for discovered children. Only boot drivers will
+     * be loaded from boot driver!
+     */
+    Status = IopInitializePnpServices(DeviceNode, BootDrivers);
+    if (!NT_SUCCESS(Status))
+    {
+        DPRINT("IopInitializePnpServices() failed with status 0x%08lx\n", Status);
+        return;
+    }
+
+    DPRINT("IopInvalidateDeviceRelations() finished\n");
 }
 
 /*
@@ -2158,7 +2334,6 @@ IopActionConfigureChildServices(PDEVICE_NODE DeviceNode,
    PDEVICE_NODE ParentDeviceNode;
    PUNICODE_STRING Service;
    UNICODE_STRING ClassGUID;
-   UNICODE_STRING NullString = RTL_CONSTANT_STRING(L"");
    NTSTATUS Status;
 
    DPRINT("IopActionConfigureChildServices(%p, %p)\n", DeviceNode, Context);
@@ -2206,14 +2381,14 @@ IopActionConfigureChildServices(PDEVICE_NODE DeviceNode,
       RtlInitUnicodeString(&ClassGUID, NULL);
 
       QueryTable[0].Name = L"Service";
-      QueryTable[0].Flags = RTL_QUERY_REGISTRY_DIRECT;
+      QueryTable[0].Flags = RTL_QUERY_REGISTRY_DIRECT | RTL_QUERY_REGISTRY_REQUIRED;
       QueryTable[0].EntryContext = Service;
 
       QueryTable[1].Name = L"ClassGUID";
       QueryTable[1].Flags = RTL_QUERY_REGISTRY_DIRECT;
       QueryTable[1].EntryContext = &ClassGUID;
       QueryTable[1].DefaultType = REG_SZ;
-      QueryTable[1].DefaultData = &NullString;
+      QueryTable[1].DefaultData = L"";
       QueryTable[1].DefaultLength = 0;
 
       RtlAppendUnicodeToString(&RegKey, L"\\Registry\\Machine\\System\\CurrentControlSet\\Enum\\");
@@ -2224,10 +2399,9 @@ IopActionConfigureChildServices(PDEVICE_NODE DeviceNode,
 
       if (!NT_SUCCESS(Status))
       {
-         DPRINT("RtlQueryRegistryValues() failed (Status %x)\n", Status);
          /* FIXME: Log the error */
-         CPRINT("Could not retrieve configuration for device %S (Status %x)\n",
-            DeviceNode->InstancePath.Buffer, Status);
+         DPRINT("Could not retrieve configuration for device %wZ (Status 0x%08x)\n",
+            &DeviceNode->InstancePath, Status);
          IopDeviceNodeSetFlag(DeviceNode, DNF_DISABLED);
          return STATUS_SUCCESS;
       }
@@ -2241,7 +2415,7 @@ IopActionConfigureChildServices(PDEVICE_NODE DeviceNode,
             /* Device has a ClassGUID value, but no Service value.
              * Suppose it is using the NULL driver, so state the
              * device is started */
-            DPRINT("%wZ is using NULL driver\n", &DeviceNode->InstancePath);
+            DPRINT1("%wZ is using NULL driver\n", &DeviceNode->InstancePath);
             IopDeviceNodeSetFlag(DeviceNode, DNF_STARTED);
             DeviceNode->Flags |= DN_STARTED;
          }
@@ -2321,37 +2495,63 @@ IopActionInitChildServices(PDEVICE_NODE DeviceNode,
       PLDR_DATA_TABLE_ENTRY ModuleObject;
       PDRIVER_OBJECT DriverObject;
 
-      Status = IopLoadServiceModule(&DeviceNode->ServiceName, &ModuleObject);
-      if (NT_SUCCESS(Status) || Status == STATUS_IMAGE_ALREADY_LOADED)
+      /* Get existing DriverObject pointer (in case the driver has
+         already been loaded and initialized) */
+      Status = IopGetDriverObject(
+          &DriverObject,
+          &DeviceNode->ServiceName,
+          FALSE);
+
+      if (!NT_SUCCESS(Status))
       {
-         if (Status != STATUS_IMAGE_ALREADY_LOADED)
+         /* Driver is not initialized, try to load it */
+         Status = IopLoadServiceModule(&DeviceNode->ServiceName, &ModuleObject);
+
+         if (NT_SUCCESS(Status) || Status == STATUS_IMAGE_ALREADY_LOADED)
          {
-            DeviceNode->Flags |= DN_DRIVER_LOADED;
-            Status = IopInitializeDriverModule(DeviceNode, ModuleObject,
-               &DeviceNode->ServiceName, FALSE, &DriverObject);
+            /* STATUS_IMAGE_ALREADY_LOADED means this driver
+               was loaded by the bootloader */
+            if ((Status != STATUS_IMAGE_ALREADY_LOADED) ||
+                (Status == STATUS_IMAGE_ALREADY_LOADED && !DriverObject))
+            {
+               /* Initialize the driver */
+               Status = IopInitializeDriverModule(DeviceNode, ModuleObject,
+                  &DeviceNode->ServiceName, FALSE, &DriverObject);
+            }
+            else
+            {
+               Status = STATUS_SUCCESS;
+            }
          }
          else
          {
-            /* get existing DriverObject pointer */
-            Status = IopGetDriverObject(
-               &DriverObject,
-               &DeviceNode->ServiceName,
-               FALSE);
+            DPRINT1("IopLoadServiceModule(%wZ) failed with status 0x%08x\n",
+                    &DeviceNode->ServiceName, Status);
          }
+      }
+
+      /* Driver is loaded and initialized at this point */
+      if (NT_SUCCESS(Status))
+      {
+         /* We have a driver for this DeviceNode */
+         DeviceNode->Flags |= DN_DRIVER_LOADED;
+         /* Attach lower level filter drivers. */
+         IopAttachFilterDrivers(DeviceNode, TRUE);
+         /* Initialize the function driver for the device node */
+         Status = IopInitializeDevice(DeviceNode, DriverObject);
+
          if (NT_SUCCESS(Status))
          {
-            /* Attach lower level filter drivers. */
-            IopAttachFilterDrivers(DeviceNode, TRUE);
-            /* Initialize the function driver for the device node */
-            Status = IopInitializeDevice(DeviceNode, DriverObject);
-            if (NT_SUCCESS(Status))
-            {
-               /* Attach upper level filter drivers. */
-               IopAttachFilterDrivers(DeviceNode, FALSE);
-               IopDeviceNodeSetFlag(DeviceNode, DNF_STARTED);
+            /* Attach upper level filter drivers. */
+            IopAttachFilterDrivers(DeviceNode, FALSE);
+            IopDeviceNodeSetFlag(DeviceNode, DNF_STARTED);
 
-               Status = IopStartDevice(DeviceNode);
-            }
+            Status = IopStartDevice(DeviceNode);
+         }
+         else
+         {
+            DPRINT1("IopInitializeDevice(%wZ) failed with status 0x%08x\n",
+                    &DeviceNode->InstancePath, Status);
          }
       }
       else
@@ -2368,10 +2568,11 @@ IopActionInitChildServices(PDEVICE_NODE DeviceNode,
               DeviceNode->ServiceName.Buffer, Status);
          }
       }
-   } else
+   }
+   else
    {
-      DPRINT("Service %S is disabled or already initialized\n",
-         DeviceNode->ServiceName.Buffer);
+      DPRINT("Device %wZ is disabled or already initialized\n",
+         &DeviceNode->InstancePath);
    }
 
    return STATUS_SUCCESS;
@@ -2449,171 +2650,10 @@ IopInitializePnpServices(IN PDEVICE_NODE DeviceNode,
    return IopTraverseDeviceTree(&Context);
 }
 
-/* Invalidate device list enumerated by a device node.
- * The call can be make synchronous by defining the Event field
- * of the INVALIDATE_DEVICE_RELATION_DATA structure
- */
-static VOID NTAPI
-IopInvalidateDeviceRelations(
-    IN PDEVICE_OBJECT DeviceObject,
-    IN PVOID InvalidateContext) /* PINVALIDATE_DEVICE_RELATION_DATA */
-{
-    PINVALIDATE_DEVICE_RELATION_DATA Data = InvalidateContext;
-    PDEVICE_NODE DeviceNode = IopGetDeviceNode(DeviceObject);
-    PKEVENT Event = Data->Event;
-    DEVICETREE_TRAVERSE_CONTEXT Context;
-    PDEVICE_RELATIONS DeviceRelations;
-    IO_STATUS_BLOCK IoStatusBlock;
-    PDEVICE_NODE ChildDeviceNode;
-    IO_STACK_LOCATION Stack;
-    BOOLEAN BootDrivers;
-    OBJECT_ATTRIBUTES ObjectAttributes;
-    UNICODE_STRING LinkName = RTL_CONSTANT_STRING(L"\\SystemRoot");
-    HANDLE Handle;
-    NTSTATUS Status;
-    ULONG i;
-
-    DPRINT("DeviceObject 0x%p\n", DeviceObject);
-
-    DPRINT("Sending IRP_MN_QUERY_DEVICE_RELATIONS to device stack\n");
-
-    Stack.Parameters.QueryDeviceRelations.Type = Data->Type;
-
-    Status = IopInitiatePnpIrp(
-        DeviceObject,
-        &IoStatusBlock,
-        IRP_MN_QUERY_DEVICE_RELATIONS,
-        &Stack);
-    if (!NT_SUCCESS(Status))
-    {
-        DPRINT("IopInitiatePnpIrp() failed with status 0x%08lx\n", Status);
-        goto cleanup;
-    }
-
-    DeviceRelations = (PDEVICE_RELATIONS)IoStatusBlock.Information;
-
-    if (!DeviceRelations || DeviceRelations->Count <= 0)
-    {
-        DPRINT("No PDOs\n");
-        if (DeviceRelations)
-        {
-            ExFreePool(DeviceRelations);
-        }
-        Status = STATUS_SUCCESS;
-        goto cleanup;
-    }
-
-    DPRINT("Got %d PDOs\n", DeviceRelations->Count);
-
-    /*
-     * Create device nodes for all discovered devices
-     */
-    for (i = 0; i < DeviceRelations->Count; i++)
-    {
-        Status = IopCreateDeviceNode(
-            DeviceNode,
-            DeviceRelations->Objects[i],
-            &ChildDeviceNode);
-        DeviceNode->Flags |= DNF_ENUMERATED;
-        if (!NT_SUCCESS(Status))
-        {
-            DPRINT("No resources\n");
-            for (i = 0; i < DeviceRelations->Count; i++)
-                ObDereferenceObject(DeviceRelations->Objects[i]);
-            ExFreePool(DeviceRelations);
-            Status = STATUS_NO_MEMORY;
-            goto cleanup;
-        }
-    }
-    ExFreePool(DeviceRelations);
-
-    /*
-     * Retrieve information about all discovered children from the bus driver
-     */
-    IopInitDeviceTreeTraverseContext(
-        &Context,
-        DeviceNode,
-        IopActionInterrogateDeviceStack,
-        DeviceNode);
-
-    Status = IopTraverseDeviceTree(&Context);
-    if (!NT_SUCCESS(Status))
-    {
-        DPRINT("IopTraverseDeviceTree() failed with status 0x%08lx\n", Status);
-        goto cleanup;
-    }
-
-    /*
-     * Retrieve configuration from the registry for discovered children
-     */
-    IopInitDeviceTreeTraverseContext(
-        &Context,
-        DeviceNode,
-        IopActionConfigureChildServices,
-        DeviceNode);
-
-    Status = IopTraverseDeviceTree(&Context);
-    if (!NT_SUCCESS(Status))
-    {
-        DPRINT("IopTraverseDeviceTree() failed with status 0x%08lx\n", Status);
-        goto cleanup;
-    }
-
-    /*
-     * Get the state of the system boot. If the \\SystemRoot link isn't
-     * created yet, we will assume that it's possible to load only boot
-     * drivers.
-     */
-    InitializeObjectAttributes(
-        &ObjectAttributes,
-        &LinkName,
-        0,
-        NULL,
-        NULL);
-    Status = ZwOpenFile(
-        &Handle,
-        FILE_ALL_ACCESS,
-        &ObjectAttributes,
-        &IoStatusBlock,
-        0,
-        0);
-     if (NT_SUCCESS(Status))
-     {
-         BootDrivers = FALSE;
-         ZwClose(Handle);
-     }
-     else
-         BootDrivers = TRUE;
-
-    /*
-     * Initialize services for discovered children. Only boot drivers will
-     * be loaded from boot driver!
-     */
-    Status = IopInitializePnpServices(DeviceNode, BootDrivers);
-    if (!NT_SUCCESS(Status))
-    {
-        DPRINT("IopInitializePnpServices() failed with status 0x%08lx\n", Status);
-        goto cleanup;
-    }
-
-    DPRINT("IopInvalidateDeviceRelations() finished\n");
-    Status = STATUS_SUCCESS;
-
-cleanup:
-    IoFreeWorkItem(Data->WorkItem);
-    if (Event)
-    {
-        Data->Status = Status;
-        KeSetEvent(Event, 0, FALSE);
-    }
-    else
-        ExFreePool(Data);
-}
-
 static NTSTATUS INIT_FUNCTION
 IopEnumerateDetectedDevices(
    IN HANDLE hBaseKey,
-   IN PUNICODE_STRING RelativePath,
+   IN PUNICODE_STRING RelativePath OPTIONAL,
    IN HANDLE hRootKey,
    IN BOOLEAN EnumerateSubKeys,
    IN PCM_FULL_RESOURCE_DESCRIPTOR ParentBootResources,
@@ -2643,12 +2683,14 @@ IopEnumerateDetectedDevices(
    ULONG BootResourcesLength;
    NTSTATUS Status;
 
-   const UNICODE_STRING IdentifierPci = RTL_CONSTANT_STRING(L"PCI BIOS");
+   const UNICODE_STRING IdentifierPci = RTL_CONSTANT_STRING(L"PCI");
    UNICODE_STRING HardwareIdPci = RTL_CONSTANT_STRING(L"*PNP0A03\0");
    static ULONG DeviceIndexPci = 0;
-   /*const UNICODE_STRING IdentifierAcpi = RTL_CONSTANT_STRING(L"ACPI BIOS");
+#ifdef ENABLE_ACPI
+   const UNICODE_STRING IdentifierAcpi = RTL_CONSTANT_STRING(L"ACPI BIOS");
    UNICODE_STRING HardwareIdAcpi = RTL_CONSTANT_STRING(L"*PNP0C08\0");
-   static ULONG DeviceIndexAcpi = 0;*/
+   static ULONG DeviceIndexAcpi = 0;
+#endif
    const UNICODE_STRING IdentifierSerial = RTL_CONSTANT_STRING(L"SerialController");
    UNICODE_STRING HardwareIdSerial = RTL_CONSTANT_STRING(L"*PNP0501\0");
    static ULONG DeviceIndexSerial = 0;
@@ -2658,16 +2700,22 @@ IopEnumerateDetectedDevices(
    const UNICODE_STRING IdentifierMouse = RTL_CONSTANT_STRING(L"PointerController");
    UNICODE_STRING HardwareIdMouse = RTL_CONSTANT_STRING(L"*PNP0F13\0");
    static ULONG DeviceIndexMouse = 0;
+   UNICODE_STRING HardwareIdKey;
    PUNICODE_STRING pHardwareId;
    ULONG DeviceIndex = 0;
 
-   InitializeObjectAttributes(&ObjectAttributes, RelativePath, OBJ_KERNEL_HANDLE, hBaseKey, NULL);
-   Status = ZwOpenKey(&hDevicesKey, KEY_ENUMERATE_SUB_KEYS, &ObjectAttributes);
-   if (!NT_SUCCESS(Status))
-   {
-      DPRINT("ZwOpenKey() failed with status 0x%08lx\n", Status);
-      goto cleanup;
-   }
+    if (RelativePath)
+    {
+        InitializeObjectAttributes(&ObjectAttributes, RelativePath, OBJ_KERNEL_HANDLE, hBaseKey, NULL);
+        Status = ZwOpenKey(&hDevicesKey, KEY_ENUMERATE_SUB_KEYS, &ObjectAttributes);
+        if (!NT_SUCCESS(Status))
+        {
+            DPRINT("ZwOpenKey() failed with status 0x%08lx\n", Status);
+            goto cleanup;
+        }
+    }
+    else
+        hDevicesKey = hBaseKey;
 
    pDeviceInformation = ExAllocatePool(PagedPool, DeviceInfoLength);
    if (!pDeviceInformation)
@@ -2755,11 +2803,6 @@ IopEnumerateDetectedDevices(
          DPRINT("Wrong registry type: got 0x%lx, expected 0x%lx\n", pValueInformation->Type, REG_FULL_RESOURCE_DESCRIPTOR);
          goto nextdevice;
       }
-      else if (((PCM_FULL_RESOURCE_DESCRIPTOR)pValueInformation->Data)->PartialResourceList.Count == 0)
-      {
-         BootResources = ParentBootResources;
-         BootResourcesLength = ParentBootResourcesLength;
-      }
       else
       {
          static const ULONG Header = FIELD_OFFSET(CM_FULL_RESOURCE_DESCRIPTOR, PartialResourceList.PartialDescriptors);
@@ -2869,6 +2912,7 @@ IopEnumerateDetectedDevices(
             DPRINT("ZwQueryValueKey() failed with status 0x%08lx\n", Status);
             goto nextdevice;
          }
+         ValueName.Length = ValueName.MaximumLength = 0;
       }
       else if (pValueInformation->Type != REG_SZ)
       {
@@ -2884,17 +2928,17 @@ IopEnumerateDetectedDevices(
             ValueName.Length -= sizeof(WCHAR);
       }
 
-      if (RtlCompareUnicodeString(RelativePath, &IdentifierSerial, FALSE) == 0)
+      if (RelativePath && RtlCompareUnicodeString(RelativePath, &IdentifierSerial, FALSE) == 0)
       {
          pHardwareId = &HardwareIdSerial;
          DeviceIndex = DeviceIndexSerial++;
       }
-      else if (RtlCompareUnicodeString(RelativePath, &IdentifierKeyboard, FALSE) == 0)
+      else if (RelativePath && RtlCompareUnicodeString(RelativePath, &IdentifierKeyboard, FALSE) == 0)
       {
          pHardwareId = &HardwareIdKeyboard;
          DeviceIndex = DeviceIndexKeyboard++;
       }
-      else if (RtlCompareUnicodeString(RelativePath, &IdentifierMouse, FALSE) == 0)
+      else if (RelativePath && RtlCompareUnicodeString(RelativePath, &IdentifierMouse, FALSE) == 0)
       {
          pHardwareId = &HardwareIdMouse;
          DeviceIndex = DeviceIndexMouse++;
@@ -2907,11 +2951,13 @@ IopEnumerateDetectedDevices(
             pHardwareId = &HardwareIdPci;
             DeviceIndex = DeviceIndexPci++;
          }
-         /*else if (RtlCompareUnicodeString(&ValueName, &IdentifierAcpi, FALSE) == 0)
+#ifdef ENABLE_ACPI
+         else if (RtlCompareUnicodeString(&ValueName, &IdentifierAcpi, FALSE) == 0)
          {
             pHardwareId = &HardwareIdAcpi;
             DeviceIndex = DeviceIndexAcpi++;
-         }*/
+         }
+#endif
          else
          {
             /* Unknown device */
@@ -2922,12 +2968,16 @@ IopEnumerateDetectedDevices(
       else
       {
          /* Unknown key path */
-         DPRINT("Unknown key path %wZ\n", RelativePath);
+         DPRINT("Unknown key path '%wZ'\n", RelativePath);
          goto nextdevice;
       }
 
+      /* Prepare hardware id key (hardware id value without final \0) */
+      HardwareIdKey = *pHardwareId;
+      HardwareIdKey.Length -= sizeof(UNICODE_NULL);
+
       /* Add the detected device to Root key */
-      InitializeObjectAttributes(&ObjectAttributes, pHardwareId, OBJ_KERNEL_HANDLE, hRootKey, NULL);
+      InitializeObjectAttributes(&ObjectAttributes, &HardwareIdKey, OBJ_KERNEL_HANDLE, hRootKey, NULL);
       Status = ZwCreateKey(
          &hLevel1Key,
          KEY_CREATE_SUB_KEY,
@@ -2958,7 +3008,7 @@ IopEnumerateDetectedDevices(
          DPRINT("ZwCreateKey() failed with status 0x%08lx\n", Status);
          goto nextdevice;
       }
-      DPRINT("Found %wZ #%lu (%wZ)\n", &ValueName, DeviceIndex, pHardwareId);
+      DPRINT("Found %wZ #%lu (%wZ)\n", &ValueName, DeviceIndex, &HardwareIdKey);
       Status = ZwSetValueKey(hLevel2Key, &DeviceDescU, 0, REG_SZ, ValueName.Buffer, ValueName.MaximumLength);
       if (!NT_SUCCESS(Status))
       {
@@ -2973,33 +3023,35 @@ IopEnumerateDetectedDevices(
          ZwDeleteKey(hLevel2Key);
          goto nextdevice;
       }
+      /* Create 'LogConf' subkey */
+      InitializeObjectAttributes(&ObjectAttributes, &LogConfU, OBJ_KERNEL_HANDLE, hLevel2Key, NULL);
+      Status = ZwCreateKey(
+         &hLogConf,
+         KEY_SET_VALUE,
+         &ObjectAttributes,
+         0,
+         NULL,
+         REG_OPTION_VOLATILE,
+         NULL);
+      if (!NT_SUCCESS(Status))
+      {
+         DPRINT("ZwCreateKey() failed with status 0x%08lx\n", Status);
+         ZwDeleteKey(hLevel2Key);
+         goto nextdevice;
+      }
       if (BootResourcesLength > 0)
       {
          /* Save boot resources to 'LogConf\BootConfig' */
-         InitializeObjectAttributes(&ObjectAttributes, &LogConfU, OBJ_KERNEL_HANDLE, hLevel2Key, NULL);
-         Status = ZwCreateKey(
-            &hLogConf,
-            KEY_SET_VALUE,
-            &ObjectAttributes,
-            0,
-            NULL,
-            REG_OPTION_VOLATILE,
-            NULL);
-         if (!NT_SUCCESS(Status))
-         {
-            DPRINT("ZwCreateKey() failed with status 0x%08lx\n", Status);
-            ZwDeleteKey(hLevel2Key);
-            goto nextdevice;
-         }
          Status = ZwSetValueKey(hLogConf, &BootConfigU, 0, REG_FULL_RESOURCE_DESCRIPTOR, BootResources, BootResourcesLength);
-         ZwClose(hLogConf);
          if (!NT_SUCCESS(Status))
          {
             DPRINT("ZwSetValueKey() failed with status 0x%08lx\n", Status);
+            ZwClose(hLogConf);
             ZwDeleteKey(hLevel2Key);
             goto nextdevice;
          }
       }
+      ZwClose(hLogConf);
 
 nextdevice:
       if (BootResources && BootResources != ParentBootResources)
@@ -3019,7 +3071,7 @@ nextdevice:
    Status = STATUS_SUCCESS;
 
 cleanup:
-   if (hDevicesKey)
+   if (hDevicesKey && hDevicesKey != hBaseKey)
       ZwClose(hDevicesKey);
    if (hDeviceKey)
       ZwClose(hDeviceKey);
@@ -3033,8 +3085,9 @@ cleanup:
 static BOOLEAN INIT_FUNCTION
 IopIsAcpiComputer(VOID)
 {
+#ifndef ENABLE_ACPI
    return FALSE;
-#if 0
+#else
    UNICODE_STRING MultiKeyPathU = RTL_CONSTANT_STRING(L"\\Registry\\Machine\\HARDWARE\\DESCRIPTION\\System\\MultifunctionAdapter");
    UNICODE_STRING IdentifierU = RTL_CONSTANT_STRING(L"Identifier");
    UNICODE_STRING AcpiBiosIdentifier = RTL_CONSTANT_STRING(L"ACPI BIOS");
@@ -3172,26 +3225,32 @@ cleanup:
 static NTSTATUS INIT_FUNCTION
 IopUpdateRootKey(VOID)
 {
-   UNICODE_STRING RootPathU = RTL_CONSTANT_STRING(L"\\Registry\\Machine\\SYSTEM\\CurrentControlSet\\Enum\\Root");
+   UNICODE_STRING EnumU = RTL_CONSTANT_STRING(L"\\Registry\\Machine\\SYSTEM\\CurrentControlSet\\Enum");
+   UNICODE_STRING RootPathU = RTL_CONSTANT_STRING(L"Root");
    UNICODE_STRING MultiKeyPathU = RTL_CONSTANT_STRING(L"\\Registry\\Machine\\HARDWARE\\DESCRIPTION\\System\\MultifunctionAdapter");
    UNICODE_STRING DeviceDescU = RTL_CONSTANT_STRING(L"DeviceDesc");
    UNICODE_STRING HardwareIDU = RTL_CONSTANT_STRING(L"HardwareID");
+   UNICODE_STRING LogConfU = RTL_CONSTANT_STRING(L"LogConf");
    UNICODE_STRING HalAcpiDevice = RTL_CONSTANT_STRING(L"ACPI_HAL");
    UNICODE_STRING HalAcpiId = RTL_CONSTANT_STRING(L"0000");
    UNICODE_STRING HalAcpiDeviceDesc = RTL_CONSTANT_STRING(L"HAL ACPI");
    UNICODE_STRING HalAcpiHardwareID = RTL_CONSTANT_STRING(L"*PNP0C08\0");
    OBJECT_ATTRIBUTES ObjectAttributes;
-   HANDLE hRoot, hHalAcpiDevice, hHalAcpiId;
+   HANDLE hEnum, hRoot, hHalAcpiDevice, hHalAcpiId, hLogConf;
    NTSTATUS Status;
 
-   InitializeObjectAttributes(&ObjectAttributes, &RootPathU, OBJ_KERNEL_HANDLE, NULL, NULL);
-   Status = ZwOpenKey(&hRoot, KEY_CREATE_SUB_KEY, &ObjectAttributes);
-   if (Status == STATUS_OBJECT_NAME_NOT_FOUND)
+   InitializeObjectAttributes(&ObjectAttributes, &EnumU, OBJ_KERNEL_HANDLE, NULL, NULL);
+   Status = ZwCreateKey(&hEnum, KEY_CREATE_SUB_KEY, &ObjectAttributes, 0, NULL, 0, NULL);
+   if (!NT_SUCCESS(Status))
    {
-      /* We are probably in 1st stage */
-      return STATUS_SUCCESS;
+      DPRINT1("ZwCreateKey() failed with status 0x%08lx\n", Status);
+      return Status;
    }
-   else if (!NT_SUCCESS(Status))
+
+   InitializeObjectAttributes(&ObjectAttributes, &RootPathU, OBJ_KERNEL_HANDLE, hEnum, NULL);
+   Status = ZwCreateKey(&hRoot, KEY_CREATE_SUB_KEY, &ObjectAttributes, 0, NULL, 0, NULL);
+   ZwClose(hEnum);
+   if (!NT_SUCCESS(Status))
    {
       DPRINT1("ZwOpenKey() failed with status 0x%08lx\n", Status);
       return Status;
@@ -3212,23 +3271,47 @@ IopUpdateRootKey(VOID)
       Status = ZwSetValueKey(hHalAcpiId, &DeviceDescU, 0, REG_SZ, HalAcpiDeviceDesc.Buffer, HalAcpiDeviceDesc.MaximumLength);
       if (NT_SUCCESS(Status))
          Status = ZwSetValueKey(hHalAcpiId, &HardwareIDU, 0, REG_MULTI_SZ, HalAcpiHardwareID.Buffer, HalAcpiHardwareID.MaximumLength);
+      if (NT_SUCCESS(Status))
+      {
+          InitializeObjectAttributes(&ObjectAttributes, &LogConfU, OBJ_KERNEL_HANDLE, hHalAcpiId, NULL);
+          Status = ZwCreateKey(&hLogConf, 0, &ObjectAttributes, 0, NULL, REG_OPTION_VOLATILE, NULL);
+          if (NT_SUCCESS(Status))
+              ZwClose(hLogConf);
+      }
       ZwClose(hHalAcpiId);
       return Status;
    }
    else
    {
-      Status = IopEnumerateDetectedDevices(
-         NULL,
-         &MultiKeyPathU,
-         hRoot,
-         TRUE,
-         NULL,
-         0);
-      ZwClose(hRoot);
-      return Status;
+        InitializeObjectAttributes(&ObjectAttributes, &MultiKeyPathU, OBJ_KERNEL_HANDLE, NULL, NULL);
+        Status = ZwOpenKey(&hEnum, KEY_ENUMERATE_SUB_KEYS, &ObjectAttributes);
+        if (!NT_SUCCESS(Status))
+        {
+            /* Nothing to do, don't return with an error status */
+            DPRINT("ZwOpenKey() failed with status 0x%08lx\n", Status);
+            ZwClose(hRoot);
+            return STATUS_SUCCESS;
+        }
+        Status = IopEnumerateDetectedDevices(
+            hEnum,
+            NULL,
+            hRoot,
+            TRUE,
+            NULL,
+            0);
+        ZwClose(hEnum);
+        ZwClose(hRoot);
+        return Status;
    }
 }
 
+static NTSTATUS INIT_FUNCTION
+NTAPI
+PnpDriverInitializeEmpty(IN struct _DRIVER_OBJECT *DriverObject, IN PUNICODE_STRING RegistryPath)
+{
+   return STATUS_SUCCESS;
+}
+
 VOID INIT_FUNCTION
 PnpInit(VOID)
 {
@@ -3256,7 +3339,7 @@ PnpInit(VOID)
     * Create root device node
     */
 
-    Status = IopCreateDriverObject(&IopRootDriverObject, NULL, 0, FALSE, NULL, 0);
+    Status = IopCreateDriver(NULL, PnpDriverInitializeEmpty, NULL, 0, 0, &IopRootDriverObject);
     if (!NT_SUCCESS(Status))
     {
         CPRINT("IoCreateDriverObject() failed\n");
@@ -3271,7 +3354,7 @@ PnpInit(VOID)
         KEBUGCHECKEX(PHASE1_INITIALIZATION_FAILED, Status, 0, 0, 0);
     }
 
-    Status = IopCreateDeviceNode(NULL, Pdo, &IopRootDeviceNode);
+    Status = IopCreateDeviceNode(NULL, Pdo, NULL, &IopRootDeviceNode);
     if (!NT_SUCCESS(Status))
     {
         CPRINT("Insufficient resources\n");
@@ -3291,6 +3374,7 @@ PnpInit(VOID)
 
     IopRootDeviceNode->PhysicalDeviceObject->Flags |= DO_BUS_ENUMERATED_DEVICE;
     PnpRootDriverEntry(IopRootDriverObject, NULL);
+    IopRootDeviceNode->PhysicalDeviceObject->Flags &= ~DO_DEVICE_INITIALIZING;
     IopRootDriverObject->DriverExtension->AddDevice(
         IopRootDriverObject,
         IopRootDeviceNode->PhysicalDeviceObject);
@@ -3304,5 +3388,91 @@ PnpInit(VOID)
     }
 }
 
+RTL_GENERIC_COMPARE_RESULTS
+NTAPI
+PiCompareInstancePath(IN PRTL_AVL_TABLE Table,
+                      IN PVOID FirstStruct,
+                      IN PVOID SecondStruct)
+{
+    /* FIXME: TODO */
+    KEBUGCHECK(0);
+    return 0;
+}
+
+//
+//  The allocation function is called by the generic table package whenever
+//  it needs to allocate memory for the table.
+//
+
+PVOID
+NTAPI
+PiAllocateGenericTableEntry(IN PRTL_AVL_TABLE Table,
+                            IN CLONG ByteSize)
+{
+    /* FIXME: TODO */
+    KEBUGCHECK(0);
+    return NULL;
+}
+
+VOID
+NTAPI
+PiFreeGenericTableEntry(IN PRTL_AVL_TABLE Table,
+                        IN PVOID Buffer)
+{
+    /* FIXME: TODO */
+    KEBUGCHECK(0);
+}
+
+VOID
+NTAPI
+PpInitializeDeviceReferenceTable(VOID)
+{
+    /* Setup the guarded mutex and AVL table */
+    KeInitializeGuardedMutex(&PpDeviceReferenceTableLock);
+    RtlInitializeGenericTableAvl(
+        &PpDeviceReferenceTable,
+        (PRTL_AVL_COMPARE_ROUTINE)PiCompareInstancePath,
+        (PRTL_AVL_ALLOCATE_ROUTINE)PiAllocateGenericTableEntry,
+        (PRTL_AVL_FREE_ROUTINE)PiFreeGenericTableEntry,
+        NULL);
+}
+
+BOOLEAN
+NTAPI
+PiInitPhase0(VOID)
+{
+    /* Initialize the resource when accessing device registry data */
+    ExInitializeResourceLite(&PpRegistryDeviceResource);
+
+    /* Setup the device reference AVL table */
+    PpInitializeDeviceReferenceTable();
+    return TRUE;
+}
+
+BOOLEAN
+NTAPI
+PpInitSystem(VOID)
+{
+    /* Check the initialization phase */
+    switch (ExpInitializationPhase)
+    {
+    case 0:
+
+        /* Do Phase 0 */
+        return PiInitPhase0();
+
+    case 1:
+
+        /* Do Phase 1 */
+        return TRUE;
+        //return PiInitPhase1();
+
+    default:
+
+        /* Don't know any other phase! Bugcheck! */
+        KeBugCheck(UNEXPECTED_INITIALIZATION_CALL);
+        return FALSE;
+    }
+}
 
 /* EOF */