fix typo
[reactos.git] / reactos / ntoskrnl / io / pnpmgr / pnpmgr.c
index c0047ae..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 **********************************************************************/
 
@@ -28,26 +37,33 @@ PIO_BUS_TYPE_GUID_LIST IopBusTypeGuidList = NULL;
 #if defined (ALLOC_PRAGMA)
 #pragma alloc_text(INIT, PnpInit)
 #pragma alloc_text(INIT, PnpInit2)
-#pragma alloc_text(INIT, IopUpdateRootKey)
-#pragma alloc_text(INIT, IopEnumerateDetectedDevices)
-#pragma alloc_text(INIT, IopIsAcpiComputer)
 #endif
 
 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 CALLBACK
-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)
@@ -62,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;
 }
@@ -123,20 +142,56 @@ 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;
 
-   /* FIXME: Not sure of this! */
-   if (!Stack.Parameters.StartDevice.AllocatedResources)
-      Stack.Parameters.StartDevice.AllocatedResources = DeviceNode->BootResources;
-   if (!Stack.Parameters.StartDevice.AllocatedResourcesTranslated)
-      Stack.Parameters.StartDevice.AllocatedResourcesTranslated = DeviceNode->BootResources;
+   /*
+    * 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,
@@ -144,16 +199,20 @@ IopStartDevice(
       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);
       }
    }
@@ -192,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);
 }
 
 /*
@@ -230,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)
@@ -248,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);
 }
 
 /*
@@ -274,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);
 
@@ -309,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)
@@ -356,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;
 }
 
 /*
@@ -602,7 +646,7 @@ IoOpenDeviceRegistryKey(IN PDEVICE_OBJECT DeviceObject,
       return STATUS_INSUFFICIENT_RESOURCES;
 
    KeyName.Length = 0;
-   KeyName.MaximumLength = KeyNameLength;
+   KeyName.MaximumLength = (USHORT)KeyNameLength;
    KeyName.Buffer = KeyNameBuffer;
 
    /*
@@ -628,7 +672,7 @@ IoOpenDeviceRegistryKey(IN PDEVICE_OBJECT DeviceObject,
          ExFreePool(KeyNameBuffer);
          return Status;
       }
-      KeyName.Length += DriverKeyLength - sizeof(UNICODE_NULL);
+      KeyName.Length += (USHORT)DriverKeyLength - sizeof(UNICODE_NULL);
    }
    else
    {
@@ -713,7 +757,7 @@ IopGetBusTypeGuidIndex(LPGUID BusTypeGuid)
    USHORT i = 0, FoundIndex = 0xFFFF;
    ULONG NewSize;
    PVOID NewList;
-    
+
    /* Acquire the lock */
    ExAcquireFastMutex(&IopBusTypeGuidList->Lock);
 
@@ -759,7 +803,7 @@ IopGetBusTypeGuidIndex(LPGUID BusTypeGuid)
                  sizeof(GUID));
 
    /* The new entry is the index */
-   FoundIndex = IopBusTypeGuidList->GuidCount;
+   FoundIndex = (USHORT)IopBusTypeGuidList->GuidCount;
    IopBusTypeGuidList->GuidCount++;
 
 Quickie:
@@ -784,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)
@@ -803,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;
       }
@@ -931,17 +977,16 @@ 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);
-   IrpSp->MinorFunction = MinorFunction;
+   IrpSp->MinorFunction = (UCHAR)MinorFunction;
 
    if (Stack)
    {
-      RtlMoveMemory(&IrpSp->Parameters,
+      RtlCopyMemory(&IrpSp->Parameters,
                     &Stack->Parameters,
                     sizeof(Stack->Parameters));
    }
@@ -1025,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;
 }
 
 
@@ -1188,71 +1261,67 @@ 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");
+  DPRINT("IopSetDeviceInstanceData() done\n");
 
   return STATUS_SUCCESS;
 }
 
 
-NTSTATUS
-IopAssignDeviceResources(PDEVICE_NODE DeviceNode)
+static NTSTATUS
+IopAssignDeviceResources(
+   IN PDEVICE_NODE DeviceNode,
+   OUT ULONG *pRequiredSize)
 {
    PIO_RESOURCE_LIST ResourceList;
    PIO_RESOURCE_DESCRIPTOR ResourceDescriptor;
-   PCM_PARTIAL_RESOURCE_DESCRIPTOR DescriptorRaw, DescriptorTranslated;
+   PCM_PARTIAL_RESOURCE_DESCRIPTOR DescriptorRaw;
+   PCM_PARTIAL_RESOURCE_LIST pPartialResourceList;
    ULONG NumberOfResources = 0;
-   ULONG i;
+   ULONG Size;
+   ULONG i, j;
    NTSTATUS Status;
 
-   /* Fill DeviceNode->ResourceList and DeviceNode->ResourceListTranslated;
-    * by using DeviceNode->ResourceRequirements */
-
-   if (!DeviceNode->ResourceRequirements
-      || DeviceNode->ResourceRequirements->AlternativeLists == 0)
+   if (!DeviceNode->BootResources && !DeviceNode->ResourceRequirements)
    {
-      DeviceNode->ResourceList = DeviceNode->ResourceListTranslated = NULL;
+      /* No resource needed for this device */
+      DeviceNode->ResourceList = NULL;
       return STATUS_SUCCESS;
    }
 
-   IopDeviceNodeSetFlag(DeviceNode, DNF_ASSIGNING_RESOURCES);
+   /* Fill DeviceNode->ResourceList
+    * FIXME: the PnP arbiter should go there!
+    * Actually, use the BootResources if provided, else the resource list #0
+    */
+
+   if (DeviceNode->BootResources)
+   {
+      /* Browse the boot resources to know if we have some custom structures */
+      Size = FIELD_OFFSET(CM_RESOURCE_LIST, List);
+      for (i = 0; i < DeviceNode->BootResources->Count; i++)
+      {
+         pPartialResourceList = &DeviceNode->BootResources->List[i].PartialResourceList;
+         Size += FIELD_OFFSET(CM_FULL_RESOURCE_DESCRIPTOR, PartialResourceList.PartialDescriptors)
+            + pPartialResourceList->Count * sizeof(CM_PARTIAL_RESOURCE_DESCRIPTOR);
+         for (j = 0; j < pPartialResourceList->Count; j++)
+         {
+            if (pPartialResourceList->PartialDescriptors[j].Type == CmResourceTypeDeviceSpecific)
+               Size += pPartialResourceList->PartialDescriptors[j].u.DeviceSpecificData.DataSize;
+         }
+      }
 
-   /* FIXME: that's here that PnP arbiter should go */
-   /* Actually, simply use resource list #0 as assigned resource list */
+      DeviceNode->ResourceList = ExAllocatePool(PagedPool, Size);
+      if (!DeviceNode->ResourceList)
+      {
+         Status = STATUS_NO_MEMORY;
+         goto ByeBye;
+      }
+      RtlCopyMemory(DeviceNode->ResourceList, DeviceNode->BootResources, Size);
+
+      *pRequiredSize = Size;
+      return STATUS_SUCCESS;
+   }
+
+   /* Ok, here, we have to use the device requirement list */
    ResourceList = &DeviceNode->ResourceRequirements->List[0];
    if (ResourceList->Version != 1 || ResourceList->Revision != 1)
    {
@@ -1260,19 +1329,12 @@ IopAssignDeviceResources(PDEVICE_NODE DeviceNode)
       goto ByeBye;
    }
 
-   DeviceNode->ResourceList = ExAllocatePool(PagedPool,
-      sizeof(CM_RESOURCE_LIST) + ResourceList->Count * sizeof(CM_PARTIAL_RESOURCE_DESCRIPTOR));
+   Size = sizeof(CM_RESOURCE_LIST) + ResourceList->Count * sizeof(CM_PARTIAL_RESOURCE_DESCRIPTOR);
+   *pRequiredSize = Size;
+   DeviceNode->ResourceList = ExAllocatePool(PagedPool, Size);
    if (!DeviceNode->ResourceList)
    {
-      Status = STATUS_INSUFFICIENT_RESOURCES;
-      goto ByeBye;
-   }
-
-   DeviceNode->ResourceListTranslated = ExAllocatePool(PagedPool,
-      sizeof(CM_RESOURCE_LIST) + ResourceList->Count * sizeof(CM_PARTIAL_RESOURCE_DESCRIPTOR));
-   if (!DeviceNode->ResourceListTranslated)
-   {
-      Status = STATUS_INSUFFICIENT_RESOURCES;
+      Status = STATUS_NO_MEMORY;
       goto ByeBye;
    }
 
@@ -1282,12 +1344,6 @@ IopAssignDeviceResources(PDEVICE_NODE DeviceNode)
    DeviceNode->ResourceList->List[0].PartialResourceList.Version = 1;
    DeviceNode->ResourceList->List[0].PartialResourceList.Revision = 1;
 
-   DeviceNode->ResourceListTranslated->Count = 1;
-   DeviceNode->ResourceListTranslated->List[0].InterfaceType = DeviceNode->ResourceRequirements->InterfaceType;
-   DeviceNode->ResourceListTranslated->List[0].BusNumber = DeviceNode->ResourceRequirements->BusNumber;
-   DeviceNode->ResourceListTranslated->List[0].PartialResourceList.Version = 1;
-   DeviceNode->ResourceListTranslated->List[0].PartialResourceList.Revision = 1;
-
    for (i = 0; i < ResourceList->Count; i++)
    {
       ResourceDescriptor = &ResourceList->Descriptors[i];
@@ -1295,31 +1351,18 @@ IopAssignDeviceResources(PDEVICE_NODE DeviceNode)
       if (ResourceDescriptor->Option == 0 || ResourceDescriptor->Option == IO_RESOURCE_PREFERRED)
       {
          DescriptorRaw = &DeviceNode->ResourceList->List[0].PartialResourceList.PartialDescriptors[NumberOfResources];
-         DescriptorTranslated = &DeviceNode->ResourceListTranslated->List[0].PartialResourceList.PartialDescriptors[NumberOfResources];
          NumberOfResources++;
 
          /* Copy ResourceDescriptor to DescriptorRaw and DescriptorTranslated */
-         DescriptorRaw->Type = DescriptorTranslated->Type = ResourceDescriptor->Type;
-         DescriptorRaw->ShareDisposition = DescriptorTranslated->ShareDisposition = ResourceDescriptor->ShareDisposition;
-         DescriptorRaw->Flags = DescriptorTranslated->Flags = ResourceDescriptor->Flags;
+         DescriptorRaw->Type = ResourceDescriptor->Type;
+         DescriptorRaw->ShareDisposition = ResourceDescriptor->ShareDisposition;
+         DescriptorRaw->Flags = ResourceDescriptor->Flags;
          switch (ResourceDescriptor->Type)
          {
             case CmResourceTypePort:
             {
-               ULONG AddressSpace = 0; /* IO space */
                DescriptorRaw->u.Port.Start = ResourceDescriptor->u.Port.MinimumAddress;
-               DescriptorRaw->u.Port.Length = DescriptorTranslated->u.Port.Length
-                  = ResourceDescriptor->u.Port.Length;
-               if (!HalTranslateBusAddress(
-                  DeviceNode->ResourceRequirements->InterfaceType,
-                  DeviceNode->ResourceRequirements->BusNumber,
-                  DescriptorRaw->u.Port.Start,
-                  &AddressSpace,
-                  &DescriptorTranslated->u.Port.Start))
-               {
-                  Status = STATUS_UNSUCCESSFUL;
-                  goto ByeBye;
-               }
+               DescriptorRaw->u.Port.Length = ResourceDescriptor->u.Port.Length;
                break;
             }
             case CmResourceTypeInterrupt:
@@ -1379,54 +1422,26 @@ IopAssignDeviceResources(PDEVICE_NODE DeviceNode)
                      }
                   }
                }
-
-               DescriptorTranslated->u.Interrupt.Level = 0;
-               DescriptorTranslated->u.Interrupt.Vector = HalGetInterruptVector(
-                  DeviceNode->ResourceRequirements->InterfaceType,
-                  DeviceNode->ResourceRequirements->BusNumber,
-                  DescriptorRaw->u.Interrupt.Level,
-                  DescriptorRaw->u.Interrupt.Vector,
-                  (PKIRQL)&DescriptorTranslated->u.Interrupt.Level,
-                  &DescriptorRaw->u.Interrupt.Affinity);
-               DescriptorTranslated->u.Interrupt.Affinity = DescriptorRaw->u.Interrupt.Affinity;
                break;
             }
             case CmResourceTypeMemory:
             {
-               ULONG AddressSpace = 1; /* Memory space */
                DescriptorRaw->u.Memory.Start = ResourceDescriptor->u.Memory.MinimumAddress;
-               DescriptorRaw->u.Memory.Length = DescriptorTranslated->u.Memory.Length
-                  = ResourceDescriptor->u.Memory.Length;
-               if (!HalTranslateBusAddress(
-                  DeviceNode->ResourceRequirements->InterfaceType,
-                  DeviceNode->ResourceRequirements->BusNumber,
-                  DescriptorRaw->u.Memory.Start,
-                  &AddressSpace,
-                  &DescriptorTranslated->u.Memory.Start))
-               {
-                  Status = STATUS_UNSUCCESSFUL;
-                  goto ByeBye;
-               }
+               DescriptorRaw->u.Memory.Length = ResourceDescriptor->u.Memory.Length;
                break;
             }
             case CmResourceTypeDma:
             {
-               DescriptorRaw->u.Dma.Channel = DescriptorTranslated->u.Dma.Channel
-                  = ResourceDescriptor->u.Dma.MinimumChannel;
-               DescriptorRaw->u.Dma.Port = DescriptorTranslated->u.Dma.Port
-                  = 0; /* FIXME */
-               DescriptorRaw->u.Dma.Reserved1 = DescriptorTranslated->u.Dma.Reserved1
-                  = 0;
+               DescriptorRaw->u.Dma.Channel = ResourceDescriptor->u.Dma.MinimumChannel;
+               DescriptorRaw->u.Dma.Port = 0; /* FIXME */
+               DescriptorRaw->u.Dma.Reserved1 = 0;
                break;
             }
             case CmResourceTypeBusNumber:
             {
-               DescriptorRaw->u.BusNumber.Start = DescriptorTranslated->u.BusNumber.Start
-                  = ResourceDescriptor->u.BusNumber.MinBusNumber;
-               DescriptorRaw->u.BusNumber.Length = DescriptorTranslated->u.BusNumber.Length
-                  = ResourceDescriptor->u.BusNumber.Length;
-               DescriptorRaw->u.BusNumber.Reserved = DescriptorTranslated->u.BusNumber.Reserved
-                  = ResourceDescriptor->u.BusNumber.Reserved;
+               DescriptorRaw->u.BusNumber.Start = ResourceDescriptor->u.BusNumber.MinBusNumber;
+               DescriptorRaw->u.BusNumber.Length = ResourceDescriptor->u.BusNumber.Length;
+               DescriptorRaw->u.BusNumber.Reserved = ResourceDescriptor->u.BusNumber.Reserved;
                break;
             }
             /*CmResourceTypeDevicePrivate:
@@ -1452,10 +1467,7 @@ IopAssignDeviceResources(PDEVICE_NODE DeviceNode)
    }
 
    DeviceNode->ResourceList->List[0].PartialResourceList.Count = NumberOfResources;
-   DeviceNode->ResourceListTranslated->List[0].PartialResourceList.Count = NumberOfResources;
 
-   IopDeviceNodeClearFlag(DeviceNode, DNF_ASSIGNING_RESOURCES);
-   IopDeviceNodeSetFlag(DeviceNode, DNF_RESOURCE_ASSIGNED);
    return STATUS_SUCCESS;
 
 ByeBye:
@@ -1464,13 +1476,111 @@ ByeBye:
       ExFreePool(DeviceNode->ResourceList);
       DeviceNode->ResourceList = NULL;
    }
-   if (DeviceNode->ResourceListTranslated)
+   return Status;
+}
+
+
+static NTSTATUS
+IopTranslateDeviceResources(
+   IN PDEVICE_NODE DeviceNode,
+   IN ULONG RequiredSize)
+{
+   PCM_PARTIAL_RESOURCE_LIST pPartialResourceList;
+   PCM_PARTIAL_RESOURCE_DESCRIPTOR DescriptorRaw, DescriptorTranslated;
+   ULONG i, j;
+   NTSTATUS Status;
+
+   if (!DeviceNode->ResourceList)
    {
-      ExFreePool(DeviceNode->ResourceListTranslated);
       DeviceNode->ResourceListTranslated = NULL;
+      return STATUS_SUCCESS;
    }
 
-   IopDeviceNodeClearFlag(DeviceNode, DNF_ASSIGNING_RESOURCES);
+   /* That's easy to translate a resource list. Just copy the
+    * untranslated one and change few fields in the copy
+    */
+   DeviceNode->ResourceListTranslated = ExAllocatePool(PagedPool, RequiredSize);
+   if (!DeviceNode->ResourceListTranslated)
+   {
+      Status =STATUS_NO_MEMORY;
+      goto cleanup;
+   }
+   RtlCopyMemory(DeviceNode->ResourceListTranslated, DeviceNode->ResourceList, RequiredSize);
+
+   for (i = 0; i < DeviceNode->ResourceList->Count; i++)
+   {
+      pPartialResourceList = &DeviceNode->ResourceList->List[i].PartialResourceList;
+      for (j = 0; j < pPartialResourceList->Count; j++)
+      {
+         DescriptorRaw = &pPartialResourceList->PartialDescriptors[j];
+         DescriptorTranslated = &DeviceNode->ResourceListTranslated->List[i].PartialResourceList.PartialDescriptors[j];
+         switch (DescriptorRaw->Type)
+         {
+            case CmResourceTypePort:
+            {
+               ULONG AddressSpace = 0; /* IO space */
+               if (!HalTranslateBusAddress(
+                  DeviceNode->ResourceList->List[i].InterfaceType,
+                  DeviceNode->ResourceList->List[i].BusNumber,
+                  DescriptorRaw->u.Port.Start,
+                  &AddressSpace,
+                  &DescriptorTranslated->u.Port.Start))
+               {
+                  Status = STATUS_UNSUCCESSFUL;
+                  goto cleanup;
+               }
+               break;
+            }
+            case CmResourceTypeInterrupt:
+            {
+               DescriptorTranslated->u.Interrupt.Vector = HalGetInterruptVector(
+                  DeviceNode->ResourceList->List[i].InterfaceType,
+                  DeviceNode->ResourceList->List[i].BusNumber,
+                  DescriptorRaw->u.Interrupt.Level,
+                  DescriptorRaw->u.Interrupt.Vector,
+                  (PKIRQL)&DescriptorTranslated->u.Interrupt.Level,
+                  &DescriptorRaw->u.Interrupt.Affinity);
+               break;
+            }
+            case CmResourceTypeMemory:
+            {
+               ULONG AddressSpace = 1; /* Memory space */
+               if (!HalTranslateBusAddress(
+                  DeviceNode->ResourceList->List[i].InterfaceType,
+                  DeviceNode->ResourceList->List[i].BusNumber,
+                  DescriptorRaw->u.Memory.Start,
+                  &AddressSpace,
+                  &DescriptorTranslated->u.Memory.Start))
+               {
+                  Status = STATUS_UNSUCCESSFUL;
+                  goto cleanup;
+               }
+            }
+
+            case CmResourceTypeDma:
+            case CmResourceTypeBusNumber:
+            case CmResourceTypeDeviceSpecific:
+               /* Nothing to do */
+               break;
+            default:
+               DPRINT1("Unknown resource descriptor type 0x%x\n", DescriptorRaw->Type);
+               Status = STATUS_NOT_IMPLEMENTED;
+               goto cleanup;
+         }
+      }
+   }
+   return STATUS_SUCCESS;
+
+cleanup:
+   /* Yes! Also delete ResourceList because ResourceList and
+    * ResourceListTranslated should be a pair! */
+   ExFreePool(DeviceNode->ResourceList);
+   DeviceNode->ResourceList = NULL;
+   if (DeviceNode->ResourceListTranslated)
+   {
+      ExFreePool(DeviceNode->ResourceListTranslated);
+      DeviceNode->ResourceList = NULL;
+   }
    return Status;
 }
 
@@ -1512,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);
@@ -1546,14 +1660,14 @@ IopGetParentIdPrefix(PDEVICE_NODE DeviceNode,
          Status = STATUS_UNSUCCESSFUL;
       else
       {
-         KeyValue.Length = KeyValue.MaximumLength = ParentIdPrefixInformation->DataLength;
+         KeyValue.Length = KeyValue.MaximumLength = (USHORT)ParentIdPrefixInformation->DataLength;
          KeyValue.Buffer = (PWSTR)ParentIdPrefixInformation->Data;
       }
       goto cleanup;
    }
    if (Status != STATUS_OBJECT_NAME_NOT_FOUND)
    {
-      KeyValue.Length = KeyValue.MaximumLength = ParentIdPrefixInformation->DataLength;
+      KeyValue.Length = KeyValue.MaximumLength = (USHORT)ParentIdPrefixInformation->DataLength;
       KeyValue.Buffer = (PWSTR)ParentIdPrefixInformation->Data;
       goto cleanup;
    }
@@ -1759,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))
    {
@@ -1879,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;
@@ -2030,104 +2143,252 @@ IopActionInterrogateDeviceStack(PDEVICE_NODE DeviceNode,
 
    ZwClose(InstanceKey);
 
-   Status = IopAssignDeviceResources(DeviceNode);
-   if (!NT_SUCCESS(Status))
+   IopDeviceNodeSetFlag(DeviceNode, DNF_PROCESSED);
+
+   if (!IopDeviceNodeHasFlag(DeviceNode, DNF_LEGACY_DRIVER))
    {
-      DPRINT("IopAssignDeviceResources() failed (Status %x)\n", Status);
+      /* Report the device to the user-mode pnp manager */
+      IopQueueTargetDeviceEvent(&GUID_DEVICE_ARRIVAL,
+                                &DeviceNode->InstancePath);
    }
 
-   DeviceNode->Flags |= DNF_PROCESSED;
-
-   /* Report the device to the user-mode pnp manager */
-   IopQueueTargetDeviceEvent(&GUID_DEVICE_ARRIVAL,
-                             &DeviceNode->InstancePath);
-
    return STATUS_SUCCESS;
 }
 
 /*
- * IopActionConfigureChildServices
- *
- * Retrieve configuration for all (direct) child nodes of a parent node.
- *
- * Parameters
- *    DeviceNode
- *       Pointer to device node.
- *    Context
- *       Pointer to parent node to retrieve child node configuration for.
- *
- * Remarks
- *    We only return a status code indicating an error (STATUS_UNSUCCESSFUL)
- *    when we reach a device node which is not a direct child of the device
- *    node for which we configure child services for. Any errors that occur is
- *    logged instead so that all child services have a chance of beeing
- *    configured.
+ * @implemented
  */
-
-NTSTATUS
-IopActionConfigureChildServices(PDEVICE_NODE DeviceNode,
-                                PVOID Context)
+VOID
+NTAPI
+IoSynchronousInvalidateDeviceRelations(
+    IN PDEVICE_OBJECT DeviceObject,
+    IN DEVICE_RELATION_TYPE Type)
 {
-   RTL_QUERY_REGISTRY_TABLE QueryTable[3];
-   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);
+    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;
 
-   ParentDeviceNode = (PDEVICE_NODE)Context;
+    DPRINT("DeviceObject 0x%p\n", DeviceObject);
 
-   /*
-    * We are called for the parent too, but we don't need to do special
-    * handling for this node
-    */
-   if (DeviceNode == ParentDeviceNode)
-   {
-      DPRINT("Success\n");
-      return STATUS_SUCCESS;
-   }
+    DPRINT("Sending IRP_MN_QUERY_DEVICE_RELATIONS to device stack\n");
 
-   /*
-    * Make sure this device node is a direct child of the parent device node
-    * that is given as an argument
-    */
-   if (DeviceNode->Parent != ParentDeviceNode)
-   {
-      /* Stop the traversal immediately and indicate successful operation */
-      DPRINT("Stop\n");
-      return STATUS_UNSUCCESSFUL;
-   }
+    Stack.Parameters.QueryDeviceRelations.Type = Type;
 
-   if (!IopDeviceNodeHasFlag(DeviceNode, DNF_DISABLED))
-   {
-      WCHAR RegKeyBuffer[MAX_PATH];
-      UNICODE_STRING RegKey;
+    Status = IopInitiatePnpIrp(
+        DeviceObject,
+        &IoStatusBlock,
+        IRP_MN_QUERY_DEVICE_RELATIONS,
+        &Stack);
+    if (!NT_SUCCESS(Status))
+    {
+        DPRINT("IopInitiatePnpIrp() failed with status 0x%08lx\n", Status);
+        return;
+    }
 
-      RegKey.Length = 0;
-      RegKey.MaximumLength = sizeof(RegKeyBuffer);
-      RegKey.Buffer = RegKeyBuffer;
+    DeviceRelations = (PDEVICE_RELATIONS)IoStatusBlock.Information;
 
-      /*
-       * Retrieve configuration from Enum key
-       */
+    if (!DeviceRelations || DeviceRelations->Count <= 0)
+    {
+        DPRINT("No PDOs\n");
+        if (DeviceRelations)
+        {
+            ExFreePool(DeviceRelations);
+        }
+        return;
+    }
 
-      Service = &DeviceNode->ServiceName;
+    DPRINT("Got %d PDOs\n", DeviceRelations->Count);
 
-      RtlZeroMemory(QueryTable, sizeof(QueryTable));
-      RtlInitUnicodeString(Service, NULL);
-      RtlInitUnicodeString(&ClassGUID, NULL);
+    /*
+     * 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);
 
-      QueryTable[0].Name = L"Service";
-      QueryTable[0].Flags = RTL_QUERY_REGISTRY_DIRECT;
-      QueryTable[0].EntryContext = Service;
+    /*
+     * 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");
+}
+
+/*
+ * IopActionConfigureChildServices
+ *
+ * Retrieve configuration for all (direct) child nodes of a parent node.
+ *
+ * Parameters
+ *    DeviceNode
+ *       Pointer to device node.
+ *    Context
+ *       Pointer to parent node to retrieve child node configuration for.
+ *
+ * Remarks
+ *    We only return a status code indicating an error (STATUS_UNSUCCESSFUL)
+ *    when we reach a device node which is not a direct child of the device
+ *    node for which we configure child services for. Any errors that occur is
+ *    logged instead so that all child services have a chance of beeing
+ *    configured.
+ */
+
+NTSTATUS
+IopActionConfigureChildServices(PDEVICE_NODE DeviceNode,
+                                PVOID Context)
+{
+   RTL_QUERY_REGISTRY_TABLE QueryTable[3];
+   PDEVICE_NODE ParentDeviceNode;
+   PUNICODE_STRING Service;
+   UNICODE_STRING ClassGUID;
+   NTSTATUS Status;
+
+   DPRINT("IopActionConfigureChildServices(%p, %p)\n", DeviceNode, Context);
+
+   ParentDeviceNode = (PDEVICE_NODE)Context;
+
+   /*
+    * We are called for the parent too, but we don't need to do special
+    * handling for this node
+    */
+   if (DeviceNode == ParentDeviceNode)
+   {
+      DPRINT("Success\n");
+      return STATUS_SUCCESS;
+   }
+
+   /*
+    * Make sure this device node is a direct child of the parent device node
+    * that is given as an argument
+    */
+   if (DeviceNode->Parent != ParentDeviceNode)
+   {
+      /* Stop the traversal immediately and indicate successful operation */
+      DPRINT("Stop\n");
+      return STATUS_UNSUCCESSFUL;
+   }
+
+   if (!IopDeviceNodeHasFlag(DeviceNode, DNF_DISABLED))
+   {
+      WCHAR RegKeyBuffer[MAX_PATH];
+      UNICODE_STRING RegKey;
+
+      RegKey.Length = 0;
+      RegKey.MaximumLength = sizeof(RegKeyBuffer);
+      RegKey.Buffer = RegKeyBuffer;
+
+      /*
+       * Retrieve configuration from Enum key
+       */
+
+      Service = &DeviceNode->ServiceName;
+
+      RtlZeroMemory(QueryTable, sizeof(QueryTable));
+      RtlInitUnicodeString(Service, NULL);
+      RtlInitUnicodeString(&ClassGUID, NULL);
+
+      QueryTable[0].Name = L"Service";
+      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\\");
@@ -2138,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;
       }
@@ -2155,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;
          }
@@ -2235,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
@@ -2282,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;
@@ -2337,266 +2624,40 @@ IopActionInitBootServices(PDEVICE_NODE DeviceNode,
  */
 NTSTATUS
 IopInitializePnpServices(IN PDEVICE_NODE DeviceNode,
-                         IN BOOLEAN BootDrivers)
-{
-   DEVICETREE_TRAVERSE_CONTEXT Context;
-
-   DPRINT("IopInitializePnpServices(%p, %d)\n", DeviceNode, BootDrivers);
-
-   if (BootDrivers)
-   {
-      IopInitDeviceTreeTraverseContext(
-         &Context,
-         DeviceNode,
-         IopActionInitBootServices,
-         DeviceNode);
-   }
-   else
-   {
-      IopInitDeviceTreeTraverseContext(
-         &Context,
-         DeviceNode,
-         IopActionInitAllServices,
-         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 CALLBACK
-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, Type %d\n", DeviceObject, Type);
-
-    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);
-}
-
-VOID INIT_FUNCTION
-PnpInit(VOID)
+                         IN BOOLEAN BootDrivers)
 {
-   PDEVICE_OBJECT Pdo;
-   NTSTATUS Status;
-
-   DPRINT("PnpInit()\n");
-
-   KeInitializeSpinLock(&IopDeviceTreeLock);
-
-   /* Initialize the Bus Type GUID List */
-   IopBusTypeGuidList = ExAllocatePool(PagedPool, sizeof(IO_BUS_TYPE_GUID_LIST));
-   RtlZeroMemory(IopBusTypeGuidList, sizeof(IO_BUS_TYPE_GUID_LIST));
-   ExInitializeFastMutex(&IopBusTypeGuidList->Lock);
-
-   /* Initialize PnP-Event notification support */
-   Status = IopInitPlugPlayEvents();
-   if (!NT_SUCCESS(Status))
-   {
-      CPRINT("IopInitPlugPlayEvents() failed\n");
-      KEBUGCHECKEX(PHASE1_INITIALIZATION_FAILED, Status, 0, 0, 0);
-   }
-
-   /*
-    * Create root device node
-    */
-
-   Status = IopCreateDriverObject(&IopRootDriverObject, NULL, 0, FALSE, NULL, 0);
-   if (!NT_SUCCESS(Status))
-   {
-      CPRINT("IoCreateDriverObject() failed\n");
-      KEBUGCHECKEX(PHASE1_INITIALIZATION_FAILED, Status, 0, 0, 0);
-   }
+   DEVICETREE_TRAVERSE_CONTEXT Context;
 
-   Status = IoCreateDevice(IopRootDriverObject, 0, NULL, FILE_DEVICE_CONTROLLER,
-      0, FALSE, &Pdo);
-   if (!NT_SUCCESS(Status))
-   {
-      CPRINT("IoCreateDevice() failed\n");
-      KEBUGCHECKEX(PHASE1_INITIALIZATION_FAILED, Status, 0, 0, 0);
-   }
+   DPRINT("IopInitializePnpServices(%p, %d)\n", DeviceNode, BootDrivers);
 
-   Status = IopCreateDeviceNode(NULL, Pdo, &IopRootDeviceNode);
-   if (!NT_SUCCESS(Status))
+   if (BootDrivers)
    {
-      CPRINT("Insufficient resources\n");
-      KEBUGCHECKEX(PHASE1_INITIALIZATION_FAILED, Status, 0, 0, 0);
+      IopInitDeviceTreeTraverseContext(
+         &Context,
+         DeviceNode,
+         IopActionInitBootServices,
+         DeviceNode);
    }
-
-   if (!RtlCreateUnicodeString(&IopRootDeviceNode->InstancePath,
-       L"HTREE\\ROOT\\0"))
+   else
    {
-     CPRINT("Failed to create the instance path!\n");
-     KEBUGCHECKEX(PHASE1_INITIALIZATION_FAILED, STATUS_NO_MEMORY, 0, 0, 0);
+      IopInitDeviceTreeTraverseContext(
+         &Context,
+         DeviceNode,
+         IopActionInitAllServices,
+         DeviceNode);
    }
 
-   /* Report the device to the user-mode pnp manager */
-   IopQueueTargetDeviceEvent(&GUID_DEVICE_ARRIVAL,
-                             &IopRootDeviceNode->InstancePath);
-
-   IopRootDeviceNode->PhysicalDeviceObject->Flags |= DO_BUS_ENUMERATED_DEVICE;
-   PnpRootDriverEntry(IopRootDriverObject, NULL);
-   IopRootDriverObject->DriverExtension->AddDevice(
-      IopRootDriverObject,
-      IopRootDeviceNode->PhysicalDeviceObject);
+   return IopTraverseDeviceTree(&Context);
 }
 
 static NTSTATUS INIT_FUNCTION
 IopEnumerateDetectedDevices(
    IN HANDLE hBaseKey,
-   IN PUNICODE_STRING RelativePath,
+   IN PUNICODE_STRING RelativePath OPTIONAL,
    IN HANDLE hRootKey,
-   IN BOOLEAN EnumerateSubKeys)
+   IN BOOLEAN EnumerateSubKeys,
+   IN PCM_FULL_RESOURCE_DESCRIPTOR ParentBootResources,
+   IN ULONG ParentBootResourcesLength)
 {
    UNICODE_STRING IdentifierU = RTL_CONSTANT_STRING(L"Identifier");
    UNICODE_STRING DeviceDescU = RTL_CONSTANT_STRING(L"DeviceDesc");
@@ -2618,33 +2679,43 @@ IopEnumerateDetectedDevices(
    ULONG ValueInfoLength = sizeof(KEY_VALUE_PARTIAL_INFORMATION) + 50 * sizeof(WCHAR);
    UNICODE_STRING DeviceName, ValueName;
    ULONG RequiredSize;
+   PCM_FULL_RESOURCE_DESCRIPTOR BootResources = NULL;
+   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;
-   const UNICODE_STRING IdentifierKeyboard = RTL_CONSTANT_STRING(L"KeyboardPeripheral");
+   const UNICODE_STRING IdentifierKeyboard = RTL_CONSTANT_STRING(L"KeyboardController");
    UNICODE_STRING HardwareIdKeyboard = RTL_CONSTANT_STRING(L"*PNP0303\0");
    static ULONG DeviceIndexKeyboard = 0;
-   const UNICODE_STRING IdentifierMouse = RTL_CONSTANT_STRING(L"PointerPeripheral");
+   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)
@@ -2688,12 +2759,12 @@ IopEnumerateDetectedDevices(
       IndexDevice++;
 
       /* Open device key */
-      DeviceName.Length = DeviceName.MaximumLength = pDeviceInformation->NameLength;
+      DeviceName.Length = DeviceName.MaximumLength = (USHORT)pDeviceInformation->NameLength;
       DeviceName.Buffer = pDeviceInformation->Name;
       InitializeObjectAttributes(&ObjectAttributes, &DeviceName, OBJ_KERNEL_HANDLE, hDevicesKey, NULL);
       Status = ZwOpenKey(
          &hDeviceKey,
-         KEY_QUERY_VALUE + EnumerateSubKeys ? KEY_ENUMERATE_SUB_KEYS : 0,
+         KEY_QUERY_VALUE + (EnumerateSubKeys ? KEY_ENUMERATE_SUB_KEYS : 0),
          &ObjectAttributes);
       if (!NT_SUCCESS(Status))
       {
@@ -2701,6 +2772,82 @@ IopEnumerateDetectedDevices(
          goto cleanup;
       }
 
+      /* Read boot resources, and add then to parent ones */
+      Status = ZwQueryValueKey(hDeviceKey, &ConfigurationDataU, KeyValuePartialInformation, pValueInformation, ValueInfoLength, &RequiredSize);
+      if (Status == STATUS_BUFFER_OVERFLOW)
+      {
+         ExFreePool(pValueInformation);
+         ValueInfoLength = RequiredSize;
+         pValueInformation = ExAllocatePool(PagedPool, ValueInfoLength);
+         if (!pValueInformation)
+         {
+            DPRINT("ExAllocatePool() failed\n");
+            ZwDeleteKey(hLevel2Key);
+            Status = STATUS_NO_MEMORY;
+            goto cleanup;
+         }
+         Status = ZwQueryValueKey(hDeviceKey, &ConfigurationDataU, KeyValuePartialInformation, pValueInformation, ValueInfoLength, &RequiredSize);
+      }
+      if (Status == STATUS_OBJECT_NAME_NOT_FOUND)
+      {
+         BootResources = ParentBootResources;
+         BootResourcesLength = ParentBootResourcesLength;
+      }
+      else if (!NT_SUCCESS(Status))
+      {
+         DPRINT("ZwQueryValueKey() failed with status 0x%08lx\n", Status);
+         goto nextdevice;
+      }
+      else if (pValueInformation->Type != REG_FULL_RESOURCE_DESCRIPTOR)
+      {
+         DPRINT("Wrong registry type: got 0x%lx, expected 0x%lx\n", pValueInformation->Type, REG_FULL_RESOURCE_DESCRIPTOR);
+         goto nextdevice;
+      }
+      else
+      {
+         static const ULONG Header = FIELD_OFFSET(CM_FULL_RESOURCE_DESCRIPTOR, PartialResourceList.PartialDescriptors);
+
+         /* Concatenate current resources and parent ones */
+         if (ParentBootResourcesLength == 0)
+            BootResourcesLength = pValueInformation->DataLength;
+         else
+            BootResourcesLength = ParentBootResourcesLength
+               + pValueInformation->DataLength
+               - Header;
+         BootResources = ExAllocatePool(PagedPool, BootResourcesLength);
+         if (!BootResources)
+         {
+            DPRINT("ExAllocatePool() failed\n");
+            goto nextdevice;
+         }
+         if (ParentBootResourcesLength == 0)
+         {
+            RtlCopyMemory(BootResources, pValueInformation->Data, pValueInformation->DataLength);
+         }
+         else if (ParentBootResources->PartialResourceList.PartialDescriptors[ParentBootResources->PartialResourceList.Count - 1].Type == CmResourceTypeDeviceSpecific)
+         {
+            RtlCopyMemory(BootResources, pValueInformation->Data, pValueInformation->DataLength);
+            RtlCopyMemory(
+               (PVOID)((ULONG_PTR)BootResources + pValueInformation->DataLength),
+               (PVOID)((ULONG_PTR)ParentBootResources + Header),
+               ParentBootResourcesLength - Header);
+            BootResources->PartialResourceList.Count += ParentBootResources->PartialResourceList.Count;
+         }
+         else
+         {
+            RtlCopyMemory(BootResources, pValueInformation->Data, Header);
+            RtlCopyMemory(
+               (PVOID)((ULONG_PTR)BootResources + Header),
+               (PVOID)((ULONG_PTR)ParentBootResources + Header),
+               ParentBootResourcesLength - Header);
+            RtlCopyMemory(
+               (PVOID)((ULONG_PTR)BootResources + ParentBootResourcesLength),
+               pValueInformation->Data + Header,
+               pValueInformation->DataLength - Header);
+            BootResources->PartialResourceList.Count += ParentBootResources->PartialResourceList.Count;
+         }
+      }
+
       if (EnumerateSubKeys)
       {
          IndexSubKey = 0;
@@ -2728,10 +2875,16 @@ IopEnumerateDetectedDevices(
                goto cleanup;
             }
             IndexSubKey++;
-            DeviceName.Length = DeviceName.MaximumLength = pDeviceInformation->NameLength;
+            DeviceName.Length = DeviceName.MaximumLength = (USHORT)pDeviceInformation->NameLength;
             DeviceName.Buffer = pDeviceInformation->Name;
 
-            Status = IopEnumerateDetectedDevices(hDeviceKey, &DeviceName, hRootKey, TRUE);
+            Status = IopEnumerateDetectedDevices(
+               hDeviceKey,
+               &DeviceName,
+               hRootKey,
+               TRUE,
+               BootResources,
+               BootResourcesLength);
             if (!NT_SUCCESS(Status))
                goto cleanup;
          }
@@ -2754,54 +2907,77 @@ IopEnumerateDetectedDevices(
       }
       if (!NT_SUCCESS(Status))
       {
-         DPRINT("ZwQueryValueKey() failed with status 0x%08lx\n", Status);
-         goto nextdevice;
+         if (Status != STATUS_OBJECT_NAME_NOT_FOUND)
+         {
+            DPRINT("ZwQueryValueKey() failed with status 0x%08lx\n", Status);
+            goto nextdevice;
+         }
+         ValueName.Length = ValueName.MaximumLength = 0;
       }
       else if (pValueInformation->Type != REG_SZ)
       {
          DPRINT("Wrong registry type: got 0x%lx, expected 0x%lx\n", pValueInformation->Type, REG_SZ);
          goto nextdevice;
       }
-
-      /* Assign hardware id to this device */
-      ValueName.Length = ValueName.MaximumLength = pValueInformation->DataLength;
-      ValueName.Buffer = (PWCHAR)pValueInformation->Data;
-      if (ValueName.Length >= sizeof(WCHAR) && ValueName.Buffer[ValueName.Length / sizeof(WCHAR) - 1] == UNICODE_NULL)
-         ValueName.Length -= sizeof(WCHAR);
-      if (RtlCompareUnicodeString(&ValueName, &IdentifierPci, FALSE) == 0)
+      else
       {
-         pHardwareId = &HardwareIdPci;
-         DeviceIndex = DeviceIndexPci++;
+         /* Assign hardware id to this device */
+         ValueName.Length = ValueName.MaximumLength = (USHORT)pValueInformation->DataLength;
+         ValueName.Buffer = (PWCHAR)pValueInformation->Data;
+         if (ValueName.Length >= sizeof(WCHAR) && ValueName.Buffer[ValueName.Length / sizeof(WCHAR) - 1] == UNICODE_NULL)
+            ValueName.Length -= sizeof(WCHAR);
       }
-      /*else if (RtlCompareUnicodeString(&ValueName, &IdentifierAcpi, FALSE) == 0)
-      {
-         pHardwareId = &HardwareIdAcpi;
-         DeviceIndex = DeviceIndexAcpi++;
-      }*/
-      else 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++;
       }
+      else if (NT_SUCCESS(Status))
+      {
+         /* Try to also match the device identifier */
+         if (RtlCompareUnicodeString(&ValueName, &IdentifierPci, FALSE) == 0)
+         {
+            pHardwareId = &HardwareIdPci;
+            DeviceIndex = DeviceIndexPci++;
+         }
+#ifdef ENABLE_ACPI
+         else if (RtlCompareUnicodeString(&ValueName, &IdentifierAcpi, FALSE) == 0)
+         {
+            pHardwareId = &HardwareIdAcpi;
+            DeviceIndex = DeviceIndexAcpi++;
+         }
+#endif
+         else
+         {
+            /* Unknown device */
+            DPRINT("Unknown device '%wZ'\n", &ValueName);
+            goto nextdevice;
+         }
+      }
       else
       {
-         /* Unknown device */
-         DPRINT("Unknown device %wZ in %wZ\n", &ValueName, RelativePath);
+         /* Unknown key path */
+         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,
@@ -2832,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))
       {
@@ -2847,36 +3023,7 @@ IopEnumerateDetectedDevices(
          ZwDeleteKey(hLevel2Key);
          goto nextdevice;
       }
-      /* Copy 'Configuration Data' to 'LogConf\BootConfig' */
-      Status = ZwQueryValueKey(hDeviceKey, &ConfigurationDataU, KeyValuePartialInformation, pValueInformation, ValueInfoLength, &RequiredSize);
-      if (Status == STATUS_BUFFER_OVERFLOW)
-      {
-         ExFreePool(pValueInformation);
-         ValueInfoLength = RequiredSize;
-         pValueInformation = ExAllocatePool(PagedPool, ValueInfoLength);
-         if (!pValueInformation)
-         {
-            DPRINT("ExAllocatePool() failed\n");
-            ZwDeleteKey(hLevel2Key);
-            Status = STATUS_NO_MEMORY;
-            goto cleanup;
-         }
-         Status = ZwQueryValueKey(hDeviceKey, &ConfigurationDataU, KeyValuePartialInformation, pValueInformation, ValueInfoLength, &RequiredSize);
-      }
-      if (Status == STATUS_OBJECT_NAME_NOT_FOUND)
-         goto nextdevice;
-      else if (!NT_SUCCESS(Status))
-      {
-         DPRINT("ZwQueryValueKey() failed with status 0x%08lx\n", Status);
-         ZwDeleteKey(hLevel2Key);
-         goto nextdevice;
-      }
-      else if (pValueInformation->Type != REG_FULL_RESOURCE_DESCRIPTOR)
-      {
-         DPRINT("Wrong registry type: got 0x%lx, expected 0x%lx\n", pValueInformation->Type, REG_FULL_RESOURCE_DESCRIPTOR);
-         ZwDeleteKey(hLevel2Key);
-         goto nextdevice;
-      }
+      /* Create 'LogConf' subkey */
       InitializeObjectAttributes(&ObjectAttributes, &LogConfU, OBJ_KERNEL_HANDLE, hLevel2Key, NULL);
       Status = ZwCreateKey(
          &hLogConf,
@@ -2892,16 +3039,23 @@ IopEnumerateDetectedDevices(
          ZwDeleteKey(hLevel2Key);
          goto nextdevice;
       }
-      Status = ZwSetValueKey(hLogConf, &BootConfigU, 0, pValueInformation->Type, pValueInformation->Data, pValueInformation->DataLength);
-      ZwClose(hLogConf);
-      if (!NT_SUCCESS(Status))
+      if (BootResourcesLength > 0)
       {
-         DPRINT("ZwSetValueKey() failed with status 0x%08lx\n", Status);
-         ZwDeleteKey(hLevel2Key);
-         goto nextdevice;
+         /* Save boot resources to 'LogConf\BootConfig' */
+         Status = ZwSetValueKey(hLogConf, &BootConfigU, 0, REG_FULL_RESOURCE_DESCRIPTOR, BootResources, BootResourcesLength);
+         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)
+         ExFreePool(BootResources);
       if (hLevel2Key)
       {
          ZwClose(hLevel2Key);
@@ -2917,7 +3071,7 @@ nextdevice:
    Status = STATUS_SUCCESS;
 
 cleanup:
-   if (hDevicesKey)
+   if (hDevicesKey && hDevicesKey != hBaseKey)
       ZwClose(hDevicesKey);
    if (hDeviceKey)
       ZwClose(hDeviceKey);
@@ -2931,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");
@@ -3070,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;
@@ -3110,33 +3271,208 @@ 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);
-      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
-PnpInit2(VOID)
+PnpInit(VOID)
 {
-   NTSTATUS Status;
+    PDEVICE_OBJECT Pdo;
+    NTSTATUS Status;
 
-   /* Move information about devices detected by Freeloader to SYSTEM\CurrentControlSet\Root\ */
-   Status = IopUpdateRootKey();
-   if (!NT_SUCCESS(Status))
-   {
-      CPRINT("IopUpdateRootKey() failed\n");
-      KEBUGCHECKEX(PHASE1_INITIALIZATION_FAILED, Status, 0, 0, 0);
-   }
+    DPRINT("PnpInit()\n");
+
+    KeInitializeSpinLock(&IopDeviceTreeLock);
+
+    /* Initialize the Bus Type GUID List */
+    IopBusTypeGuidList = ExAllocatePool(PagedPool, sizeof(IO_BUS_TYPE_GUID_LIST));
+    RtlZeroMemory(IopBusTypeGuidList, sizeof(IO_BUS_TYPE_GUID_LIST));
+    ExInitializeFastMutex(&IopBusTypeGuidList->Lock);
+
+    /* Initialize PnP-Event notification support */
+    Status = IopInitPlugPlayEvents();
+    if (!NT_SUCCESS(Status))
+    {
+        CPRINT("IopInitPlugPlayEvents() failed\n");
+        KEBUGCHECKEX(PHASE1_INITIALIZATION_FAILED, Status, 0, 0, 0);
+    }
+
+    /*
+    * Create root device node
+    */
+
+    Status = IopCreateDriver(NULL, PnpDriverInitializeEmpty, NULL, 0, 0, &IopRootDriverObject);
+    if (!NT_SUCCESS(Status))
+    {
+        CPRINT("IoCreateDriverObject() failed\n");
+        KEBUGCHECKEX(PHASE1_INITIALIZATION_FAILED, Status, 0, 0, 0);
+    }
+
+    Status = IoCreateDevice(IopRootDriverObject, 0, NULL, FILE_DEVICE_CONTROLLER,
+        0, FALSE, &Pdo);
+    if (!NT_SUCCESS(Status))
+    {
+        CPRINT("IoCreateDevice() failed\n");
+        KEBUGCHECKEX(PHASE1_INITIALIZATION_FAILED, Status, 0, 0, 0);
+    }
+
+    Status = IopCreateDeviceNode(NULL, Pdo, NULL, &IopRootDeviceNode);
+    if (!NT_SUCCESS(Status))
+    {
+        CPRINT("Insufficient resources\n");
+        KEBUGCHECKEX(PHASE1_INITIALIZATION_FAILED, Status, 0, 0, 0);
+    }
+
+    if (!RtlCreateUnicodeString(&IopRootDeviceNode->InstancePath,
+        L"HTREE\\ROOT\\0"))
+    {
+        CPRINT("Failed to create the instance path!\n");
+        KEBUGCHECKEX(PHASE1_INITIALIZATION_FAILED, STATUS_NO_MEMORY, 0, 0, 0);
+    }
+
+    /* Report the device to the user-mode pnp manager */
+    IopQueueTargetDeviceEvent(&GUID_DEVICE_ARRIVAL,
+        &IopRootDeviceNode->InstancePath);
+
+    IopRootDeviceNode->PhysicalDeviceObject->Flags |= DO_BUS_ENUMERATED_DEVICE;
+    PnpRootDriverEntry(IopRootDriverObject, NULL);
+    IopRootDeviceNode->PhysicalDeviceObject->Flags &= ~DO_DEVICE_INITIALIZING;
+    IopRootDriverObject->DriverExtension->AddDevice(
+        IopRootDriverObject,
+        IopRootDeviceNode->PhysicalDeviceObject);
+
+    /* Move information about devices detected by Freeloader to SYSTEM\CurrentControlSet\Root\ */
+    Status = IopUpdateRootKey();
+    if (!NT_SUCCESS(Status))
+    {
+        CPRINT("IopUpdateRootKey() failed\n");
+        KEBUGCHECKEX(PHASE1_INITIALIZATION_FAILED, Status, 0, 0, 0);
+    }
+}
+
+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 */