Index: trunk/src/VBox/Additions/WINNT/Graphics/Video/common/wddm/VBoxMPIf.h
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Video/common/wddm/VBoxMPIf.h	(revision 48058)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Video/common/wddm/VBoxMPIf.h	(revision 48070)
@@ -252,5 +252,9 @@
     VBOXWDDM_CONTEXT_TYPE_CUSTOM_UHGSMI_GL,
     /* context created by the kernel->user communication mechanism for visible rects reporting, etc.  */
-    VBOXWDDM_CONTEXT_TYPE_CUSTOM_SESSION
+    VBOXWDDM_CONTEXT_TYPE_CUSTOM_SESSION,
+    /* context created by VBoxTray to handle resize operations */
+    VBOXWDDM_CONTEXT_TYPE_CUSTOM_DISPIF_RESIZE,
+    /* context created by VBoxTray to handle seamless operations */
+    VBOXWDDM_CONTEXT_TYPE_CUSTOM_DISPIF_SEAMLESS
 } VBOXWDDM_CONTEXT_TYPE;
 
Index: trunk/src/VBox/Additions/WINNT/Graphics/Video/disp/wddm/VBoxDispD3D.h
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Video/disp/wddm/VBoxDispD3D.h	(revision 48058)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Video/disp/wddm/VBoxDispD3D.h	(revision 48070)
@@ -21,5 +21,5 @@
 
 #include "VBoxDispD3DIf.h"
-#include "common/wddm/VBoxMPIf.h"
+#include "../../common/wddm/VBoxMPIf.h"
 #ifdef VBOX_WITH_CRHGSMI
 #include "VBoxUhgsmiDisp.h"
Index: trunk/src/VBox/Additions/WINNT/Graphics/Video/disp/wddm/VBoxDispD3DCmn.h
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Video/disp/wddm/VBoxDispD3DCmn.h	(revision 48058)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Video/disp/wddm/VBoxDispD3DCmn.h	(revision 48070)
@@ -19,28 +19,5 @@
 #define ___VBoxDispD3DCmn_h___
 
-#       define _InterlockedExchange           _InterlockedExchange_StupidDDKVsCompilerCrap
-#       define _InterlockedExchangeAdd        _InterlockedExchangeAdd_StupidDDKVsCompilerCrap
-#       define _InterlockedCompareExchange    _InterlockedCompareExchange_StupidDDKVsCompilerCrap
-#       define _InterlockedAddLargeStatistic  _InterlockedAddLargeStatistic_StupidDDKVsCompilerCrap
-#       define _interlockedbittestandset      _interlockedbittestandset_StupidDDKVsCompilerCrap
-#       define _interlockedbittestandreset    _interlockedbittestandreset_StupidDDKVsCompilerCrap
-#       define _interlockedbittestandset64    _interlockedbittestandset64_StupidDDKVsCompilerCrap
-#       define _interlockedbittestandreset64  _interlockedbittestandreset64_StupidDDKVsCompilerCrap
-#       pragma warning(disable : 4163)
-#include <windows.h>
-#       pragma warning(default : 4163)
-#       undef  _InterlockedExchange
-#       undef  _InterlockedExchangeAdd
-#       undef  _InterlockedCompareExchange
-#       undef  _InterlockedAddLargeStatistic
-#       undef  _interlockedbittestandset
-#       undef  _interlockedbittestandreset
-#       undef  _interlockedbittestandset64
-#       undef  _interlockedbittestandreset64
-
-#include <d3d9types.h>
-//#include <d3dtypes.h>
-#include <D3dumddi.h>
-#include <d3dhal.h>
+#include "VBoxDispD3DBase.h"
 
 #include <iprt/initterm.h>
@@ -54,5 +31,5 @@
 #include "VBoxDispDbg.h"
 #include "VBoxDispD3DIf.h"
-#include "common/wddm/VBoxMPIf.h"
+#include "../../common/wddm/VBoxMPIf.h"
 #include "VBoxDispCm.h"
 #include "VBoxDispMpInternal.h"
Index: trunk/src/VBox/Additions/WINNT/Graphics/Video/disp/wddm/VBoxDispKmt.cpp
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Video/disp/wddm/VBoxDispKmt.cpp	(revision 48058)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Video/disp/wddm/VBoxDispKmt.cpp	(revision 48070)
@@ -17,5 +17,9 @@
  */
 
-#include "VBoxDispD3DCmn.h"
+#include "VBoxDispD3DBase.h"
+#include "VBoxDispKmt.h"
+
+#include <iprt/assert.h>
+#include <iprt/log.h>
 
 #ifndef NT_SUCCESS
@@ -103,4 +107,12 @@
         Log((__FUNCTION__": pfnD3DKMTUnlock = %p\n", pCallbacks->pfnD3DKMTUnlock));
         bSupported &= !!(pCallbacks->pfnD3DKMTUnlock);
+
+        pCallbacks->pfnD3DKMTInvalidateActiveVidPn = (PFND3DKMT_INVALIDATEACTIVEVIDPN)GetProcAddress(pCallbacks->hGdi32, "D3DKMTInvalidateActiveVidPn");
+        Log((__FUNCTION__": pfnD3DKMTInvalidateActiveVidPn = %p\n", pCallbacks->pfnD3DKMTInvalidateActiveVidPn));
+        bSupported &= !!(pCallbacks->pfnD3DKMTInvalidateActiveVidPn);
+
+        pCallbacks->pfnD3DKMTPollDisplayChildren = (PFND3DKMT_POLLDISPLAYCHILDREN)GetProcAddress(pCallbacks->hGdi32, "D3DKMTPollDisplayChildren");
+        Log((__FUNCTION__": pfnD3DKMTPollDisplayChildren = %p\n", pCallbacks->pfnD3DKMTPollDisplayChildren));
+        bSupported &= !!(pCallbacks->pfnD3DKMTPollDisplayChildren);
 
         pCallbacks->pfnD3DKMTEnumAdapters = (PFND3DKMT_ENUMADAPTERS)GetProcAddress(pCallbacks->hGdi32, "D3DKMTEnumAdapters");
@@ -204,5 +216,5 @@
 }
 
-static HRESULT vboxDispKmtOpenAdapterViaHdc(PVBOXDISPKMT_CALLBACKS pCallbacks, PVBOXDISPKMT_ADAPTER pAdapter)
+static HRESULT vboxDispKmtOpenAdapterViaHdc(const VBOXDISPKMT_CALLBACKS *pCallbacks, PVBOXDISPKMT_ADAPTER pAdapter)
 {
     D3DKMT_OPENADAPTERFROMHDC OpenAdapterData = {0};
@@ -232,5 +244,5 @@
 }
 
-static HRESULT vboxDispKmtOpenAdapterViaLuid(PVBOXDISPKMT_CALLBACKS pCallbacks, PVBOXDISPKMT_ADAPTER pAdapter)
+static HRESULT vboxDispKmtOpenAdapterViaLuid(const VBOXDISPKMT_CALLBACKS *pCallbacks, PVBOXDISPKMT_ADAPTER pAdapter)
 {
     if (pCallbacks->enmVersion < VBOXDISPKMT_CALLBACKS_VERSION_WIN8)
@@ -281,5 +293,5 @@
 }
 
-HRESULT vboxDispKmtOpenAdapter(PVBOXDISPKMT_CALLBACKS pCallbacks, PVBOXDISPKMT_ADAPTER pAdapter)
+HRESULT vboxDispKmtOpenAdapter(const VBOXDISPKMT_CALLBACKS *pCallbacks, PVBOXDISPKMT_ADAPTER pAdapter)
 {
     HRESULT hr = vboxDispKmtOpenAdapterViaHdc(pCallbacks, pAdapter);
Index: trunk/src/VBox/Additions/WINNT/Graphics/Video/disp/wddm/VBoxDispKmt.h
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Video/disp/wddm/VBoxDispKmt.h	(revision 48058)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Video/disp/wddm/VBoxDispKmt.h	(revision 48070)
@@ -21,4 +21,6 @@
 
 #include <D3dkmthk.h>
+
+#include "../../common/wddm/VBoxMPIf.h"
 
 /* win8 release preview-specific stuff */
@@ -82,4 +84,9 @@
     PFND3DKMT_UNLOCK pfnD3DKMTUnlock;
 
+    /* auto resize support */
+    PFND3DKMT_INVALIDATEACTIVEVIDPN pfnD3DKMTInvalidateActiveVidPn;
+    PFND3DKMT_POLLDISPLAYCHILDREN pfnD3DKMTPollDisplayChildren;
+
+    /* win8 specifics */
     PFND3DKMT_ENUMADAPTERS pfnD3DKMTEnumAdapters;
     PFND3DKMT_OPENADAPTERFROMLUID pfnD3DKMTOpenAdapterFromLuid;
@@ -91,5 +98,5 @@
     HDC hDc;
     LUID Luid;
-    PVBOXDISPKMT_CALLBACKS pCallbacks;
+    const VBOXDISPKMT_CALLBACKS *pCallbacks;
 }VBOXDISPKMT_ADAPTER, *PVBOXDISPKMT_ADAPTER;
 
@@ -121,5 +128,5 @@
 HRESULT vboxDispKmtCallbacksTerm(PVBOXDISPKMT_CALLBACKS pCallbacks);
 
-HRESULT vboxDispKmtOpenAdapter(PVBOXDISPKMT_CALLBACKS pCallbacks, PVBOXDISPKMT_ADAPTER pAdapter);
+HRESULT vboxDispKmtOpenAdapter(const VBOXDISPKMT_CALLBACKS *pCallbacks, PVBOXDISPKMT_ADAPTER pAdapter);
 HRESULT vboxDispKmtCloseAdapter(PVBOXDISPKMT_ADAPTER pAdapter);
 HRESULT vboxDispKmtCreateDevice(PVBOXDISPKMT_ADAPTER pAdapter, PVBOXDISPKMT_DEVICE pDevice);
Index: trunk/src/VBox/Additions/WINNT/Graphics/Video/mp/common/VBoxMPCommon.h
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Video/mp/common/VBoxMPCommon.h	(revision 48058)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Video/mp/common/VBoxMPCommon.h	(revision 48070)
@@ -42,8 +42,6 @@
 
 #ifdef VBOX_WDDM_MINIPORT
-void VBoxWddmInvalidateAllVideoModesInfos(PVBOXMP_DEVEXT pExt);
-void VBoxWddmInvalidateVideoModesInfo(PVBOXMP_DEVEXT pExt, D3DDDI_VIDEO_PRESENT_TARGET_ID VidPnTargetId);
 PVBOXWDDM_VIDEOMODES_INFO VBoxWddmUpdateVideoModesInfoByMask(PVBOXMP_DEVEXT pExt, uint8_t *pScreenIdMask);
-PVBOXWDDM_VIDEOMODES_INFO VBoxWddmUpdateAllVideoModesInfos(PVBOXMP_DEVEXT pExt);
+void VBoxWddmInitVideoModes(PVBOXMP_DEVEXT pExt);
 NTSTATUS VBoxWddmGetModesForResolution(VIDEO_MODE_INFORMATION *pAllModes, uint32_t cAllModes, int iSearchPreferredMode,
                                        const D3DKMDT_2DREGION *pResolution, VIDEO_MODE_INFORMATION * pModes,
Index: trunk/src/VBox/Additions/WINNT/Graphics/Video/mp/common/VBoxMPDevExt.h
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Video/mp/common/VBoxMPDevExt.h	(revision 48058)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Video/mp/common/VBoxMPDevExt.h	(revision 48070)
@@ -100,4 +100,5 @@
 
    VBOXVIDEOCM_MGR CmMgr;
+   VBOXVIDEOCM_MGR SeamlessCtxMgr;
    /* hgsmi allocation manager */
    VBOXVIDEOCM_ALLOC_MGR AllocMgr;
@@ -110,6 +111,9 @@
    volatile uint32_t cContexts3D;
    volatile uint32_t cContexts2D;
+   volatile uint32_t cContextsDispIfResize;
    volatile uint32_t cRenderFromShadowDisabledContexts;
    volatile uint32_t cUnlockedVBVADisabled;
+
+   DWORD dwDrvCfgFlags;
    /* this is examined and swicthed by DxgkDdiSubmitCommand only! */
    volatile BOOLEAN fRenderToShadowDisabled;
Index: trunk/src/VBox/Additions/WINNT/Graphics/Video/mp/common/VBoxMPVidModes.cpp
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Video/mp/common/VBoxMPVidModes.cpp	(revision 48058)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Video/mp/common/VBoxMPVidModes.cpp	(revision 48070)
@@ -900,4 +900,5 @@
 #ifdef VBOX_WDDM_MINIPORT
 static VBOXWDDM_VIDEOMODES_INFO g_aVBoxVideoModeInfos[VBOX_VIDEO_MAX_SCREENS] = {0};
+static VBOXWDDM_VIDEOMODES_INFO g_VBoxVideoModeTmp;
 
 bool VBoxWddmFillMode(PVBOXMP_DEVEXT pExt, uint32_t iDisplay, VIDEO_MODE_INFORMATION *pInfo, D3DDDIFORMAT enmFormat, ULONG w, ULONG h)
@@ -954,4 +955,5 @@
 
     *piPreferredResolution = -1;
+    *pcResolutions = 0;
 
     for (uint32_t i=0; i<tableSize; ++i)
@@ -1003,4 +1005,5 @@
     Assert(pModes->aResolutions[pModes->iPreferredResolution].cx == pModes->aModes[pModes->iPreferredMode].VisScreenWidth
             && pModes->aResolutions[pModes->iPreferredResolution].cy == pModes->aModes[pModes->iPreferredMode].VisScreenHeight);
+    Assert(pModes->cModes >= pModes->cResolutions);
 }
 
@@ -1225,29 +1228,262 @@
 }
 
-void VBoxWddmInvalidateVideoModesInfo(PVBOXMP_DEVEXT pExt, D3DDDI_VIDEO_PRESENT_TARGET_ID VidPnTargetId)
-{
-    if (VidPnTargetId != D3DDDI_ID_ALL)
-    {
-        if (VidPnTargetId >= RT_ELEMENTS(g_aVBoxVideoModeInfos))
-        {
-            WARN(("VidPnTargetId (%d) must be less than (%d)", VidPnTargetId, RT_ELEMENTS(g_aVBoxVideoModeInfos)));
-            return;
-        }
-        LOG(("invalidating videomede info for screen %d", VidPnTargetId));
-        g_aVBoxVideoModeInfos[VidPnTargetId].cModes = 0;
+static void VBoxWddmInitVideoMode(PVBOXMP_DEVEXT pExt, int i)
+{
+    VBoxWddmBuildVideoModesInfo(pExt, (D3DDDI_VIDEO_PRESENT_TARGET_ID)i, &g_aVBoxVideoModeInfos[i], NULL, 0);
+}
+
+void VBoxWddmInitVideoModes(PVBOXMP_DEVEXT pExt)
+{
+    for (int i = 0; i < VBoxCommonFromDeviceExt(pExt)->cDisplays; ++i)
+    {
+        VBoxWddmInitVideoMode(pExt, i);
+    }
+}
+
+static NTSTATUS vboxWddmChildStatusReportPerform(PVBOXMP_DEVEXT pDevExt, PVBOXVDMA_CHILD_STATUS pChildStatus, D3DDDI_VIDEO_PRESENT_TARGET_ID iChild)
+{
+    DXGK_CHILD_STATUS DdiChildStatus;
+
+    Assert(iChild < UINT32_MAX/2);
+    Assert(iChild < (UINT)VBoxCommonFromDeviceExt(pDevExt)->cDisplays);
+
+    PVBOXWDDM_TARGET pTarget = &pDevExt->aTargets[iChild];
+
+    if ((pChildStatus->fFlags & VBOXVDMA_CHILD_STATUS_F_DISCONNECTED)
+            && pTarget->fConnected)
+    {
+        /* report disconnected */
+        memset(&DdiChildStatus, 0, sizeof (DdiChildStatus));
+        DdiChildStatus.Type = StatusConnection;
+        DdiChildStatus.ChildUid = iChild;
+        DdiChildStatus.HotPlug.Connected = FALSE;
+
+        LOG(("Reporting DISCONNECT to child %d", DdiChildStatus.ChildUid));
+
+        NTSTATUS Status = pDevExt->u.primary.DxgkInterface.DxgkCbIndicateChildStatus(pDevExt->u.primary.DxgkInterface.DeviceHandle, &DdiChildStatus);
+        if (!NT_SUCCESS(Status))
+        {
+            WARN(("DxgkCbIndicateChildStatus failed with Status (0x%x)", Status));
+            return Status;
+        }
+        pTarget->fConnected = FALSE;
+    }
+
+    if ((pChildStatus->fFlags & VBOXVDMA_CHILD_STATUS_F_CONNECTED)
+            && !pTarget->fConnected)
+    {
+        /* report disconnected */
+        memset(&DdiChildStatus, 0, sizeof (DdiChildStatus));
+        DdiChildStatus.Type = StatusConnection;
+        DdiChildStatus.ChildUid = iChild;
+        DdiChildStatus.HotPlug.Connected = TRUE;
+
+        LOG(("Reporting CONNECT to child %d", DdiChildStatus.ChildUid));
+
+        NTSTATUS Status = pDevExt->u.primary.DxgkInterface.DxgkCbIndicateChildStatus(pDevExt->u.primary.DxgkInterface.DeviceHandle, &DdiChildStatus);
+        if (!NT_SUCCESS(Status))
+        {
+            WARN(("DxgkCbIndicateChildStatus failed with Status (0x%x)", Status));
+            return Status;
+        }
+        pTarget->fConnected = TRUE;
+    }
+
+    if (pChildStatus->fFlags & VBOXVDMA_CHILD_STATUS_F_ROTATED)
+    {
+        /* report disconnected */
+        memset(&DdiChildStatus, 0, sizeof (DdiChildStatus));
+        DdiChildStatus.Type = StatusRotation;
+        DdiChildStatus.ChildUid = iChild;
+        DdiChildStatus.Rotation.Angle = pChildStatus->u8RotationAngle;
+
+        LOG(("Reporting ROTATED to child %d", DdiChildStatus.ChildUid));
+
+        NTSTATUS Status = pDevExt->u.primary.DxgkInterface.DxgkCbIndicateChildStatus(pDevExt->u.primary.DxgkInterface.DeviceHandle, &DdiChildStatus);
+        if (!NT_SUCCESS(Status))
+        {
+            WARN(("DxgkCbIndicateChildStatus failed with Status (0x%x)", Status));
+            return Status;
+        }
+    }
+
+    return STATUS_SUCCESS;
+}
+
+static NTSTATUS vboxWddmChildStatusHandleRequest(PVBOXMP_DEVEXT pDevExt, VBOXVDMACMD_CHILD_STATUS_IRQ *pBody)
+{
+    NTSTATUS Status = STATUS_SUCCESS;
+
+    for (UINT i = 0; i < pBody->cInfos; ++i)
+    {
+        PVBOXVDMA_CHILD_STATUS pInfo = &pBody->aInfos[i];
+        if (pBody->fFlags & VBOXVDMACMD_CHILD_STATUS_IRQ_F_APPLY_TO_ALL)
+        {
+            for (D3DDDI_VIDEO_PRESENT_TARGET_ID iChild = 0; iChild < (UINT)VBoxCommonFromDeviceExt(pDevExt)->cDisplays; ++iChild)
+            {
+                Status = vboxWddmChildStatusReportPerform(pDevExt, pInfo, iChild);
+                if (!NT_SUCCESS(Status))
+                {
+                    WARN(("vboxWddmChildStatusReportPerform failed with Status (0x%x)", Status));
+                    break;
+                }
+            }
+        }
+        else
+        {
+            Status = vboxWddmChildStatusReportPerform(pDevExt, pInfo, pInfo->iChild);
+            if (!NT_SUCCESS(Status))
+            {
+                WARN(("vboxWddmChildStatusReportPerform failed with Status (0x%x)", Status));
+                break;
+            }
+        }
+    }
+
+    return Status;
+}
+
+#ifdef VBOX_WDDM_MONITOR_REPLUG_IRQ
+typedef struct VBOXWDDMCHILDSTATUSCB
+{
+    PVBOXVDMACBUF_DR pDr;
+    PKEVENT pEvent;
+} VBOXWDDMCHILDSTATUSCB, *PVBOXWDDMCHILDSTATUSCB;
+
+static DECLCALLBACK(VOID) vboxWddmChildStatusReportCompletion(PVBOXMP_DEVEXT pDevExt, PVBOXVDMADDI_CMD pCmd, PVOID pvContext)
+{
+    /* we should be called from our DPC routine */
+    Assert(KeGetCurrentIrql() == DISPATCH_LEVEL);
+
+    PVBOXWDDMCHILDSTATUSCB pCtx = (PVBOXWDDMCHILDSTATUSCB)pvContext;
+    PVBOXVDMACBUF_DR pDr = pCtx->pDr;
+    PVBOXVDMACMD pHdr = VBOXVDMACBUF_DR_TAIL(pDr, VBOXVDMACMD);
+    VBOXVDMACMD_CHILD_STATUS_IRQ *pBody = VBOXVDMACMD_BODY(pHdr, VBOXVDMACMD_CHILD_STATUS_IRQ);
+
+    vboxWddmChildStatusHandleRequest(pDevExt, pBody);
+
+    vboxVdmaCBufDrFree(&pDevExt->u.primary.Vdma, pDr);
+
+    if (pCtx->pEvent)
+    {
+        KeSetEvent(pCtx->pEvent, 0, FALSE);
+    }
+}
+#endif
+
+static NTSTATUS vboxWddmChildStatusReportReconnected(PVBOXMP_DEVEXT pDevExt, D3DDDI_VIDEO_PRESENT_TARGET_ID idTarget)
+{
+#ifdef VBOX_WDDM_MONITOR_REPLUG_IRQ
+    NTSTATUS Status = STATUS_UNSUCCESSFUL;
+    UINT cbCmd = VBOXVDMACMD_SIZE_FROMBODYSIZE(sizeof (VBOXVDMACMD_CHILD_STATUS_IRQ));
+
+    PVBOXVDMACBUF_DR pDr = vboxVdmaCBufDrCreate(&pDevExt->u.primary.Vdma, cbCmd);
+    if (pDr)
+    {
+        // vboxVdmaCBufDrCreate zero initializes the pDr
+        /* the command data follows the descriptor */
+        pDr->fFlags = VBOXVDMACBUF_FLAG_BUF_FOLLOWS_DR;
+        pDr->cbBuf = cbCmd;
+        pDr->rc = VERR_NOT_IMPLEMENTED;
+
+        PVBOXVDMACMD pHdr = VBOXVDMACBUF_DR_TAIL(pDr, VBOXVDMACMD);
+        pHdr->enmType = VBOXVDMACMD_TYPE_CHILD_STATUS_IRQ;
+        pHdr->u32CmdSpecific = 0;
+        PVBOXVDMACMD_CHILD_STATUS_IRQ pBody = VBOXVDMACMD_BODY(pHdr, VBOXVDMACMD_CHILD_STATUS_IRQ);
+        pBody->cInfos = 1;
+        if (idTarget == D3DDDI_ID_ALL)
+        {
+            pBody->fFlags |= VBOXVDMACMD_CHILD_STATUS_IRQ_F_APPLY_TO_ALL;
+        }
+        pBody->aInfos[0].iChild = idTarget;
+        pBody->aInfos[0].fFlags = VBOXVDMA_CHILD_STATUS_F_DISCONNECTED | VBOXVDMA_CHILD_STATUS_F_CONNECTED;
+        /* we're going to KeWaitForSingleObject */
+        Assert(KeGetCurrentIrql() < DISPATCH_LEVEL);
+
+        PVBOXVDMADDI_CMD pDdiCmd = VBOXVDMADDI_CMD_FROM_BUF_DR(pDr);
+        VBOXWDDMCHILDSTATUSCB Ctx;
+        KEVENT Event;
+        KeInitializeEvent(&Event, NotificationEvent, FALSE);
+        Ctx.pDr = pDr;
+        Ctx.pEvent = &Event;
+        vboxVdmaDdiCmdInit(pDdiCmd, 0, 0, vboxWddmChildStatusReportCompletion, &Ctx);
+        /* mark command as submitted & invisible for the dx runtime since dx did not originate it */
+        vboxVdmaDdiCmdSubmittedNotDx(pDdiCmd);
+        int rc = vboxVdmaCBufDrSubmit(pDevExt, &pDevExt->u.primary.Vdma, pDr);
+        Assert(rc == VINF_SUCCESS);
+        if (RT_SUCCESS(rc))
+        {
+            Status = KeWaitForSingleObject(&Event, Executive, KernelMode, FALSE, NULL);
+            Assert(Status == STATUS_SUCCESS);
+            return STATUS_SUCCESS;
+        }
+
+        Status = STATUS_UNSUCCESSFUL;
+
+        vboxVdmaCBufDrFree(&pDevExt->u.primary.Vdma, pDr);
+    }
+    else
+    {
+        /* @todo: try flushing.. */
+        WARN(("vboxVdmaCBufDrCreate returned NULL"));
+        Status = STATUS_INSUFFICIENT_RESOURCES;
+    }
+
+    return Status;
+#else
+    VBOXVDMACMD_CHILD_STATUS_IRQ Body = {0};
+    Body.cInfos = 1;
+    if (idTarget == D3DDDI_ID_ALL)
+    {
+        Body.fFlags |= VBOXVDMACMD_CHILD_STATUS_IRQ_F_APPLY_TO_ALL;
+    }
+    Body.aInfos[0].iChild = idTarget;
+    Body.aInfos[0].fFlags = VBOXVDMA_CHILD_STATUS_F_DISCONNECTED | VBOXVDMA_CHILD_STATUS_F_CONNECTED;
+    Assert(KeGetCurrentIrql() <= DISPATCH_LEVEL);
+    return vboxWddmChildStatusHandleRequest(pDevExt, &Body);
+#endif
+}
+
+NTSTATUS vboxWddmChildStatusConnect(PVBOXMP_DEVEXT pDevExt, uint32_t iChild, BOOLEAN fConnect)
+{
+#ifdef VBOX_WDDM_MONITOR_REPLUG_IRQ
+# error "port me!"
+#else
+    Assert(iChild < (uint32_t)VBoxCommonFromDeviceExt(pDevExt)->cDisplays);
+    NTSTATUS Status = STATUS_SUCCESS;
+    VBOXVDMACMD_CHILD_STATUS_IRQ Body = {0};
+    Body.cInfos = 1;
+    Body.aInfos[0].iChild = iChild;
+    Body.aInfos[0].fFlags = fConnect ? VBOXVDMA_CHILD_STATUS_F_CONNECTED : VBOXVDMA_CHILD_STATUS_F_DISCONNECTED;
+    Assert(KeGetCurrentIrql() <= DISPATCH_LEVEL);
+    Status = vboxWddmChildStatusHandleRequest(pDevExt, &Body);
+    if (!NT_SUCCESS(Status))
+        WARN(("vboxWddmChildStatusHandleRequest failed Status 0x%x", Status));
+
+    return Status;
+#endif
+}
+
+void VBoxWddmUpdateVideoMode(PVBOXMP_DEVEXT pExt, int i)
+{
+    g_VBoxVideoModeTmp = g_aVBoxVideoModeInfos[i];
+
+    Assert(g_aVBoxVideoModeInfos[i].cModes);
+
+    VBoxWddmInitVideoMode(pExt, i);
+
+    if (!memcmp(&g_VBoxVideoModeTmp, &g_aVBoxVideoModeInfos[i], sizeof (g_VBoxVideoModeTmp)))
         return;
-    }
-
-    LOG(("invalidating ALL videomede infos"));
-
-    for (UINT i = 0; i < RT_ELEMENTS(g_aVBoxVideoModeInfos); ++i)
-    {
-        g_aVBoxVideoModeInfos[i].cModes = 0;
-    }
-}
-
-void VBoxWddmInvalidateAllVideoModesInfos(PVBOXMP_DEVEXT pExt)
-{
-    VBoxWddmInvalidateVideoModesInfo(pExt, D3DDDI_ID_ALL);
+
+#ifdef DEBUG_misha
+    g_VBoxDbgBreakModes = 0;
+#endif
+
+#ifdef DEBUG_misha
+    LOGREL(("modes changed for target %d", i));
+#else
+    LOG(("modes changed for target %d", i));
+#endif
+    vboxWddmChildStatusReportReconnected(pExt, (D3DDDI_VIDEO_PRESENT_TARGET_ID)i);
 }
 
@@ -1256,19 +1492,10 @@
     for (int i = 0; i < VBoxCommonFromDeviceExt(pExt)->cDisplays; ++i)
     {
-        if (ASMBitTest(pScreenIdMask, i))
-            VBoxWddmInvalidateVideoModesInfo(pExt, i);
-    }
-
-    /* ensure we have all the rest populated */
-    VBoxWddmGetAllVideoModesInfos(pExt);
-    return g_aVBoxVideoModeInfos;
-}
-
-PVBOXWDDM_VIDEOMODES_INFO VBoxWddmUpdateAllVideoModesInfos(PVBOXMP_DEVEXT pExt)
-{
-    VBoxWddmInvalidateAllVideoModesInfos(pExt);
-
-    /* ensure we have all the rest populated */
-    VBoxWddmGetAllVideoModesInfos(pExt);
+        if (!pScreenIdMask || ASMBitTest(pScreenIdMask, i))
+        {
+            VBoxWddmUpdateVideoMode(pExt, i);
+        }
+    }
+
     return g_aVBoxVideoModeInfos;
 }
@@ -1364,48 +1591,6 @@
 }
 
-static PVBOXWDDM_VIDEOMODES_INFO vboxWddmGetVideoModesInfoInternal(PVBOXMP_DEVEXT pExt, D3DDDI_VIDEO_PRESENT_TARGET_ID VidPnTargetId)
-{
-    Assert(VidPnTargetId < (D3DDDI_VIDEO_PRESENT_TARGET_ID)VBoxCommonFromDeviceExt(pExt)->cDisplays);
-    if (VidPnTargetId >= (D3DDDI_VIDEO_PRESENT_TARGET_ID)VBoxCommonFromDeviceExt(pExt)->cDisplays)
-    {
-        WARN(("video mode info for invalid screen (%d) requested", VidPnTargetId));
-        return NULL;
-    }
-
-    PVBOXWDDM_VIDEOMODES_INFO pInfo = &g_aVBoxVideoModeInfos[VidPnTargetId];
-
-    if (!pInfo->cModes)
-    {
-        VBoxWddmBuildVideoModesInfo(pExt, VidPnTargetId, pInfo, NULL, 0);
-        Assert(pInfo->cModes);
-    }
-
-    return pInfo;
-}
-
-static VOID vboxWddmAddVideoModes(PVBOXMP_DEVEXT pExt, PVBOXWDDM_VIDEOMODES_INFO pDstInfo, PVBOXWDDM_VIDEOMODES_INFO pSrcInfo)
-{
-    for (int i = 0; i < (int)pSrcInfo->cModes; ++i)
-    {
-        int foundIdx = VBoxMPFindVideoMode(pDstInfo->aModes, pDstInfo->cModes, &pSrcInfo->aModes[i]);
-        if (foundIdx >= 0)
-            continue;
-
-        Assert(0);
-        pDstInfo->aModes[pDstInfo->cModes] = pSrcInfo->aModes[i];
-        ++pDstInfo->cModes;
-    }
-
-    VBoxWddmBuildResolutionTableForModes(pDstInfo);
-}
-
 PVBOXWDDM_VIDEOMODES_INFO VBoxWddmGetAllVideoModesInfos(PVBOXMP_DEVEXT pExt)
 {
-    /* ensure all modes are initialized */
-    for (int i = 0; i < VBoxCommonFromDeviceExt(pExt)->cDisplays; ++i)
-    {
-        vboxWddmGetVideoModesInfoInternal(pExt, (D3DDDI_VIDEO_PRESENT_TARGET_ID)i);
-    }
-
     return g_aVBoxVideoModeInfos;
 }
Index: trunk/src/VBox/Additions/WINNT/Graphics/Video/mp/wddm/VBoxMPCm.cpp
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Video/mp/wddm/VBoxMPCm.cpp	(revision 48058)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Video/mp/wddm/VBoxMPCm.cpp	(revision 48070)
@@ -72,5 +72,5 @@
     PKEVENT pUmEvent;
     /* sync lock */
-    FAST_MUTEX Mutex;
+    KSPIN_LOCK SynchLock;
     /* indicates whether event signaling is needed on cmd add */
     bool bEventNeeded;
@@ -181,6 +181,8 @@
     }
 
-    Assert(KeGetCurrentIrql() < DISPATCH_LEVEL);
-    ExAcquireFastMutex(&pSession->Mutex);
+    Assert(KeGetCurrentIrql() <= DISPATCH_LEVEL);
+
+    KIRQL OldIrql;
+    KeAcquireSpinLock(&pSession->SynchLock, &OldIrql);
 
     InsertHeadList(&pSession->CommandsList, &pHdr->QueueList);
@@ -191,5 +193,5 @@
     }
 
-    ExReleaseFastMutex(&pSession->Mutex);
+    KeReleaseSpinLock(&pSession->SynchLock, OldIrql);
 
     if (bSignalEvent)
@@ -225,5 +227,6 @@
     PVBOXVIDEOCM_CMD_DR pHdr;
 
-    ExAcquireFastMutex(&pSession->Mutex);
+    KIRQL OldIrql;
+    KeAcquireSpinLock(&pSession->SynchLock, &OldIrql);
 
     pCurEntry = pSession->CommandsList.Blink;
@@ -260,5 +263,5 @@
 
 
-    ExReleaseFastMutex(&pSession->Mutex);
+    KeReleaseSpinLock(&pSession->SynchLock, OldIrql);
 
     return STATUS_SUCCESS;
@@ -280,9 +283,18 @@
 void vboxVideoCmSessionCtxAdd(PVBOXVIDEOCM_SESSION pSession, PVBOXVIDEOCM_CTX pContext)
 {
-    Assert(KeGetCurrentIrql() < DISPATCH_LEVEL);
-    ExAcquireFastMutex(&pSession->Mutex);
+    Assert(KeGetCurrentIrql() <= DISPATCH_LEVEL);
+    KIRQL OldIrql;
+    KeAcquireSpinLock(&pSession->SynchLock, &OldIrql);
+
     vboxVideoCmSessionCtxAddLocked(pSession, pContext);
-    ExReleaseFastMutex(&pSession->Mutex);
-
+
+    KeReleaseSpinLock(&pSession->SynchLock, OldIrql);
+}
+
+void vboxVideoCmSessionSignalEvent(PVBOXVIDEOCM_SESSION pSession)
+{
+    Assert(KeGetCurrentIrql() <= DISPATCH_LEVEL);
+    if (pSession->pUmEvent)
+        KeSetEvent(pSession->pUmEvent, 0, FALSE);
 }
 
@@ -346,6 +358,8 @@
     InitializeListHead(&RemainedList);
     InitializeListHead(&RemainedPpList);
-    Assert(KeGetCurrentIrql() < DISPATCH_LEVEL);
-    ExAcquireFastMutex(&pSession->Mutex);
+    Assert(KeGetCurrentIrql() <= DISPATCH_LEVEL);
+    KIRQL OldIrql;
+    KeAcquireSpinLock(&pSession->SynchLock, &OldIrql);
+
     pContext->pSession = NULL;
     RemoveEntryList(&pContext->SessionEntry);
@@ -362,5 +376,6 @@
         vboxVideoCmSessionCtxDetachCmdsLocked(&pSession->PpCommandsList, pContext, &RemainedPpList);
     }
-    ExReleaseFastMutex(&pSession->Mutex);
+
+    KeReleaseSpinLock(&pSession->SynchLock, OldIrql);
 
     for (pCur = RemainedList.Flink; pCur != &RemainedList; pCur = RemainedList.Flink)
@@ -393,6 +408,6 @@
         InitializeListHead(&pSession->PpCommandsList);
         pSession->pUmEvent = pUmEvent;
-        Assert(KeGetCurrentIrql() < DISPATCH_LEVEL);
-        ExInitializeFastMutex(&pSession->Mutex);
+        Assert(KeGetCurrentIrql() <= DISPATCH_LEVEL);
+        KeInitializeSpinLock(&pSession->SynchLock);
         pSession->bEventNeeded = true;
         vboxVideoCmSessionCtxAddLocked(pSession, pContext);
@@ -421,42 +436,37 @@
     if (Status == STATUS_SUCCESS)
     {
-        Status = KeWaitForSingleObject(&pMgr->SynchEvent, Executive, KernelMode,
-                FALSE, /* BOOLEAN Alertable */
-                NULL /* PLARGE_INTEGER Timeout */
-            );
-        Assert(Status == STATUS_SUCCESS);
+        KIRQL OldIrql;
+        KeAcquireSpinLock(&pMgr->SynchLock, &OldIrql);
+
+        bool bFound = false;
+        PVBOXVIDEOCM_SESSION pSession = NULL;
+        for (PLIST_ENTRY pEntry = pMgr->SessionList.Flink; pEntry != &pMgr->SessionList; pEntry = pEntry->Flink)
+        {
+            pSession = VBOXCMENTRY_2_SESSION(pEntry);
+            if (pSession->pUmEvent == pUmEvent)
+            {
+                bFound = true;
+                break;
+            }
+        }
+
+        pContext->u64UmData = u64UmData;
+
+        if (!bFound)
+        {
+            Status = vboxVideoCmSessionCreateLocked(pMgr, &pSession, pUmEvent, pContext);
+            Assert(Status == STATUS_SUCCESS);
+        }
+        else
+        {
+            /* Status = */vboxVideoCmSessionCtxAdd(pSession, pContext);
+            /*Assert(Status == STATUS_SUCCESS);*/
+        }
+
+        KeReleaseSpinLock(&pMgr->SynchLock, OldIrql);
+
         if (Status == STATUS_SUCCESS)
         {
-            bool bFound = false;
-            PVBOXVIDEOCM_SESSION pSession = NULL;
-            for (PLIST_ENTRY pEntry = pMgr->SessionList.Flink; pEntry != &pMgr->SessionList; pEntry = pEntry->Flink)
-            {
-                pSession = VBOXCMENTRY_2_SESSION(pEntry);
-                if (pSession->pUmEvent == pUmEvent)
-                {
-                    bFound = true;
-                    break;
-                }
-            }
-
-            pContext->u64UmData = u64UmData;
-
-            if (!bFound)
-            {
-                Status = vboxVideoCmSessionCreateLocked(pMgr, &pSession, pUmEvent, pContext);
-                Assert(Status == STATUS_SUCCESS);
-            }
-            else
-            {
-                /* Status = */vboxVideoCmSessionCtxAdd(pSession, pContext);
-                /*Assert(Status == STATUS_SUCCESS);*/
-            }
-            LONG tstL = KeSetEvent(&pMgr->SynchEvent, 0, FALSE);
-            Assert(!tstL);
-
-            if (Status == STATUS_SUCCESS)
-            {
-                return STATUS_SUCCESS;
-            }
+            return STATUS_SUCCESS;
         }
 
@@ -472,22 +482,17 @@
         return STATUS_SUCCESS;
 
-    NTSTATUS Status = KeWaitForSingleObject(&pMgr->SynchEvent, Executive, KernelMode,
-                FALSE, /* BOOLEAN Alertable */
-                NULL /* PLARGE_INTEGER Timeout */
-    );
-    Assert(Status == STATUS_SUCCESS);
-    if (Status == STATUS_SUCCESS)
-    {
-        vboxVideoCmSessionCtxRemoveLocked(pSession, pContext);
-        LONG tstL = KeSetEvent(&pMgr->SynchEvent, 0, FALSE);
-        Assert(!tstL);
-    }
-
-    return Status;
+    KIRQL OldIrql;
+    KeAcquireSpinLock(&pMgr->SynchLock, &OldIrql);
+
+    vboxVideoCmSessionCtxRemoveLocked(pSession, pContext);
+
+    KeReleaseSpinLock(&pMgr->SynchLock, OldIrql);
+
+    return STATUS_SUCCESS;
 }
 
 NTSTATUS vboxVideoCmInit(PVBOXVIDEOCM_MGR pMgr)
 {
-    KeInitializeEvent(&pMgr->SynchEvent, SynchronizationEvent, TRUE);
+    KeInitializeSpinLock(&pMgr->SynchLock);
     InitializeListHead(&pMgr->SessionList);
     return STATUS_SUCCESS;
@@ -500,4 +505,23 @@
 }
 
+NTSTATUS vboxVideoCmSignalEvents(PVBOXVIDEOCM_MGR pMgr)
+{
+    Assert(KeGetCurrentIrql() <= DISPATCH_LEVEL);
+    PVBOXVIDEOCM_SESSION pSession = NULL;
+
+    KIRQL OldIrql;
+    KeAcquireSpinLock(&pMgr->SynchLock, &OldIrql);
+
+    for (PLIST_ENTRY pEntry = pMgr->SessionList.Flink; pEntry != &pMgr->SessionList; pEntry = pEntry->Flink)
+    {
+        pSession = VBOXCMENTRY_2_SESSION(pEntry);
+        vboxVideoCmSessionSignalEvent(pSession);
+    }
+
+    KeReleaseSpinLock(&pMgr->SynchLock, OldIrql);
+
+    return STATUS_SUCCESS;
+}
+
 VOID vboxVideoCmProcessKm(PVBOXVIDEOCM_CTX pContext, PVBOXVIDEOCM_CMD_CTL_KM pCmd)
 {
@@ -515,7 +539,8 @@
         {
             PVBOXVIDEOCM_CMD_DR pHdr = VBOXVIDEOCM_HEAD(pCmd);
-            ExAcquireFastMutex(&pSession->Mutex);
+            KIRQL OldIrql;
+            KeAcquireSpinLock(&pSession->SynchLock, &OldIrql);
             InsertTailList(&pSession->PpCommandsList, &pHdr->QueueList);
-            ExReleaseFastMutex(&pSession->Mutex);
+            KeReleaseSpinLock(&pSession->SynchLock, OldIrql);
             break;
         }
@@ -550,6 +575,7 @@
 //    PVBOXWDDM_GETVBOXVIDEOCMCMD_HDR *pvCmd
 
-    Assert(KeGetCurrentIrql() < DISPATCH_LEVEL);
-    ExAcquireFastMutex(&pSession->Mutex);
+    Assert(KeGetCurrentIrql() <= DISPATCH_LEVEL);
+    KIRQL OldIrql;
+    KeAcquireSpinLock(&pSession->SynchLock, &OldIrql);
 
     vboxVideoCmSessionCtxDetachCmdsLocked(&pSession->PpCommandsList, pContext, &DetachedPpList);
@@ -606,5 +632,5 @@
     } while (1);
 
-    ExReleaseFastMutex(&pSession->Mutex);
+    KeReleaseSpinLock(&pSession->SynchLock, OldIrql);
 
     vboxVideoCmSessionCtxPpList(pContext, &DetachedPpList);
@@ -647,14 +673,4 @@
 }
 
-VOID vboxVideoCmLock(PVBOXVIDEOCM_CTX pContext)
-{
-    ExAcquireFastMutex(&pContext->pSession->Mutex);
-}
-
-VOID vboxVideoCmUnlock(PVBOXVIDEOCM_CTX pContext)
-{
-    ExReleaseFastMutex(&pContext->pSession->Mutex);
-}
-
 static BOOLEAN vboxVideoCmHasUncompletedCmdsLocked(PVBOXVIDEOCM_MGR pMgr)
 {
@@ -663,86 +679,15 @@
     {
         pSession = VBOXCMENTRY_2_SESSION(pEntry);
-        ExAcquireFastMutex(&pSession->Mutex);
+        KIRQL OldIrql;
+        KeAcquireSpinLock(&pSession->SynchLock, &OldIrql);
+
         if (pSession->bEventNeeded)
         {
             /* commands still being processed */
-            ExReleaseFastMutex(&pSession->Mutex);
+            KeReleaseSpinLock(&pSession->SynchLock, OldIrql);
             return TRUE;
         }
-        ExReleaseFastMutex(&pSession->Mutex);
+        KeReleaseSpinLock(&pSession->SynchLock, OldIrql);
     }
     return FALSE;
 }
-
-/* waits for all outstanding commands to completed by client
- * assumptions here are:
- * 1. no new commands are submitted while we are waiting
- * 2. it is assumed that a client completes all previously received commands
- *    once it queries for the new set of commands */
-NTSTATUS vboxVideoCmWaitCompletedCmds(PVBOXVIDEOCM_MGR pMgr, uint32_t msTimeout)
-{
-    LARGE_INTEGER Timeout;
-    PLARGE_INTEGER pTimeout;
-    uint32_t cIters;
-
-    if (msTimeout != RT_INDEFINITE_WAIT)
-    {
-        uint32_t msIter = 2;
-        cIters = msTimeout/msIter;
-        if (!cIters)
-        {
-            msIter = msTimeout;
-            cIters = 1;
-        }
-        Timeout.QuadPart = -(int64_t) msIter /* ms */ * 10000;
-        pTimeout = &Timeout;
-    }
-    else
-    {
-        pTimeout = NULL;
-        cIters = 1;
-    }
-
-    Assert(cIters);
-    do
-    {
-        NTSTATUS Status = KeWaitForSingleObject(&pMgr->SynchEvent, Executive, KernelMode,
-                    FALSE, /* BOOLEAN Alertable */
-                    pTimeout /* PLARGE_INTEGER Timeout */
-        );
-        if (Status == STATUS_TIMEOUT)
-        {
-            --cIters;
-        }
-        else
-        {
-            if (!NT_SUCCESS(Status))
-            {
-                WARN(("KeWaitForSingleObject failed with Status (0x%x)", Status));
-                return Status;
-            }
-
-            /* succeeded */
-            if (!vboxVideoCmHasUncompletedCmdsLocked(pMgr))
-            {
-                LONG tstL = KeSetEvent(&pMgr->SynchEvent, 0, FALSE);
-                Assert(!tstL);
-                return STATUS_SUCCESS;
-            }
-
-            LONG tstL = KeSetEvent(&pMgr->SynchEvent, 0, FALSE);
-            Assert(!tstL);
-        }
-
-        if (!cIters)
-            break;
-
-        KeDelayExecutionThread(KernelMode, FALSE, pTimeout);
-        --cIters;
-        if (!cIters)
-            break;
-    } while (0);
-
-    return STATUS_TIMEOUT;
-}
-
Index: trunk/src/VBox/Additions/WINNT/Graphics/Video/mp/wddm/VBoxMPCm.h
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Video/mp/wddm/VBoxMPCm.h	(revision 48058)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Video/mp/wddm/VBoxMPCm.h	(revision 48070)
@@ -22,5 +22,5 @@
 typedef struct VBOXVIDEOCM_MGR
 {
-    KEVENT SynchEvent;
+    KSPIN_LOCK SynchLock;
     /* session list */
     LIST_ENTRY SessionList;
@@ -41,4 +41,5 @@
 NTSTATUS vboxVideoCmInit(PVBOXVIDEOCM_MGR pMgr);
 NTSTATUS vboxVideoCmTerm(PVBOXVIDEOCM_MGR pMgr);
+NTSTATUS vboxVideoCmSignalEvents(PVBOXVIDEOCM_MGR pMgr);
 
 NTSTATUS vboxVideoCmCmdSubmitCompleteEvent(PVBOXVIDEOCM_CTX pContext, PKEVENT pEvent);
@@ -58,8 +59,3 @@
 NTSTATUS vboxVideoCmEscape(PVBOXVIDEOCM_CTX pContext, PVBOXDISPIFESCAPE_GETVBOXVIDEOCMCMD pCmd, uint32_t cbCmd);
 
-NTSTATUS vboxVideoCmWaitCompletedCmds(PVBOXVIDEOCM_MGR pMgr, uint32_t msTimeout);
-
-VOID vboxVideoCmLock(PVBOXVIDEOCM_CTX pContext);
-VOID vboxVideoCmUnlock(PVBOXVIDEOCM_CTX pContext);
-
 #endif /* #ifndef ___VBoxMPCm_h___ */
Index: trunk/src/VBox/Additions/WINNT/Graphics/Video/mp/wddm/VBoxMPMisc.cpp
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Video/mp/wddm/VBoxMPMisc.cpp	(revision 48058)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Video/mp/wddm/VBoxMPMisc.cpp	(revision 48070)
@@ -573,6 +573,4 @@
 }
 
-#define VBOXWDDM_REG_DRVKEY_PREFIX L"\\Registry\\Machine\\System\\CurrentControlSet\\Control\\Class\\"
-
 NTSTATUS vboxWddmRegQueryDrvKeyName(PVBOXMP_DEVEXT pDevExt, ULONG cbBuf, PWCHAR pBuf, PULONG pcbResult)
 {
@@ -607,11 +605,4 @@
 }
 
-#define VBOXWDDM_REG_DISPLAYSETTINGSKEY_PREFIX_VISTA L"\\Registry\\Machine\\System\\CurrentControlSet\\Hardware Profiles\\Current\\System\\CurrentControlSet\\Control\\VIDEO\\"
-#define VBOXWDDM_REG_DISPLAYSETTINGSKEY_PREFIX_WIN7 L"\\Registry\\Machine\\System\\CurrentControlSet\\Hardware Profiles\\UnitedVideo\\CONTROL\\VIDEO\\"
-
-#define VBOXWDDM_REG_DISPLAYSETTINGS_ATTACH_RELX L"Attach.RelativeX"
-#define VBOXWDDM_REG_DISPLAYSETTINGS_ATTACH_RELY L"Attach.RelativeY"
-#define VBOXWDDM_REG_DISPLAYSETTINGS_ATTACH_DESKTOP L"Attach.ToDesktop"
-
 NTSTATUS vboxWddmRegQueryDisplaySettingsKeyName(PVBOXMP_DEVEXT pDevExt, D3DDDI_VIDEO_PRESENT_SOURCE_ID VidPnSourceId,
         ULONG cbBuf, PWCHAR pBuf, PULONG pcbResult)
@@ -660,7 +651,4 @@
     return Status;
 }
-
-#define VBOXWDDM_REG_DISPLAYSETTINGSVIDEOKEY L"\\Registry\\Machine\\System\\CurrentControlSet\\Control\\Video\\"
-#define VBOXWDDM_REG_DISPLAYSETTINGSVIDEOKEY_SUBKEY L"\\Video"
 
 NTSTATUS vboxWddmRegQueryVideoGuidString(PVBOXMP_DEVEXT pDevExt, ULONG cbBuf, PWCHAR pBuf, PULONG pcbResult)
@@ -891,4 +879,48 @@
 }
 
+NTSTATUS vboxWddmRegDrvFlagsSet(PVBOXMP_DEVEXT pDevExt, DWORD fVal)
+{
+    HANDLE hKey = NULL;
+    NTSTATUS Status = IoOpenDeviceRegistryKey(pDevExt->pPDO, PLUGPLAY_REGKEY_DRIVER, GENERIC_WRITE, &hKey);
+    if (!NT_SUCCESS(Status))
+    {
+        WARN(("IoOpenDeviceRegistryKey failed, Status = 0x%x", Status));
+        return Status;
+    }
+
+    Status = vboxWddmRegSetValueDword(hKey, VBOXWDDM_REG_DRV_FLAGS_NAME, fVal);
+    if (!NT_SUCCESS(Status))
+        WARN(("vboxWddmRegSetValueDword failed, Status = 0x%x", Status));
+
+    NTSTATUS tmpStatus = ZwClose(hKey);
+    Assert(tmpStatus == STATUS_SUCCESS);
+
+    return Status;
+}
+
+DWORD vboxWddmRegDrvFlagsGet(PVBOXMP_DEVEXT pDevExt, DWORD fDefault)
+{
+    HANDLE hKey = NULL;
+    NTSTATUS Status = IoOpenDeviceRegistryKey(pDevExt->pPDO, PLUGPLAY_REGKEY_DRIVER, GENERIC_READ, &hKey);
+    if (!NT_SUCCESS(Status))
+    {
+        WARN(("IoOpenDeviceRegistryKey failed, Status = 0x%x", Status));
+        return fDefault;
+    }
+
+    DWORD dwVal = 0;
+    Status = vboxWddmRegQueryValueDword(hKey, VBOXWDDM_REG_DRV_FLAGS_NAME, &dwVal);
+    if (!NT_SUCCESS(Status))
+    {
+        WARN(("vboxWddmRegQueryValueDword failed, Status = 0x%x", Status));
+        dwVal = fDefault;
+    }
+
+    NTSTATUS tmpStatus = ZwClose(hKey);
+    Assert(tmpStatus == STATUS_SUCCESS);
+
+    return dwVal;
+}
+
 NTSTATUS vboxWddmRegQueryValueDword(IN HANDLE hKey, IN PWCHAR pName, OUT PDWORD pDword)
 {
@@ -920,5 +952,5 @@
 }
 
-NTSTATUS vboxWddmRegSetValueDword(IN HANDLE hKey, IN PWCHAR pName, OUT DWORD val)
+NTSTATUS vboxWddmRegSetValueDword(IN HANDLE hKey, IN PWCHAR pName, IN DWORD val)
 {
     UNICODE_STRING RtlStr;
Index: trunk/src/VBox/Additions/WINNT/Graphics/Video/mp/wddm/VBoxMPMisc.h
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Video/mp/wddm/VBoxMPMisc.h	(revision 48058)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Video/mp/wddm/VBoxMPMisc.h	(revision 48070)
@@ -99,5 +99,8 @@
 NTSTATUS vboxWddmRegOpenKey(OUT PHANDLE phKey, IN PWCHAR pName, IN ACCESS_MASK fAccess);
 NTSTATUS vboxWddmRegQueryValueDword(IN HANDLE hKey, IN PWCHAR pName, OUT PDWORD pDword);
-NTSTATUS vboxWddmRegSetValueDword(IN HANDLE hKey, IN PWCHAR pName, OUT DWORD val);
+NTSTATUS vboxWddmRegSetValueDword(IN HANDLE hKey, IN PWCHAR pName, IN DWORD val);
+
+NTSTATUS vboxWddmRegDrvFlagsSet(PVBOXMP_DEVEXT pDevExt, DWORD fVal);
+DWORD vboxWddmRegDrvFlagsGet(PVBOXMP_DEVEXT pDevExt, DWORD fDefault);
 
 UNICODE_STRING* vboxWddmVGuidGet(PVBOXMP_DEVEXT pDevExt);
@@ -184,3 +187,5 @@
 #endif
 
+NTSTATUS vboxWddmChildStatusConnect(PVBOXMP_DEVEXT pDevExt, uint32_t iChild, BOOLEAN fConnect);
+
 #endif /* #ifndef ___VBoxMPMisc_h__ */
Index: trunk/src/VBox/Additions/WINNT/Graphics/Video/mp/wddm/VBoxMPTypes.h
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Video/mp/wddm/VBoxMPTypes.h	(revision 48058)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Video/mp/wddm/VBoxMPTypes.h	(revision 48070)
@@ -35,4 +35,7 @@
 #include <cr_vreg.h>
 
+#ifdef DEBUG_misha
+extern DWORD g_VBoxDbgBreakModes;
+#endif
 
 #if 0
@@ -139,4 +142,9 @@
     uint32_t HeightVisible;
     uint32_t HeightTotal;
+    /* since there coul be multiple state changes on auto-resize,
+     * we pend notifying host to avoi flickering */
+    volatile bool fStateSyncPening;
+    bool fConnected;
+    bool fConfigured;
 } VBOXWDDM_TARGET, *PVBOXWDDM_TARGET;
 
Index: trunk/src/VBox/Additions/WINNT/Graphics/Video/mp/wddm/VBoxMPVidPn.cpp
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Video/mp/wddm/VBoxMPVidPn.cpp	(revision 48058)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Video/mp/wddm/VBoxMPVidPn.cpp	(revision 48070)
@@ -1263,8 +1263,5 @@
     const DXGK_VIDPNTARGETMODESET_INTERFACE *pNewVidPnTargetModeSetInterface;
 
-    if (VidPnSourceId != VidPnTargetId || pCbContext->apPathInfos[VidPnTargetId].enmState != VBOXVIDPNPATHITEM_STATE_PRESENT)
-    {
-        return STATUS_SUCCESS;
-    }
+    Assert(VidPnSourceId == VidPnTargetId);
 
     D3DKMDT_HVIDPNSOURCEMODESET hCurVidPnSourceModeSet;
@@ -1306,8 +1303,7 @@
         {
             Assert(hNewVidPnTargetModeSet);
-            if (VidPnSourceId == VidPnTargetId && pCbContext->apPathInfos[VidPnTargetId].enmState == VBOXVIDPNPATHITEM_STATE_PRESENT)
-            {
-                Assert(VidPnSourceId == VidPnTargetId);
-
+            Assert(VidPnSourceId == VidPnTargetId);
+//            if (VidPnSourceId == VidPnTargetId && pCbContext->apPathInfos[VidPnTargetId].enmState == VBOXVIDPNPATHITEM_STATE_PRESENT)
+            {
                 for (uint32_t i = 0; i < pInfo->cResolutions; ++i)
                 {
@@ -1398,8 +1394,5 @@
     const DXGK_VIDPNSOURCEMODESET_INTERFACE *pNewVidPnSourceModeSetInterface;
 
-    if (VidPnSourceId != VidPnTargetId || pCbContext->apPathInfos[VidPnSourceId].enmState != VBOXVIDPNPATHITEM_STATE_PRESENT)
-    {
-        return STATUS_SUCCESS;
-    }
+    Assert(VidPnSourceId == VidPnTargetId);
 
     D3DKMDT_HVIDPNTARGETMODESET hCurVidPnTargetModeSet;
@@ -1441,7 +1434,7 @@
         {
             Assert(hNewVidPnSourceModeSet);
-            if (VidPnSourceId == VidPnTargetId && pCbContext->apPathInfos[VidPnSourceId].enmState == VBOXVIDPNPATHITEM_STATE_PRESENT)
-            {
-                Assert(VidPnSourceId == VidPnTargetId);
+            Assert(VidPnSourceId == VidPnTargetId);
+//            if (VidPnSourceId == VidPnTargetId && pCbContext->apPathInfos[VidPnSourceId].enmState == VBOXVIDPNPATHITEM_STATE_PRESENT)
+            {
                 for (uint32_t i = 0; i < pInfo->cModes; ++i)
                 {
@@ -1755,5 +1748,5 @@
             else
             {
-                AssertFailed();
+                WARN(("cItems(%d) <= VidPnSourceId(%d)", pCbContext->cItems, VidPnSourceId));
                 Status = STATUS_BUFFER_OVERFLOW;
                 break;
@@ -1766,5 +1759,5 @@
             else
             {
-                AssertFailed();
+                WARN(("cItems(%d) <= VidPnTargetId(%d)", pCbContext->cItems, VidPnTargetId));
                 Status = STATUS_BUFFER_OVERFLOW;
                 break;
@@ -1775,4 +1768,5 @@
 
         /* VidPnSourceId == VidPnTargetId */
+        Assert(VidPnSourceId == VidPnTargetId);
         if (pCbContext->cItems > VidPnSourceId)
         {
@@ -1785,5 +1779,5 @@
         else
         {
-            AssertFailed();
+            WARN(("cItems(%d) <= VidPnSource/TargetId(%d)", pCbContext->cItems, VidPnSourceId));
             Status = STATUS_BUFFER_OVERFLOW;
             break;
@@ -1801,18 +1795,19 @@
 /* we currently support only 0 -> 0, 1 -> 1, 2 -> 2 paths, AND 0 -> 0 must be present
  * this routine disables all paths unsupported */
-NTSTATUS vboxVidPnCheckTopology(D3DKMDT_HVIDPNTOPOLOGY hVidPnTopology, const DXGK_VIDPNTOPOLOGY_INTERFACE* pVidPnTopologyInterface,
-                                    BOOLEAN fBreakOnDisabled, UINT cItems, PVBOXVIDPNPATHITEM paItems, BOOLEAN *pfDisabledFound)
-{
+NTSTATUS vboxVidPnCheckTopology(D3DKMDT_HVIDPNTOPOLOGY hVidPnTopology, const DXGK_VIDPNTOPOLOGY_INTERFACE* pVidPnTopologyInterface, BOOLEAN *pfSupported)
+{
+    VBOXVIDPNPATHITEM aItems[VBOX_VIDEO_MAX_SCREENS];
+    const uint32_t cItems = RT_ELEMENTS(aItems);
     UINT i;
     for (i = 0; i < cItems; ++i)
     {
-        paItems[i].enmState = VBOXVIDPNPATHITEM_STATE_NOT_EXISTS;
+        aItems[i].enmState = VBOXVIDPNPATHITEM_STATE_NOT_EXISTS;
     }
     VBOXVIDPNGETPATHSINFO CbContext = {0};
     CbContext.Status = STATUS_SUCCESS;
-    CbContext.fBreakOnDisabled = fBreakOnDisabled;
+    CbContext.fBreakOnDisabled = FALSE;
     CbContext.fDisabledFound = FALSE;
     CbContext.cItems = cItems;
-    CbContext.paItems = paItems;
+    CbContext.paItems = aItems;
     NTSTATUS Status = vboxVidPnEnumPaths(hVidPnTopology, pVidPnTopologyInterface, vboxVidPnCheckTopologyEnum, &CbContext);
     if (!NT_SUCCESS(Status))
@@ -1829,20 +1824,20 @@
     }
 
-    if (pfDisabledFound)
-        *pfDisabledFound = CbContext.fDisabledFound;
-
-    if (!fBreakOnDisabled)
-    {
-        /* now check if 0->0 path is present and enabled, and if not, disable everything */
-        if (cItems && paItems[0].enmState != VBOXVIDPNPATHITEM_STATE_PRESENT)
-        {
-            LOGREL(("path 0 not set to present\n"));
-            for (i = 0; i < cItems; ++i)
-            {
-                if (paItems[i].enmState == VBOXVIDPNPATHITEM_STATE_PRESENT)
-                    paItems[i].enmState = VBOXVIDPNPATHITEM_STATE_DISABLED;
-            }
-        }
-    }
+    BOOLEAN fSupported = !CbContext.fDisabledFound;
+
+    /* now check if 0->0 path is present and enabled, and if not, disable everything */
+//    if (cItems && aItems[0].enmState != VBOXVIDPNPATHITEM_STATE_PRESENT)
+//    {
+//        LOG(("path 0 not set to present\n"));
+////        for (i = 0; i < cItems; ++i)
+////        {
+////            if (aItems[i].enmState == VBOXVIDPNPATHITEM_STATE_PRESENT)
+////                aItems[i].enmState = VBOXVIDPNPATHITEM_STATE_DISABLED;
+////        }
+//        fSupported = FALSE;
+//    }
+
+    if (pfSupported)
+        *pfSupported = fSupported;
 
     return Status;
@@ -2063,7 +2058,6 @@
                 else
                 {
-                    Assert(Status == STATUS_GRAPHICS_NO_MORE_ELEMENTS_IN_DATASET);
                     if (Status != STATUS_GRAPHICS_NO_MORE_ELEMENTS_IN_DATASET)
-                        LOGREL(("pfnAcquireNextPathInfo Failed Status(0x%x), ignored since callback returned false", Status));
+                        WARN(("pfnAcquireNextPathInfo Failed Status(0x%x), ignored since callback returned false", Status));
                     Status = STATUS_SUCCESS;
                 }
@@ -2080,6 +2074,5 @@
             else
             {
-                AssertBreakpoint();
-                LOGREL(("pfnAcquireNextPathInfo Failed Status(0x%x)", Status));
+                WARN(("pfnAcquireNextPathInfo Failed Status(0x%x)", Status));
                 pNewVidPnPresentPathInfo = NULL;
                 break;
@@ -2090,5 +2083,5 @@
         Status = STATUS_SUCCESS;
     else
-        LOGREL(("pfnAcquireFirstModeInfo failed Status(0x%x)", Status));
+        WARN(("pfnAcquireFirstModeInfo failed Status(0x%x)", Status));
 
     return Status;
@@ -2181,4 +2174,8 @@
     return Status == STATUS_SUCCESS;
 }
+
+#ifdef DEBUG_misha
+DWORD g_VBoxDbgBreakModes = 0;
+#endif
 
 NTSTATUS vboxVidPnCommitSourceModeForSrcId(PVBOXMP_DEVEXT pDevExt, const D3DKMDT_HVIDPN hDesiredVidPn, const DXGK_VIDPN_INTERFACE* pVidPnInterface, D3DDDI_VIDEO_PRESENT_SOURCE_ID srcId, PVBOXWDDM_ALLOCATION pAllocation)
@@ -2235,11 +2232,11 @@
                     }
                     else
-                        LOGREL(("vboxVidPnEnumTargetsForSource failed Status(0x%x)", Status));
+                        WARN(("vboxVidPnEnumTargetsForSource failed Status(0x%x)", Status));
                 }
                 else
-                    LOGREL(("pfnGetTopology failed Status(0x%x)", Status));
+                    WARN(("pfnGetTopology failed Status(0x%x)", Status));
             }
             else
-                LOGREL(("vboxVidPnCommitSourceMode failed Status(0x%x)", Status));
+                WARN(("vboxVidPnCommitSourceMode failed Status(0x%x)", Status));
             /* release */
             pCurVidPnSourceModeSetInterface->pfnReleaseModeInfo(hCurVidPnSourceModeSet, pPinnedVidPnSourceModeInfo);
@@ -2247,9 +2244,13 @@
         else if (Status == STATUS_GRAPHICS_MODE_NOT_PINNED)
         {
+#ifdef DEBUG_misha
+            Assert(!g_VBoxDbgBreakModes);
+            ++g_VBoxDbgBreakModes;
+#endif
             Status = vboxVidPnCommitSourceMode(pDevExt, srcId, NULL, pAllocation);
             Assert(Status == STATUS_SUCCESS);
         }
         else
-            LOGREL(("pfnAcquirePinnedModeInfo failed Status(0x%x)", Status));
+            WARN(("pfnAcquirePinnedModeInfo failed Status(0x%x)", Status));
 
         pVidPnInterface->pfnReleaseSourceModeSet(hDesiredVidPn, hCurVidPnSourceModeSet);
@@ -2257,5 +2258,5 @@
     else
     {
-        LOGREL(("pfnAcquireSourceModeSet failed Status(0x%x)", Status));
+        WARN(("pfnAcquireSourceModeSet failed Status(0x%x)", Status));
     }
 
Index: trunk/src/VBox/Additions/WINNT/Graphics/Video/mp/wddm/VBoxMPVidPn.h
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Video/mp/wddm/VBoxMPVidPn.h	(revision 48058)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Video/mp/wddm/VBoxMPVidPn.h	(revision 48070)
@@ -58,6 +58,6 @@
     CONST DXGKARG_ENUMVIDPNCOFUNCMODALITY* pEnumCofuncModalityArg;
     PVBOXWDDM_VIDEOMODES_INFO pInfos;
-    UINT cPathInfos;
-    PVBOXVIDPNPATHITEM apPathInfos;
+//    UINT cPathInfos;
+//    PVBOXVIDPNPATHITEM apPathInfos;
 } VBOXVIDPNCOFUNCMODALITY, *PVBOXVIDPNCOFUNCMODALITY;
 
@@ -146,6 +146,5 @@
 NTSTATUS vboxVidPnCofuncModalityForPath(PVBOXVIDPNCOFUNCMODALITY pCbContext, D3DDDI_VIDEO_PRESENT_SOURCE_ID VidPnSourceId, D3DDDI_VIDEO_PRESENT_TARGET_ID VidPnTargetId);
 
-NTSTATUS vboxVidPnCheckTopology(D3DKMDT_HVIDPNTOPOLOGY hVidPnTopology, const DXGK_VIDPNTOPOLOGY_INTERFACE* pVidPnTopologyInterface,
-                                    BOOLEAN fBreakOnDisabled, UINT cItems, PVBOXVIDPNPATHITEM paItems, BOOLEAN *pfDisabledFound);
+NTSTATUS vboxVidPnCheckTopology(D3DKMDT_HVIDPNTOPOLOGY hVidPnTopology, const DXGK_VIDPNTOPOLOGY_INTERFACE* pVidPnTopologyInterface, BOOLEAN *pfSupported);
 
 NTSTATUS vboxVidPnPathAdd(D3DKMDT_HVIDPN hVidPn, const DXGK_VIDPN_INTERFACE* pVidPnInterface,
Index: trunk/src/VBox/Additions/WINNT/Graphics/Video/mp/wddm/VBoxMPWddm.cpp
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Video/mp/wddm/VBoxMPWddm.cpp	(revision 48058)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Video/mp/wddm/VBoxMPWddm.cpp	(revision 48070)
@@ -31,4 +31,6 @@
 #include <VBox/Hardware/VBoxVideoVBE.h>
 
+#include <stdio.h>
+
 DWORD g_VBoxLogUm = 0;
 #ifdef VBOX_WDDM_WIN8
@@ -187,4 +189,11 @@
 }
 
+BOOL vboxWddmGhDisplayCheckCompletePeningScreenInfo(PVBOXMP_DEVEXT pDevExt, D3DDDI_VIDEO_PRESENT_TARGET_ID VidPnTargetId)
+{
+    if (!ASMAtomicCmpXchgBool(&pDevExt->aTargets[VidPnTargetId].fStateSyncPening, false, true))
+        return FALSE;
+    return vboxWddmGhDisplayCheckSetInfoFromSource(pDevExt, &pDevExt->aSources[VidPnTargetId]);
+}
+
 NTSTATUS vboxWddmGhDisplayPostInfoView(PVBOXMP_DEVEXT pDevExt, const VBOXWDDM_ALLOC_DATA *pAllocData)
 {
@@ -302,10 +311,12 @@
 }
 
-bool vboxWddmGhDisplayCheckSetInfoFromSource(PVBOXMP_DEVEXT pDevExt, PVBOXWDDM_SOURCE pSource)
-{
-//    Assert(VBOXVIDEOOFFSET_VOID != pSource->AllocData.Addr.offVram);
-
-    if (pSource->fGhSynced)
-        return false;
+bool vboxWddmGhDisplaySetInfoFromSourceTarget(PVBOXMP_DEVEXT pDevExt, PVBOXWDDM_SOURCE pSource, PVBOXWDDM_TARGET pTarget)
+{
+    if (!pTarget->HeightVisible)
+    {
+        vboxWddmGhDisplayHideScreen(pDevExt, pSource->AllocData.SurfDesc.VidPnSourceId);
+        pSource->fGhSynced = 1;
+        return true;
+    }
 
     char fGhSynced = 1;
@@ -346,5 +357,22 @@
         WARN(("vboxWddmGhDisplaySetInfo failed, Status (0x%x)", Status));
 
+    vboxVideoCmSignalEvents(&pDevExt->SeamlessCtxMgr);
+
     return true;
+}
+
+bool vboxWddmGhDisplayCheckSetInfoFromSource(PVBOXMP_DEVEXT pDevExt, PVBOXWDDM_SOURCE pSource)
+{
+    Assert(VBOXVIDEOOFFSET_VOID != pSource->AllocData.Addr.offVram
+            || !pDevExt->aTargets[pSource->AllocData.SurfDesc.VidPnSourceId].HeightVisible);
+
+    if (pSource->fGhSynced)
+        return false;
+
+    PVBOXWDDM_TARGET pTarget = &pDevExt->aTargets[pSource->AllocData.SurfDesc.VidPnSourceId];
+    if (ASMAtomicUoReadBool(&pTarget->fStateSyncPening))
+        return false;
+
+    return vboxWddmGhDisplaySetInfoFromSourceTarget(pDevExt, pSource, pTarget);
 }
 
@@ -467,329 +495,4 @@
         return VBOXWDDM_HGSMICMD_TYPE_CTL;
     return VBOXWDDM_HGSMICMD_TYPE_UNDEFINED;
-}
-
-static NTSTATUS vboxWddmChildStatusReportPerform(PVBOXMP_DEVEXT pDevExt, PVBOXVDMA_CHILD_STATUS pChildStatus, D3DDDI_VIDEO_PRESENT_TARGET_ID iChild)
-{
-    DXGK_CHILD_STATUS DdiChildStatus;
-    if (pChildStatus->fFlags & VBOXVDMA_CHILD_STATUS_F_DISCONNECTED)
-    {
-        /* report disconnected */
-        memset(&DdiChildStatus, 0, sizeof (DdiChildStatus));
-        DdiChildStatus.Type = StatusConnection;
-        if (iChild != D3DDDI_ID_UNINITIALIZED)
-        {
-            Assert(iChild < UINT32_MAX/2);
-            Assert(iChild < (UINT)VBoxCommonFromDeviceExt(pDevExt)->cDisplays);
-            DdiChildStatus.ChildUid = iChild;
-        }
-        else
-        {
-            Assert(pChildStatus->iChild < UINT32_MAX/2);
-            Assert(pChildStatus->iChild < (UINT)VBoxCommonFromDeviceExt(pDevExt)->cDisplays);
-            DdiChildStatus.ChildUid = pChildStatus->iChild;
-        }
-        LOG(("Reporting DISCONNECT to child %d", DdiChildStatus.ChildUid));
-        DdiChildStatus.HotPlug.Connected = FALSE;
-        NTSTATUS Status = pDevExt->u.primary.DxgkInterface.DxgkCbIndicateChildStatus(pDevExt->u.primary.DxgkInterface.DeviceHandle, &DdiChildStatus);
-        if (!NT_SUCCESS(Status))
-        {
-            WARN(("DxgkCbIndicateChildStatus failed with Status (0x%x)", Status));
-            return Status;
-        }
-    }
-
-    if (pChildStatus->fFlags & VBOXVDMA_CHILD_STATUS_F_CONNECTED)
-    {
-        /* report disconnected */
-        memset(&DdiChildStatus, 0, sizeof (DdiChildStatus));
-        DdiChildStatus.Type = StatusConnection;
-        if (iChild != D3DDDI_ID_UNINITIALIZED)
-        {
-            Assert(iChild < UINT32_MAX/2);
-            Assert(iChild < (UINT)VBoxCommonFromDeviceExt(pDevExt)->cDisplays);
-            DdiChildStatus.ChildUid = iChild;
-        }
-        else
-        {
-            Assert(pChildStatus->iChild < UINT32_MAX/2);
-            Assert(pChildStatus->iChild < (UINT)VBoxCommonFromDeviceExt(pDevExt)->cDisplays);
-            DdiChildStatus.ChildUid = pChildStatus->iChild;
-        }
-        LOG(("Reporting CONNECT to child %d", DdiChildStatus.ChildUid));
-        DdiChildStatus.HotPlug.Connected = TRUE;
-        NTSTATUS Status = pDevExt->u.primary.DxgkInterface.DxgkCbIndicateChildStatus(pDevExt->u.primary.DxgkInterface.DeviceHandle, &DdiChildStatus);
-        if (!NT_SUCCESS(Status))
-        {
-            WARN(("DxgkCbIndicateChildStatus failed with Status (0x%x)", Status));
-            return Status;
-        }
-    }
-
-    if (pChildStatus->fFlags & VBOXVDMA_CHILD_STATUS_F_ROTATED)
-    {
-        /* report disconnected */
-        memset(&DdiChildStatus, 0, sizeof (DdiChildStatus));
-        DdiChildStatus.Type = StatusRotation;
-        if (iChild != D3DDDI_ID_UNINITIALIZED)
-        {
-            Assert(iChild < UINT32_MAX/2);
-            Assert(iChild < (UINT)VBoxCommonFromDeviceExt(pDevExt)->cDisplays);
-            DdiChildStatus.ChildUid = iChild;
-        }
-        else
-        {
-            Assert(pChildStatus->iChild < UINT32_MAX/2);
-            Assert(pChildStatus->iChild < (UINT)VBoxCommonFromDeviceExt(pDevExt)->cDisplays);
-            DdiChildStatus.ChildUid = pChildStatus->iChild;
-        }
-        LOG(("Reporting ROTATED to child %d", DdiChildStatus.ChildUid));
-        DdiChildStatus.Rotation.Angle = pChildStatus->u8RotationAngle;
-        NTSTATUS Status = pDevExt->u.primary.DxgkInterface.DxgkCbIndicateChildStatus(pDevExt->u.primary.DxgkInterface.DeviceHandle, &DdiChildStatus);
-        if (!NT_SUCCESS(Status))
-        {
-            WARN(("DxgkCbIndicateChildStatus failed with Status (0x%x)", Status));
-            return Status;
-        }
-    }
-
-    return STATUS_SUCCESS;
-}
-
-static NTSTATUS vboxWddmChildStatusDoReportReconnected(PVBOXMP_DEVEXT pDevExt, VBOXVDMACMD_CHILD_STATUS_IRQ *pBody)
-{
-    NTSTATUS Status = STATUS_SUCCESS;
-
-    for (UINT i = 0; i < pBody->cInfos; ++i)
-    {
-        PVBOXVDMA_CHILD_STATUS pInfo = &pBody->aInfos[i];
-        if (pBody->fFlags & VBOXVDMACMD_CHILD_STATUS_IRQ_F_APPLY_TO_ALL)
-        {
-            for (D3DDDI_VIDEO_PRESENT_TARGET_ID iChild = 0; iChild < (UINT)VBoxCommonFromDeviceExt(pDevExt)->cDisplays; ++iChild)
-            {
-                Status = vboxWddmChildStatusReportPerform(pDevExt, pInfo, iChild);
-                if (!NT_SUCCESS(Status))
-                {
-                    WARN(("vboxWddmChildStatusReportPerform failed with Status (0x%x)", Status));
-                    break;
-                }
-            }
-        }
-        else
-        {
-            Status = vboxWddmChildStatusReportPerform(pDevExt, pInfo, D3DDDI_ID_UNINITIALIZED);
-            if (!NT_SUCCESS(Status))
-            {
-                WARN(("vboxWddmChildStatusReportPerform failed with Status (0x%x)", Status));
-                break;
-            }
-        }
-    }
-
-    return Status;
-}
-
-typedef struct VBOXWDDMCHILDSTATUSCB
-{
-    PVBOXVDMACBUF_DR pDr;
-    PKEVENT pEvent;
-} VBOXWDDMCHILDSTATUSCB, *PVBOXWDDMCHILDSTATUSCB;
-
-static DECLCALLBACK(VOID) vboxWddmChildStatusReportCompletion(PVBOXMP_DEVEXT pDevExt, PVBOXVDMADDI_CMD pCmd, PVOID pvContext)
-{
-    /* we should be called from our DPC routine */
-    Assert(KeGetCurrentIrql() == DISPATCH_LEVEL);
-
-    PVBOXWDDMCHILDSTATUSCB pCtx = (PVBOXWDDMCHILDSTATUSCB)pvContext;
-    PVBOXVDMACBUF_DR pDr = pCtx->pDr;
-    PVBOXVDMACMD pHdr = VBOXVDMACBUF_DR_TAIL(pDr, VBOXVDMACMD);
-    VBOXVDMACMD_CHILD_STATUS_IRQ *pBody = VBOXVDMACMD_BODY(pHdr, VBOXVDMACMD_CHILD_STATUS_IRQ);
-
-    vboxWddmChildStatusDoReportReconnected(pDevExt, pBody);
-
-    vboxVdmaCBufDrFree(&pDevExt->u.primary.Vdma, pDr);
-
-    if (pCtx->pEvent)
-    {
-        KeSetEvent(pCtx->pEvent, 0, FALSE);
-    }
-}
-
-static NTSTATUS vboxWddmChildStatusReportReconnected(PVBOXMP_DEVEXT pDevExt, D3DDDI_VIDEO_PRESENT_TARGET_ID idTarget)
-{
-#ifdef VBOX_WDDM_MONITOR_REPLUG_IRQ
-    NTSTATUS Status = STATUS_UNSUCCESSFUL;
-    UINT cbCmd = VBOXVDMACMD_SIZE_FROMBODYSIZE(sizeof (VBOXVDMACMD_CHILD_STATUS_IRQ));
-
-    PVBOXVDMACBUF_DR pDr = vboxVdmaCBufDrCreate(&pDevExt->u.primary.Vdma, cbCmd);
-    if (pDr)
-    {
-        // vboxVdmaCBufDrCreate zero initializes the pDr
-        /* the command data follows the descriptor */
-        pDr->fFlags = VBOXVDMACBUF_FLAG_BUF_FOLLOWS_DR;
-        pDr->cbBuf = cbCmd;
-        pDr->rc = VERR_NOT_IMPLEMENTED;
-
-        PVBOXVDMACMD pHdr = VBOXVDMACBUF_DR_TAIL(pDr, VBOXVDMACMD);
-        pHdr->enmType = VBOXVDMACMD_TYPE_CHILD_STATUS_IRQ;
-        pHdr->u32CmdSpecific = 0;
-        PVBOXVDMACMD_CHILD_STATUS_IRQ pBody = VBOXVDMACMD_BODY(pHdr, VBOXVDMACMD_CHILD_STATUS_IRQ);
-        pBody->cInfos = 1;
-        if (idTarget == D3DDDI_ID_ALL)
-        {
-            pBody->fFlags |= VBOXVDMACMD_CHILD_STATUS_IRQ_F_APPLY_TO_ALL;
-        }
-        pBody->aInfos[0].iChild = idTarget;
-        pBody->aInfos[0].fFlags = VBOXVDMA_CHILD_STATUS_F_DISCONNECTED | VBOXVDMA_CHILD_STATUS_F_CONNECTED;
-        /* we're going to KeWaitForSingleObject */
-        Assert(KeGetCurrentIrql() < DISPATCH_LEVEL);
-
-        PVBOXVDMADDI_CMD pDdiCmd = VBOXVDMADDI_CMD_FROM_BUF_DR(pDr);
-        VBOXWDDMCHILDSTATUSCB Ctx;
-        KEVENT Event;
-        KeInitializeEvent(&Event, NotificationEvent, FALSE);
-        Ctx.pDr = pDr;
-        Ctx.pEvent = &Event;
-        vboxVdmaDdiCmdInit(pDdiCmd, 0, 0, vboxWddmChildStatusReportCompletion, &Ctx);
-        /* mark command as submitted & invisible for the dx runtime since dx did not originate it */
-        vboxVdmaDdiCmdSubmittedNotDx(pDdiCmd);
-        int rc = vboxVdmaCBufDrSubmit(pDevExt, &pDevExt->u.primary.Vdma, pDr);
-        Assert(rc == VINF_SUCCESS);
-        if (RT_SUCCESS(rc))
-        {
-            Status = KeWaitForSingleObject(&Event, Executive, KernelMode, FALSE, NULL);
-            Assert(Status == STATUS_SUCCESS);
-            return STATUS_SUCCESS;
-        }
-
-        Status = STATUS_UNSUCCESSFUL;
-
-        vboxVdmaCBufDrFree(&pDevExt->u.primary.Vdma, pDr);
-    }
-    else
-    {
-        Assert(0);
-        /* @todo: try flushing.. */
-        LOGREL(("vboxVdmaCBufDrCreate returned NULL"));
-        Status = STATUS_INSUFFICIENT_RESOURCES;
-    }
-
-    return Status;
-#else
-    VBOXVDMACMD_CHILD_STATUS_IRQ Body = {0};
-    Body.cInfos = 1;
-    if (idTarget == D3DDDI_ID_ALL)
-    {
-        Body.fFlags |= VBOXVDMACMD_CHILD_STATUS_IRQ_F_APPLY_TO_ALL;
-    }
-    Body.aInfos[0].iChild = idTarget;
-    Body.aInfos[0].fFlags = VBOXVDMA_CHILD_STATUS_F_DISCONNECTED | VBOXVDMA_CHILD_STATUS_F_CONNECTED;
-    Assert(KeGetCurrentIrql() <= DISPATCH_LEVEL);
-    return vboxWddmChildStatusDoReportReconnected(pDevExt, &Body);
-#endif
-}
-
-static NTSTATUS vboxWddmChildStatusCheckByMask(PVBOXMP_DEVEXT pDevExt, PVBOXWDDM_VIDEOMODES_INFO paInfos, uint8_t *pMask)
-{
-    NTSTATUS Status = STATUS_SUCCESS;
-    bool bChanged[VBOX_VIDEO_MAX_SCREENS] = {0};
-    int i;
-
-    LOG(("checking child status.."));
-
-    for (i = 0; i < VBoxCommonFromDeviceExt(pDevExt)->cDisplays; ++i)
-    {
-        if (pMask && !ASMBitTest(pMask, i))
-            continue;
-
-        LOG(("requested to change child status for display %d", i));
-
-        /* @todo: check that we actually need the current source->target */
-        PVBOXWDDM_VIDEOMODES_INFO pInfo = &paInfos[i];
-        VIDEO_MODE_INFORMATION *pModeInfo = &pInfo->aModes[pInfo->iPreferredMode];
-        BOOLEAN fMatch = FALSE;
-        Status = vboxVidPnMatchMonitorModes(pDevExt, i, pInfo->aResolutions, pInfo->cResolutions, &fMatch);
-        if (!NT_SUCCESS(Status))
-        {
-            WARN(("vboxVidPnMatchMonitorModes failed Status(0x%x)", Status));
-            /* ignore the failures here, although we probably should not?? */
-            break;
-        }
-
-        bChanged[i] = !fMatch;
-    }
-
-    if (!NT_SUCCESS(Status))
-    {
-        WARN(("updating monitor modes failed, Status(0x%x)", Status));
-        return Status;
-    }
-
-    for (i = 0; i < VBoxCommonFromDeviceExt(pDevExt)->cDisplays; ++i)
-    {
-        if (bChanged[i])
-        {
-            LOG(("modes changed for display %d", i));
-
-            NTSTATUS tmpStatus = vboxWddmChildStatusReportReconnected(pDevExt, i);
-            if (!NT_SUCCESS(tmpStatus))
-            {
-                WARN(("vboxWddmChildStatusReportReconnected failed Status(0x%x)", Status));
-                /* ignore the failures here, although we probably should not?? */
-                break;
-            }
-        }
-    }
-
-    /* wait for the reconnected monitor data to be picked up */
-    CONST DXGK_MONITOR_INTERFACE *pMonitorInterface;
-    Status = pDevExt->u.primary.DxgkInterface.DxgkCbQueryMonitorInterface(pDevExt->u.primary.DxgkInterface.DeviceHandle, DXGK_MONITOR_INTERFACE_VERSION_V1, &pMonitorInterface);
-    if (!NT_SUCCESS(Status))
-    {
-        WARN(("DxgkCbQueryMonitorInterface failed, Status()0x%x", Status));
-        return Status;
-    }
-
-    for (i = 0; i < VBoxCommonFromDeviceExt(pDevExt)->cDisplays; ++i)
-    {
-        D3DKMDT_HMONITORSOURCEMODESET hMonitorSMS;
-        CONST DXGK_MONITORSOURCEMODESET_INTERFACE *pMonitorSMSIf;
-        if (!bChanged[i])
-            continue;
-
-        while (1)
-        {
-            Status = pMonitorInterface->pfnAcquireMonitorSourceModeSet(pDevExt->u.primary.DxgkInterface.DeviceHandle,
-                                                i,
-                                                &hMonitorSMS,
-                                                &pMonitorSMSIf);
-            if (NT_SUCCESS(Status))
-            {
-                NTSTATUS tmpStatus = pMonitorInterface->pfnReleaseMonitorSourceModeSet(pDevExt->u.primary.DxgkInterface.DeviceHandle, hMonitorSMS);
-                if (!NT_SUCCESS(tmpStatus))
-                {
-                    WARN(("pfnReleaseMonitorSourceModeSet failed tmpStatus(0x%x)", tmpStatus));
-                }
-                break;
-            }
-
-            if (Status != STATUS_GRAPHICS_MONITOR_NOT_CONNECTED)
-            {
-                WARN(("DxgkCbQueryMonitorInterface failed, Status()0x%x", Status));
-                break;
-            }
-
-            Assert(KeGetCurrentIrql() < DISPATCH_LEVEL);
-
-            LARGE_INTEGER Interval;
-            Interval.QuadPart = -(int64_t) 2 /* ms */ * 10000;
-            NTSTATUS tmpStatus = KeDelayExecutionThread(KernelMode, FALSE, &Interval);
-            if (!NT_SUCCESS(tmpStatus))
-            {
-                WARN(("KeDelayExecutionThread failed tmpStatus(0x%x)", tmpStatus));
-            }
-        }
-    }
-
-    return STATUS_SUCCESS;
 }
 
@@ -1154,7 +857,9 @@
                     vboxVdmaDdiNodesInit(pDevExt);
                     vboxVideoCmInit(&pDevExt->CmMgr);
+                    vboxVideoCmInit(&pDevExt->SeamlessCtxMgr);
                     InitializeListHead(&pDevExt->SwapchainList3D);
                     pDevExt->cContexts3D = 0;
                     pDevExt->cContexts2D = 0;
+                    pDevExt->cContextsDispIfResize = 0;
                     pDevExt->cUnlockedVBVADisabled = 0;
                     VBOXWDDM_CTXLOCK_INIT(pDevExt);
@@ -1162,5 +867,4 @@
 
                     VBoxMPCmnInitCustomVideoModes(pDevExt);
-                    VBoxWddmInvalidateAllVideoModesInfos(pDevExt);
 
                     VBoxCommonFromDeviceExt(pDevExt)->fAnyX = VBoxVideoAnyWidthAllowed();
@@ -1192,4 +896,61 @@
                     }
 
+                    DWORD dwVal = VBOXWDDM_CFG_DRV_DEFAULT;
+                    HANDLE hKey = NULL;
+                    WCHAR aNameBuf[100];
+
+                    Status = IoOpenDeviceRegistryKey(pDevExt->pPDO, PLUGPLAY_REGKEY_DRIVER, GENERIC_READ, &hKey);
+                    if (!NT_SUCCESS(Status))
+                    {
+                        WARN(("IoOpenDeviceRegistryKey failed, Status = 0x%x", Status));
+                        hKey = NULL;
+                    }
+
+
+                    if (hKey)
+                    {
+                        Status = vboxWddmRegQueryValueDword(hKey, VBOXWDDM_REG_DRV_FLAGS_NAME, &dwVal);
+                        if (!NT_SUCCESS(Status))
+                        {
+                            LOG(("vboxWddmRegQueryValueDword failed, Status = 0x%x", Status));
+                            dwVal = VBOXWDDM_CFG_DRV_DEFAULT;
+                        }
+                    }
+
+                    pDevExt->dwDrvCfgFlags = dwVal;
+
+                    for (UINT i = 0; i < (UINT)VBoxCommonFromDeviceExt(pDevExt)->cDisplays; ++i)
+                    {
+                        PVBOXWDDM_TARGET pTarget = &pDevExt->aTargets[i];
+                        if (i == 0 || (pDevExt->dwDrvCfgFlags & VBOXWDDM_CFG_DRV_SECONDARY_TARGETS_CONNECTED) || !hKey)
+                        {
+                            pTarget->fConnected = true;
+                            pTarget->fConfigured = true;
+                        }
+                        else if (hKey)
+                        {
+                            swprintf(aNameBuf, L"%s%d", VBOXWDDM_REG_DRV_DISPFLAGS_PREFIX, i);
+                            Status = vboxWddmRegQueryValueDword(hKey, aNameBuf, &dwVal);
+                            if (NT_SUCCESS(Status))
+                            {
+                                pTarget->fConnected = !!(dwVal & VBOXWDDM_CFG_DRVTARGET_CONNECTED);
+                                pTarget->fConfigured = true;
+                            }
+                            else
+                            {
+                                WARN(("vboxWddmRegQueryValueDword failed, Status = 0x%x", Status));
+                                pTarget->fConnected = false;
+                                pTarget->fConfigured = false;
+                            }
+                        }
+                    }
+
+                    if (hKey)
+                    {
+                        NTSTATUS tmpStatus = ZwClose(hKey);
+                        Assert(tmpStatus == STATUS_SUCCESS);
+                    }
+
+                    Status = STATUS_SUCCESS;
 #ifdef VBOX_WDDM_WIN8
                     DXGK_DISPLAY_INFORMATION DisplayInfo;
@@ -1230,4 +991,6 @@
                     }
 #endif
+
+                    VBoxWddmInitVideoModes(pDevExt);
                 }
                 else
@@ -1280,4 +1043,6 @@
 
     vboxVideoCmTerm(&pDevExt->CmMgr);
+
+    vboxVideoCmTerm(&pDevExt->SeamlessCtxMgr);
 
     /* do everything we did on DxgkDdiStartDevice in the reverse order */
@@ -1691,5 +1456,5 @@
         ChildRelations[i].ChildDeviceType = TypeVideoOutput;
         ChildRelations[i].ChildCapabilities.Type.VideoOutput.InterfaceTechnology = D3DKMDT_VOT_HD15; /* VGA */
-        ChildRelations[i].ChildCapabilities.Type.VideoOutput.MonitorOrientationAwareness = D3DKMDT_MOA_INTERRUPTIBLE; /* ?? D3DKMDT_MOA_NONE*/
+        ChildRelations[i].ChildCapabilities.Type.VideoOutput.MonitorOrientationAwareness = D3DKMDT_MOA_NONE; //D3DKMDT_MOA_INTERRUPTIBLE; /* ?? D3DKMDT_MOA_NONE*/
         ChildRelations[i].ChildCapabilities.Type.VideoOutput.SupportsSdtvModes = FALSE;
         ChildRelations[i].ChildCapabilities.HpdAwareness = HpdAwarenessInterruptible; /* ?? HpdAwarenessAlwaysConnected; */
@@ -1714,18 +1479,22 @@
     LOGF(("ENTER, context(0x%x)", MiniportDeviceContext));
 
+    PVBOXMP_DEVEXT pDevExt = (PVBOXMP_DEVEXT)MiniportDeviceContext;
+
     NTSTATUS Status = STATUS_SUCCESS;
     switch (ChildStatus->Type)
     {
         case StatusConnection:
-            ChildStatus->HotPlug.Connected = TRUE;
+        {
             LOGF(("StatusConnection"));
+            VBOXWDDM_TARGET *pTarget = &pDevExt->aTargets[ChildStatus->ChildUid];
+            ChildStatus->HotPlug.Connected = !!pTarget->fConnected;
             break;
+        }
         case StatusRotation:
+            LOGF(("StatusRotation"));
             ChildStatus->Rotation.Angle = 0;
-            LOGF(("StatusRotation"));
             break;
         default:
-            LOGREL(("ERROR: status type: %d", ChildStatus->Type));
-            AssertBreakpoint();
+            WARN(("ERROR: status type: %d", ChildStatus->Type));
             Status = STATUS_INVALID_PARAMETER;
             break;
@@ -2993,5 +2762,7 @@
             VBOXWDDM_SOURCE *pSource = &pDevExt->aSources[pS2P->Shadow2Primary.VidPnSourceId];
             PVBOXWDDM_ALLOCATION pSrcAlloc = pS2P->Shadow2Primary.ShadowAlloc.pAlloc;
-            vboxWddmAddrSetVram(&pSrcAlloc->AllocData.Addr, pS2P->Shadow2Primary.ShadowAlloc.segmentIdAlloc, pS2P->Shadow2Primary.ShadowAlloc.offAlloc);
+            BOOLEAN fShadowChanged = vboxWddmAddrSetVram(&pSrcAlloc->AllocData.Addr, pS2P->Shadow2Primary.ShadowAlloc.segmentIdAlloc, pS2P->Shadow2Primary.ShadowAlloc.offAlloc);
+            if (fShadowChanged)
+                pSource->fGhSynced = 0;
             vboxWddmAssignShadow(pDevExt, pSource, pSrcAlloc, pS2P->Shadow2Primary.VidPnSourceId);
             vboxWddmModeRenderFromShadowCheckOnSubmitCommand(pDevExt, NULL);
@@ -3019,7 +2790,8 @@
             PVBOXWDDM_ALLOCATION pDstAlloc = pBlt->Blt.DstAlloc.pAlloc;
             PVBOXWDDM_ALLOCATION pSrcAlloc = pBlt->Blt.SrcAlloc.pAlloc;
+            BOOLEAN fSrcChanged;
 
             vboxWddmAddrSetVram(&pDstAlloc->AllocData.Addr, pBlt->Blt.DstAlloc.segmentIdAlloc, pBlt->Blt.DstAlloc.offAlloc);
-            vboxWddmAddrSetVram(&pSrcAlloc->AllocData.Addr, pBlt->Blt.SrcAlloc.segmentIdAlloc, pBlt->Blt.SrcAlloc.offAlloc);
+            fSrcChanged = vboxWddmAddrSetVram(&pSrcAlloc->AllocData.Addr, pBlt->Blt.SrcAlloc.segmentIdAlloc, pBlt->Blt.SrcAlloc.offAlloc);
 
             if (VBOXWDDM_IS_REAL_FB_ALLOCATION(pDevExt, pDstAlloc))
@@ -3029,5 +2801,10 @@
 
                 if (pSrcAlloc->enmType == VBOXWDDM_ALLOC_TYPE_STD_SHADOWSURFACE)
+                {
+                    if (fSrcChanged)
+                        pSource->fGhSynced = 0;
+
                     vboxWddmAssignShadow(pDevExt, pSource, pSrcAlloc, pDstAlloc->AllocData.SurfDesc.VidPnSourceId);
+                }
                 vboxWddmModeRenderFromShadowCheckOnSubmitCommand(pDevExt, NULL);
                 if(pContext->enmType != VBOXWDDM_CONTEXT_TYPE_CUSTOM_3D
@@ -3910,4 +3687,19 @@
             case VBOXESC_SETVISIBLEREGION:
             {
+                PVBOXWDDM_CONTEXT pContext = (PVBOXWDDM_CONTEXT)pEscape->hContext;
+                if (!pContext)
+                {
+                    WARN(("VBOXESC_SETVISIBLEREGION no context supplied!"));
+                    Status = STATUS_INVALID_PARAMETER;
+                    break;
+                }
+
+                if (pContext->enmType != VBOXWDDM_CONTEXT_TYPE_CUSTOM_DISPIF_SEAMLESS)
+                {
+                    WARN(("VBOXESC_SETVISIBLEREGION invalid context supplied %d!", pContext->enmType));
+                    Status = STATUS_INVALID_PARAMETER;
+                    break;
+                }
+
                 /* visible regions for seamless */
                 LPRGNDATA lpRgnData = VBOXDISPIFESCAPE_DATA(pEscapeHdr, RGNDATA);
@@ -3948,7 +3740,9 @@
                         rc = VbglGRPerform (&req->header);
                         AssertRC(rc);
-                        if (!RT_SUCCESS(rc))
+                        if (RT_SUCCESS(rc))
+                            Status = STATUS_SUCCESS;
+                        else
                         {
-                            LOGREL(("VbglGRPerform failed rc (%d)", rc));
+                            WARN(("VbglGRPerform failed rc (%d)", rc));
                             Status = STATUS_UNSUCCESSFUL;
                         }
@@ -3956,5 +3750,5 @@
                     else
                     {
-                        LOGREL(("VbglGRAlloc failed rc (%d)", rc));
+                        WARN(("VbglGRAlloc failed rc (%d)", rc));
                         Status = STATUS_UNSUCCESSFUL;
                     }
@@ -3962,6 +3756,5 @@
                 else
                 {
-                    LOGREL(("VBOXESC_SETVISIBLEREGION: incorrect buffer size (%d), reported count (%d)", cbRects, lpRgnData->rdh.nCount));
-                    AssertBreakpoint();
+                    WARN(("VBOXESC_SETVISIBLEREGION: incorrect buffer size (%d), reported count (%d)", cbRects, lpRgnData->rdh.nCount));
                     Status = STATUS_INVALID_PARAMETER;
                 }
@@ -4054,28 +3847,55 @@
             case VBOXESC_REINITVIDEOMODES:
             {
-                if (pEscape->Flags.HardwareAccess)
-                {
-                    WARN(("VBOXESC_REINITVIDEOMODES called with HardwareAccess flag set, failing"));
+                if (!pEscape->Flags.HardwareAccess)
+                {
+                    WARN(("VBOXESC_REINITVIDEOMODESBYMASK called without HardwareAccess flag set, failing"));
                     Status = STATUS_INVALID_PARAMETER;
                     break;
                 }
-                WARN(("VBOXESC_REINITVIDEOMODESBYMASK should be called instead"));
-                PVBOXWDDM_VIDEOMODES_INFO pInfos = VBoxWddmUpdateAllVideoModesInfos(pDevExt);
-                Status = vboxWddmChildStatusCheckByMask(pDevExt, pInfos, NULL);
-                if (!NT_SUCCESS(Status))
-                {
-                    WARN(("vboxWddmChildStatusCheckByMask failed, Status 0x%x", Status));
-                }
-                break;
-            }
-            case VBOXESC_REINITVIDEOMODESBYMASK:
-            {
-                BOOLEAN fCheckDisplayRecconect = (pEscapeHdr->u32CmdSpecific & VBOXWDDM_REINITVIDEOMODESBYMASK_F_RECONNECT_DISPLAYS_ON_CHANGE);
-                if (fCheckDisplayRecconect && pEscape->Flags.HardwareAccess)
-                {
-                    WARN(("VBOXESC_REINITVIDEOMODESBYMASK called with HardwareAccess flag set, failing"));
+
+                PVBOXWDDM_CONTEXT pContext = (PVBOXWDDM_CONTEXT)pEscape->hContext;
+                if (!pContext)
+                {
+                    WARN(("VBOXESC_REINITVIDEOMODES no context supplied!"));
                     Status = STATUS_INVALID_PARAMETER;
                     break;
                 }
+
+                if (pContext->enmType != VBOXWDDM_CONTEXT_TYPE_CUSTOM_DISPIF_RESIZE)
+                {
+                    WARN(("VBOXESC_REINITVIDEOMODES invalid context supplied %d!", pContext->enmType));
+                    Status = STATUS_INVALID_PARAMETER;
+                    break;
+                }
+
+                WARN(("VBOXESC_REINITVIDEOMODESBYMASK should be called instead"));
+                VBoxWddmUpdateVideoModesInfoByMask(pDevExt, NULL);
+                Status = STATUS_SUCCESS;
+                break;
+            }
+            case VBOXESC_REINITVIDEOMODESBYMASK:
+            {
+                if (!pEscape->Flags.HardwareAccess)
+                {
+                    WARN(("VBOXESC_REINITVIDEOMODESBYMASK called without HardwareAccess flag set, failing"));
+                    Status = STATUS_INVALID_PARAMETER;
+                    break;
+                }
+
+                PVBOXWDDM_CONTEXT pContext = (PVBOXWDDM_CONTEXT)pEscape->hContext;
+                if (!pContext)
+                {
+                    WARN(("VBOXESC_REINITVIDEOMODESBYMASK no context supplied!"));
+                    Status = STATUS_INVALID_PARAMETER;
+                    break;
+                }
+
+                if (pContext->enmType != VBOXWDDM_CONTEXT_TYPE_CUSTOM_DISPIF_RESIZE)
+                {
+                    WARN(("VBOXESC_REINITVIDEOMODESBYMASK invalid context supplied %d!", pContext->enmType));
+                    Status = STATUS_INVALID_PARAMETER;
+                    break;
+                }
+
                 if (pEscape->PrivateDriverDataSize != sizeof (VBOXDISPIFESCAPE_REINITVIDEOMODESBYMASK))
                 {
@@ -4086,14 +3906,101 @@
                 LOG(("=> VBOXESC_REINITVIDEOMODESBYMASK"));
                 PVBOXDISPIFESCAPE_REINITVIDEOMODESBYMASK pData = (PVBOXDISPIFESCAPE_REINITVIDEOMODESBYMASK)pEscapeHdr;
-                PVBOXWDDM_VIDEOMODES_INFO pInfos = VBoxWddmUpdateVideoModesInfoByMask(pDevExt, pData->ScreenMask);
-                if (fCheckDisplayRecconect)
-                {
-                    Status = vboxWddmChildStatusCheckByMask(pDevExt, pInfos, pData->ScreenMask);
+                VBoxWddmUpdateVideoModesInfoByMask(pDevExt, pData->ScreenMask);
+                Status = STATUS_SUCCESS;
+                LOG(("<= VBOXESC_REINITVIDEOMODESBYMASK"));
+                break;
+            }
+            case VBOXESC_CONFIGURETARGETS:
+            {
+                LOG(("=> VBOXESC_CONFIGURETARGETS"));
+
+                if (!pEscape->Flags.HardwareAccess)
+                {
+                    WARN(("VBOXESC_CONFIGURETARGETS called without HardwareAccess flag set, failing"));
+                    Status = STATUS_INVALID_PARAMETER;
+                    break;
+                }
+
+                PVBOXWDDM_CONTEXT pContext = (PVBOXWDDM_CONTEXT)pEscape->hContext;
+                if (!pContext)
+                {
+                    WARN(("VBOXESC_CONFIGURETARGETS no context supplied!"));
+                    Status = STATUS_INVALID_PARAMETER;
+                    break;
+                }
+
+                if (pContext->enmType != VBOXWDDM_CONTEXT_TYPE_CUSTOM_DISPIF_RESIZE)
+                {
+                    WARN(("VBOXESC_CONFIGURETARGETS invalid context supplied %d!", pContext->enmType));
+                    Status = STATUS_INVALID_PARAMETER;
+                    break;
+                }
+
+                if (pEscape->PrivateDriverDataSize != sizeof (*pEscapeHdr))
+                {
+                    WARN(("VBOXESC_CONFIGURETARGETS invalid private driver size %d", pEscape->PrivateDriverDataSize));
+                    Status = STATUS_INVALID_PARAMETER;
+                    break;
+                }
+
+                if (pEscapeHdr->u32CmdSpecific)
+                {
+                    WARN(("VBOXESC_CONFIGURETARGETS invalid command %d", pEscapeHdr->u32CmdSpecific));
+                    Status = STATUS_INVALID_PARAMETER;
+                    break;
+                }
+
+                HANDLE hKey = NULL;
+                WCHAR aNameBuf[100];
+                uint32_t cAdjusted = 0;
+
+                for (int i = 0; i < VBoxCommonFromDeviceExt(pDevExt)->cDisplays; ++i)
+                {
+                    VBOXWDDM_TARGET *pTarget = &pDevExt->aTargets[i];
+                    if (pTarget->fConfigured)
+                        continue;
+
+                    pTarget->fConfigured = true;
+
+                    if (!pTarget->fConnected)
+                    {
+                        Status = vboxWddmChildStatusConnect(pDevExt, (uint32_t)i, TRUE);
+                        if (NT_SUCCESS(Status))
+                            ++cAdjusted;
+                        else
+                            WARN(("VBOXESC_CONFIGURETARGETS vboxWddmChildStatusConnectSecondaries failed Status 0x%x\n", Status));
+                    }
+
+                    if (!hKey)
+                    {
+                        Status = IoOpenDeviceRegistryKey(pDevExt->pPDO, PLUGPLAY_REGKEY_DRIVER, GENERIC_WRITE, &hKey);
+                        if (!NT_SUCCESS(Status))
+                        {
+                            WARN(("VBOXESC_CONFIGURETARGETS IoOpenDeviceRegistryKey failed, Status = 0x%x", Status));
+                            hKey = NULL;
+                            continue;
+                        }
+                    }
+
+                    Assert(hKey);
+
+                    swprintf(aNameBuf, L"%s%d", VBOXWDDM_REG_DRV_DISPFLAGS_PREFIX, i);
+                    Status = vboxWddmRegSetValueDword(hKey, aNameBuf, VBOXWDDM_CFG_DRVTARGET_CONNECTED);
                     if (!NT_SUCCESS(Status))
-                    {
-                        WARN(("vboxWddmChildStatusCheckByMask failed, Status 0x%x", Status));
-                    }
-                }
-                LOG(("<= VBOXESC_REINITVIDEOMODESBYMASK"));
+                        WARN(("VBOXESC_CONFIGURETARGETS vboxWddmRegSetValueDword (%d) failed Status 0x%x\n", aNameBuf, Status));
+
+                }
+
+                if (hKey)
+                {
+                    NTSTATUS tmpStatus = ZwClose(hKey);
+                    Assert(tmpStatus == STATUS_SUCCESS);
+                }
+
+                pEscapeHdr->u32CmdSpecific = cAdjusted;
+
+                Status = STATUS_SUCCESS;
+
+                LOG(("<= VBOXESC_CONFIGURETARGETS"));
                 break;
             }
@@ -4221,6 +4128,5 @@
             }
             default:
-                Assert(0);
-                LOGREL(("unsupported escape code (0x%x)", pEscapeHdr->escapeCode));
+                WARN(("unsupported escape code (0x%x)", pEscapeHdr->escapeCode));
                 break;
         }
@@ -4228,6 +4134,5 @@
     else
     {
-        LOGREL(("pEscape->PrivateDriverDataSize(%d) < (%d)", pEscape->PrivateDriverDataSize, sizeof (VBOXDISPIFESCAPE)));
-        AssertBreakpoint();
+        WARN(("pEscape->PrivateDriverDataSize(%d) < (%d)", pEscape->PrivateDriverDataSize, sizeof (VBOXDISPIFESCAPE)));
         Status = STATUS_BUFFER_TOO_SMALL;
     }
@@ -4315,5 +4220,4 @@
 
     NTSTATUS Status = STATUS_SUCCESS;
-    BOOLEAN bSupported = TRUE;
 
     PVBOXMP_DEVEXT pContext = (PVBOXMP_DEVEXT)hAdapter;
@@ -4339,8 +4243,6 @@
     }
 
-    VBOXVIDPNPATHITEM aItems[VBOX_VIDEO_MAX_SCREENS];
-    BOOLEAN fDisabledFound = FALSE;
-    Status = vboxVidPnCheckTopology(hVidPnTopology, pVidPnTopologyInterface, TRUE /* fBreakOnDisabled */, RT_ELEMENTS(aItems), aItems, &fDisabledFound);
-    Assert(Status == STATUS_SUCCESS);
+    BOOLEAN fSupported = FALSE;
+    Status = vboxVidPnCheckTopology(hVidPnTopology, pVidPnTopologyInterface, &fSupported);
     if (!NT_SUCCESS(Status))
     {
@@ -4349,11 +4251,8 @@
     }
 
-    if (fDisabledFound)
-    {
+    if (!fSupported)
         LOG(("found unsupported path"));
-        bSupported = FALSE;
-    }
-
-    pIsSupportedVidPnArg->IsVidPnSupported = bSupported;
+
+    pIsSupportedVidPnArg->IsVidPnSupported = fSupported;
 
 #ifdef VBOXWDDM_DEBUG_VIDPN
@@ -4380,9 +4279,13 @@
     vboxVDbgBreakFv();
 
+#ifdef DEBUG_misha
+    Assert(0);
+#endif
+
     PVBOXMP_DEVEXT pDevExt = (PVBOXMP_DEVEXT)hAdapter;
     NTSTATUS Status;
     PVBOXWDDM_RECOMMENDVIDPN pVidPnInfo = pRecommendFunctionalVidPnArg->PrivateDriverDataSize >= sizeof (VBOXWDDM_RECOMMENDVIDPN) ?
             (PVBOXWDDM_RECOMMENDVIDPN)pRecommendFunctionalVidPnArg->pPrivateDriverData : NULL;
-    PVBOXWDDM_VIDEOMODES_INFO pInfos = VBoxWddmUpdateAllVideoModesInfos(pDevExt);
+    PVBOXWDDM_VIDEOMODES_INFO pInfos = VBoxWddmGetAllVideoModesInfos(pDevExt);
     int i;
 
@@ -4529,7 +4432,7 @@
     }
 
-    VBOXVIDPNPATHITEM aItems[VBOX_VIDEO_MAX_SCREENS];
-    Status = vboxVidPnCheckTopology(hVidPnTopology, pVidPnTopologyInterface, FALSE /* fBreakOnDisabled */, RT_ELEMENTS(aItems), aItems, NULL /* *pfDisabledFound */);
-    Assert(Status == STATUS_SUCCESS);
+#ifdef DEBUG_misha
+    BOOLEAN fSupported = FALSE;
+    Status = vboxVidPnCheckTopology(hVidPnTopology, pVidPnTopologyInterface, &fSupported);
     if (!NT_SUCCESS(Status))
     {
@@ -4538,4 +4441,6 @@
     }
 
+    Assert(fSupported);
+#endif
     VBOXVIDPNCOFUNCMODALITY CbContext = {0};
     CbContext.pDevExt = pDevExt;
@@ -4543,10 +4448,7 @@
     CbContext.pEnumCofuncModalityArg = pEnumCofuncModalityArg;
     CbContext.pInfos = VBoxWddmGetAllVideoModesInfos(pDevExt);
-    CbContext.cPathInfos = RT_ELEMENTS(aItems);
-    CbContext.apPathInfos = aItems;
 
     Status = vboxVidPnEnumPaths(hVidPnTopology, pVidPnTopologyInterface,
                     vboxVidPnCofuncModalityPathEnum, &CbContext);
-    Assert(Status == STATUS_SUCCESS);
     if (!NT_SUCCESS(Status))
     {
@@ -4705,5 +4607,4 @@
 }
 
-
 NTSTATUS
 APIENTRY
@@ -4716,21 +4617,7 @@
 
     PVBOXMP_DEVEXT pDevExt = (PVBOXMP_DEVEXT)hAdapter;
-    uint32_t au32OldHeightVisible[VBOX_VIDEO_MAX_SCREENS];
     NTSTATUS Status;
 
     vboxVDbgBreakFv();
-
-    /* we first store the current visible height for each target (monitor)
-     * and then we will zero up it for targets either for the given source
-     * (in case pCommitVidPnArg->AffectedVidPnSourceId != D3DDDI_ID_ALL)
-     * or all targets otherwize.
-     * In the end we will match the old and new visible height for all targets to see if
-     * some of them become inactivated and hide them accordingly,
-     * or we will restore the old height values on failure */
-    for (int i = 0; i < VBoxCommonFromDeviceExt(pDevExt)->cDisplays; ++i)
-    {
-        PVBOXWDDM_TARGET pTarget = &pDevExt->aTargets[i];
-        au32OldHeightVisible[i] = pTarget->HeightVisible;
-    }
 
     do {
@@ -4840,29 +4727,18 @@
         pDevExt->u.primary.hCommittedVidPn = pCommitVidPnArg->hFunctionalVidPn;
 
-        for (int i = 1; /* <- never try to hide a primary monitor */
-                i < VBoxCommonFromDeviceExt(pDevExt)->cDisplays; ++i)
+        for (int i = 0; i < VBoxCommonFromDeviceExt(pDevExt)->cDisplays; ++i)
         {
             PVBOXWDDM_TARGET pTarget = &pDevExt->aTargets[i];
-            if (!pTarget->HeightVisible && !!au32OldHeightVisible[i])
-            {
-                /* the target was previously visible */
-                vboxWddmGhDisplayHideScreen(pDevExt, i);
-            }
-        }
-
-//#ifdef VBOX_WDDM_WIN8
-//        if (g_VBoxDisplayOnly)
-        {
-            for (int i = 0; /* <- never try to hide a primary monitor */
-                    i < VBoxCommonFromDeviceExt(pDevExt)->cDisplays; ++i)
-            {
-                PVBOXWDDM_SOURCE pSource = &pDevExt->aSources[i];
-                if (pSource->bVisible)
-                {
+            PVBOXWDDM_SOURCE pSource = &pDevExt->aSources[i];
+            uint32_t cAutoresizes = pDevExt->cContextsDispIfResize;
+            if (!cAutoresizes)
+            {
+                if (pSource->bVisible || !pTarget->HeightVisible)
                     vboxWddmGhDisplayCheckSetInfoFromSource(pDevExt, pSource);
-                }
-            }
-        }
-//#endif
+            }
+            else
+                pTarget->fStateSyncPening = true;
+        }
+
         LOGF(("LEAVE, SUCCESS status(0x%x), context(0x%x)", Status, hAdapter));
 
@@ -4871,10 +4747,4 @@
 
     AssertRelease(!NT_SUCCESS(Status));
-    /* failure branch restore original visible height values, see comments above */
-    for (int i = 0; i < VBoxCommonFromDeviceExt(pDevExt)->cDisplays; ++i)
-    {
-        PVBOXWDDM_TARGET pTarget = &pDevExt->aTargets[i];
-        pTarget->HeightVisible = au32OldHeightVisible[i];
-    }
 
     LOGF(("LEAVE, !!FAILURE!! status(0x%x), context(0x%x)", Status, hAdapter));
@@ -5848,7 +5718,23 @@
                         break;
                     }
+                    case VBOXWDDM_CONTEXT_TYPE_CUSTOM_DISPIF_RESIZE:
+                    {
+                        pContext->enmType = pInfo->enmType;
+                        ASMAtomicIncU32(&pDevExt->cContextsDispIfResize);
+                        break;
+                    }
+                    case VBOXWDDM_CONTEXT_TYPE_CUSTOM_DISPIF_SEAMLESS:
+                    {
+                        pContext->enmType = pInfo->enmType;
+                        Status = vboxVideoCmCtxAdd(&pDevice->pAdapter->SeamlessCtxMgr, &pContext->CmContext, (HANDLE)pInfo->hUmEvent, pInfo->u64UmInfo);
+                        if (!NT_SUCCESS(Status))
+                        {
+                            WARN(("vboxVideoCmCtxAdd failed, Status 0x%x", Status));
+                        }
+                        break;
+                    }
                     default:
                     {
-                        Assert(0);
+                        WARN(("unsupported context type %d", pInfo->enmType));
                         Status = STATUS_INVALID_PARAMETER;
                         break;
@@ -5891,4 +5777,6 @@
     PVBOXWDDM_CONTEXT pContext = (PVBOXWDDM_CONTEXT)hContext;
     PVBOXMP_DEVEXT pDevExt = pContext->pDevice->pAdapter;
+    NTSTATUS Status = STATUS_SUCCESS;
+
     switch(pContext->enmType)
     {
@@ -5905,4 +5793,26 @@
             uint32_t cContexts = ASMAtomicDecU32(&pDevExt->cContexts2D);
             Assert(cContexts < UINT32_MAX/2);
+            break;
+        }
+        case VBOXWDDM_CONTEXT_TYPE_CUSTOM_DISPIF_RESIZE:
+        {
+            uint32_t cContexts = ASMAtomicDecU32(&pDevExt->cContextsDispIfResize);
+            Assert(cContexts < UINT32_MAX/2);
+            if (!cContexts)
+            {
+                for (int i = 0; i < VBoxCommonFromDeviceExt(pDevExt)->cDisplays; ++i)
+                {
+                    vboxWddmGhDisplayCheckCompletePeningScreenInfo(pDevExt, i);
+                }
+            }
+            break;
+        }
+        case VBOXWDDM_CONTEXT_TYPE_CUSTOM_DISPIF_SEAMLESS:
+        {
+            Status = vboxVideoCmCtxRemove(&pContext->pDevice->pAdapter->SeamlessCtxMgr, &pContext->CmContext);
+            if (!NT_SUCCESS(Status))
+                WARN(("vboxVideoCmCtxRemove failed, Status 0x%x", Status));
+
+            Assert(pContext->CmContext.pSession == NULL);
             break;
         }
@@ -5923,15 +5833,15 @@
     vboxWddmSwapchainCtxTerm(pDevExt, pContext);
 
-    NTSTATUS Status = vboxVideoAMgrCtxDestroy(&pContext->AllocContext);
-    Assert(Status == STATUS_SUCCESS);
-    if (Status == STATUS_SUCCESS)
+    Status = vboxVideoAMgrCtxDestroy(&pContext->AllocContext);
+    if (NT_SUCCESS(Status))
     {
         Status = vboxVideoCmCtxRemove(&pContext->pDevice->pAdapter->CmMgr, &pContext->CmContext);
-        Assert(Status == STATUS_SUCCESS);
-        if (Status == STATUS_SUCCESS)
-        {
+        if (NT_SUCCESS(Status))
             vboxWddmMemFree(pContext);
-        }
-    }
+        else
+            WARN(("vboxVideoCmCtxRemove failed, Status 0x%x", Status));
+    }
+    else
+        WARN(("vboxVideoAMgrCtxDestroy failed, Status 0x%x", Status));
 
     LOGF(("LEAVE, hContext(0x%x)", hContext));
Index: trunk/src/VBox/Additions/WINNT/Graphics/Video/mp/wddm/VBoxMPWddm.h
===================================================================
--- trunk/src/VBox/Additions/WINNT/Graphics/Video/mp/wddm/VBoxMPWddm.h	(revision 48058)
+++ trunk/src/VBox/Additions/WINNT/Graphics/Video/mp/wddm/VBoxMPWddm.h	(revision 48070)
@@ -37,7 +37,29 @@
 //#define VBOXWDDM_DEBUG_VIDPN
 
+#define VBOXWDDM_CFG_DRV_DEFAULT                        0
+#define VBOXWDDM_CFG_DRV_SECONDARY_TARGETS_CONNECTED    1
+
+#define VBOXWDDM_CFG_DRVTARGET_CONNECTED                1
+
 #define VBOXWDDM_CFG_LOG_UM_BACKDOOR 0x00000001
 #define VBOXWDDM_CFG_LOG_UM_DBGPRINT 0x00000002
 #define VBOXWDDM_CFG_STR_LOG_UM L"VBoxLogUm"
+
+#define VBOXWDDM_REG_DRV_FLAGS_NAME L"VBoxFlags"
+#define VBOXWDDM_REG_DRV_DISPFLAGS_PREFIX L"VBoxDispFlags"
+
+#define VBOXWDDM_REG_DRVKEY_PREFIX L"\\Registry\\Machine\\System\\CurrentControlSet\\Control\\Class\\"
+
+#define VBOXWDDM_REG_DISPLAYSETTINGSVIDEOKEY L"\\Registry\\Machine\\System\\CurrentControlSet\\Control\\Video\\"
+#define VBOXWDDM_REG_DISPLAYSETTINGSVIDEOKEY_SUBKEY L"\\Video"
+
+
+#define VBOXWDDM_REG_DISPLAYSETTINGSKEY_PREFIX_VISTA L"\\Registry\\Machine\\System\\CurrentControlSet\\Hardware Profiles\\Current\\System\\CurrentControlSet\\Control\\VIDEO\\"
+#define VBOXWDDM_REG_DISPLAYSETTINGSKEY_PREFIX_WIN7 L"\\Registry\\Machine\\System\\CurrentControlSet\\Hardware Profiles\\UnitedVideo\\CONTROL\\VIDEO\\"
+
+#define VBOXWDDM_REG_DISPLAYSETTINGS_ATTACH_RELX L"Attach.RelativeX"
+#define VBOXWDDM_REG_DISPLAYSETTINGS_ATTACH_RELY L"Attach.RelativeY"
+#define VBOXWDDM_REG_DISPLAYSETTINGS_ATTACH_DESKTOP L"Attach.ToDesktop"
+
 extern DWORD g_VBoxLogUm;
 
@@ -81,8 +103,12 @@
 }
 
-DECLINLINE(VOID) vboxWddmAddrSetVram(PVBOXWDDM_ADDR pAddr, UINT SegmentId, VBOXVIDEOOFFSET offVram)
-{
+DECLINLINE(BOOLEAN) vboxWddmAddrSetVram(PVBOXWDDM_ADDR pAddr, UINT SegmentId, VBOXVIDEOOFFSET offVram)
+{
+    if (pAddr->SegmentId == SegmentId && pAddr->offVram == offVram)
+        return FALSE;
+
     pAddr->SegmentId = SegmentId;
     pAddr->offVram = offVram;
+    return TRUE;
 }
 
@@ -191,4 +217,6 @@
     return pPrimary;
 }
+
+bool vboxWddmGhDisplayCheckSetInfoFromSource(PVBOXMP_DEVEXT pDevExt, PVBOXWDDM_SOURCE pSource);
 
 #define VBOXWDDMENTRY_2_SWAPCHAIN(_pE) ((PVBOXWDDM_SWAPCHAIN)((uint8_t*)(_pE) - RT_OFFSETOF(VBOXWDDM_SWAPCHAIN, DevExtListEntry)))
Index: trunk/src/VBox/Additions/WINNT/VBoxTray/Makefile.kmk
===================================================================
--- trunk/src/VBox/Additions/WINNT/VBoxTray/Makefile.kmk	(revision 48058)
+++ trunk/src/VBox/Additions/WINNT/VBoxTray/Makefile.kmk	(revision 48070)
@@ -61,4 +61,5 @@
  VBoxTray_DEFS   += VBOX_WITH_WDDM
  # VBoxTray_DEFS   += LOG_ENABLED
+ VBoxTray_SOURCES += ../Graphics/Video/disp/wddm/VBoxDispKmt.cpp
 endif
 
Index: trunk/src/VBox/Additions/WINNT/VBoxTray/VBoxDispIf.cpp
===================================================================
--- trunk/src/VBox/Additions/WINNT/VBoxTray/VBoxDispIf.cpp	(revision 48058)
+++ trunk/src/VBox/Additions/WINNT/VBoxTray/VBoxDispIf.cpp	(revision 48070)
@@ -27,4 +27,29 @@
 #endif
 
+#include "VBoxDisplay.h"
+
+#ifndef NT_SUCCESS
+# define NT_SUCCESS(_Status) ((_Status) >= 0)
+#endif
+
+typedef struct VBOXDISPIF_OP
+{
+    PCVBOXDISPIF pIf;
+    VBOXDISPKMT_ADAPTER Adapter;
+    VBOXDISPKMT_DEVICE Device;
+    VBOXDISPKMT_CONTEXT Context;
+} VBOXDISPIF_OP;
+
+DWORD EnableAndResizeDispDev(DEVMODE *paDeviceModes, DISPLAY_DEVICE *paDisplayDevices, DWORD totalDispNum, UINT Id, DWORD aWidth, DWORD aHeight,
+                                    DWORD aBitsPerPixel, DWORD aPosX, DWORD aPosY, BOOL fEnabled, BOOL fExtDispSup);
+
+static DWORD vboxDispIfWddmResizeDisplay(PCVBOXDISPIF const pIf, UINT Id, BOOL fEnable, DISPLAY_DEVICE * paDisplayDevices, DEVMODE *paDeviceMode, UINT devModes);
+
+static DWORD vboxDispIfResizePerform(PCVBOXDISPIF const pIf, UINT iChangedMode, BOOL fEnable, BOOL fExtDispSup, DISPLAY_DEVICE *paDisplayDevices, DEVMODE *paDeviceModes, UINT cDevModes);
+
+static DWORD vboxDispIfWddmEnableDisplaysTryingTopology(PCVBOXDISPIF const pIf, UINT cIds, UINT *pIds, BOOL fEnable);
+
+static DWORD vboxDispIfResizeStartedWDDMOp(VBOXDISPIF_OP *pOp);
+
 /* APIs specific to win7 and above WDDM architecture. Not available for Vista WDDM.
  * This is the reason they have not been put in the VBOXDISPIF struct in VBoxDispIf.h
@@ -42,4 +67,475 @@
 static _VBOXDISPLAYWDDMAPICONTEXT gCtx = {0};
 
+typedef struct VBOXDISPIF_WDDM_DISPCFG
+{
+    UINT32 cPathInfoArray;
+    DISPLAYCONFIG_PATH_INFO *pPathInfoArray;
+    UINT32 cModeInfoArray;
+    DISPLAYCONFIG_MODE_INFO *pModeInfoArray;
+} VBOXDISPIF_WDDM_DISPCFG;
+
+static DWORD vboxDispIfWddmDcCreate(VBOXDISPIF_WDDM_DISPCFG *pCfg, UINT32 fFlags)
+{
+    UINT32 cPathInfoArray = 0;
+    UINT32 cModeInfoArray = 0;
+    DISPLAYCONFIG_PATH_INFO *pPathInfoArray;
+    DISPLAYCONFIG_MODE_INFO *pModeInfoArray;
+    DWORD winEr = gCtx.pfnGetDisplayConfigBufferSizes(fFlags, &cPathInfoArray, &cModeInfoArray);
+    if (winEr != ERROR_SUCCESS)
+    {
+        WARN(("VBoxTray: (WDDM) Failed GetDisplayConfigBufferSizes\n"));
+        return winEr;
+    }
+
+    pPathInfoArray = (DISPLAYCONFIG_PATH_INFO *)malloc(cPathInfoArray * sizeof(DISPLAYCONFIG_PATH_INFO));
+    if (!pPathInfoArray)
+    {
+        WARN(("VBoxTray: (WDDM) malloc failed!\n"));
+        return ERROR_OUTOFMEMORY;
+    }
+    pModeInfoArray = (DISPLAYCONFIG_MODE_INFO *)malloc(cModeInfoArray * sizeof(DISPLAYCONFIG_MODE_INFO));
+    if (!pModeInfoArray)
+    {
+        WARN(("VBoxTray: (WDDM) malloc failed!\n"));
+        free(pPathInfoArray);
+        return ERROR_OUTOFMEMORY;
+    }
+
+    winEr = gCtx.pfnQueryDisplayConfig(fFlags, &cPathInfoArray, pPathInfoArray, &cModeInfoArray, pModeInfoArray, NULL);
+    if (winEr != ERROR_SUCCESS)
+    {
+        WARN(("VBoxTray: (WDDM) Failed QueryDisplayConfig\n"));
+        free(pPathInfoArray);
+        free(pModeInfoArray);
+        return winEr;
+    }
+
+    pCfg->cPathInfoArray = cPathInfoArray;
+    pCfg->pPathInfoArray = pPathInfoArray;
+    pCfg->cModeInfoArray = cModeInfoArray;
+    pCfg->pModeInfoArray = pModeInfoArray;
+    return ERROR_SUCCESS;
+}
+
+static DWORD vboxDispIfWddmDcClone(VBOXDISPIF_WDDM_DISPCFG *pCfg, VBOXDISPIF_WDDM_DISPCFG *pCfgDst)
+{
+    memset(pCfgDst, 0, sizeof (*pCfgDst));
+
+    if (pCfg->cPathInfoArray)
+    {
+        pCfgDst->pPathInfoArray = (DISPLAYCONFIG_PATH_INFO *)malloc(pCfg->cPathInfoArray * sizeof (DISPLAYCONFIG_PATH_INFO));
+        if (!pCfgDst->pPathInfoArray)
+        {
+            WARN(("VBoxTray: (WDDM) malloc failed!\n"));
+            return ERROR_OUTOFMEMORY;
+        }
+
+        memcpy(pCfgDst->pPathInfoArray, pCfg->pPathInfoArray, pCfg->cPathInfoArray * sizeof (DISPLAYCONFIG_PATH_INFO));
+
+        pCfgDst->cPathInfoArray = pCfg->cPathInfoArray;
+    }
+
+    if (pCfg->cModeInfoArray)
+    {
+        pCfgDst->pModeInfoArray = (DISPLAYCONFIG_MODE_INFO *)malloc(pCfg->cModeInfoArray * sizeof (DISPLAYCONFIG_MODE_INFO));
+        if (!pCfgDst->pModeInfoArray)
+        {
+            WARN(("VBoxTray: (WDDM) malloc failed!\n"));
+            if (pCfgDst->pPathInfoArray)
+            {
+                free(pCfgDst->pPathInfoArray);
+                pCfgDst->pPathInfoArray = NULL;
+            }
+            return ERROR_OUTOFMEMORY;
+        }
+
+        memcpy(pCfgDst->pModeInfoArray, pCfg->pModeInfoArray, pCfg->cModeInfoArray * sizeof (DISPLAYCONFIG_MODE_INFO));
+
+        pCfgDst->cModeInfoArray = pCfg->cModeInfoArray;
+    }
+
+    return ERROR_SUCCESS;
+}
+
+
+static VOID vboxDispIfWddmDcTerm(VBOXDISPIF_WDDM_DISPCFG *pCfg)
+{
+    if (pCfg->pPathInfoArray)
+        free(pCfg->pPathInfoArray);
+    if (pCfg->pModeInfoArray)
+        free(pCfg->pModeInfoArray);
+    /* sanity */
+    memset(pCfg, 0, sizeof (*pCfg));
+}
+
+static UINT32 g_cVBoxDispIfWddmDisplays = 0;
+static DWORD vboxDispIfWddmDcQueryNumDisplays(UINT32 *pcDisplays)
+{
+    if (!g_cVBoxDispIfWddmDisplays)
+    {
+        VBOXDISPIF_WDDM_DISPCFG DispCfg;
+        *pcDisplays = 0;
+        DWORD winEr = vboxDispIfWddmDcCreate(&DispCfg, QDC_ALL_PATHS);
+        if (winEr != ERROR_SUCCESS)
+        {
+            WARN(("VBoxTray:(WDDM) vboxDispIfWddmDcCreate Failed winEr %d\n", winEr));
+            return winEr;
+        }
+
+        int cDisplays = -1;
+
+        for (UINT iter = 0; iter < DispCfg.cPathInfoArray; ++iter)
+        {
+            if (cDisplays < (int)(DispCfg.pPathInfoArray[iter].sourceInfo.id))
+                cDisplays = (int)(DispCfg.pPathInfoArray[iter].sourceInfo.id);
+        }
+
+        cDisplays++;
+
+        g_cVBoxDispIfWddmDisplays = cDisplays;
+        Assert(g_cVBoxDispIfWddmDisplays);
+
+        vboxDispIfWddmDcTerm(&DispCfg);
+    }
+
+    *pcDisplays = g_cVBoxDispIfWddmDisplays;
+    return ERROR_SUCCESS;
+}
+
+static int vboxDispIfWddmDcSearchPath(VBOXDISPIF_WDDM_DISPCFG *pCfg, UINT srcId, UINT trgId)
+{
+    for (UINT iter = 0; iter < pCfg->cPathInfoArray; ++iter)
+    {
+        if ((srcId == ~0UL || pCfg->pPathInfoArray[iter].sourceInfo.id == srcId)
+                && (trgId == ~0UL || pCfg->pPathInfoArray[iter].targetInfo.id == trgId))
+        {
+            return (int)iter;
+        }
+    }
+    return -1;
+}
+
+static int vboxDispIfWddmDcSearchActivePath(VBOXDISPIF_WDDM_DISPCFG *pCfg, UINT srcId, UINT trgId)
+{
+    int idx = vboxDispIfWddmDcSearchPath(pCfg, srcId, trgId);
+    if (idx < 0)
+        return idx;
+
+    if (!(pCfg->pPathInfoArray[idx].flags & DISPLAYCONFIG_PATH_ACTIVE))
+        return -1;
+
+    return idx;
+}
+
+static VOID vboxDispIfWddmDcSettingsInvalidateModeIndex(VBOXDISPIF_WDDM_DISPCFG *pCfg, int idx)
+{
+    pCfg->pPathInfoArray[idx].sourceInfo.modeInfoIdx = DISPLAYCONFIG_PATH_MODE_IDX_INVALID;
+    pCfg->pPathInfoArray[idx].targetInfo.modeInfoIdx = DISPLAYCONFIG_PATH_MODE_IDX_INVALID;
+}
+
+static VOID vboxDispIfWddmDcSettingsInvalidateModeIndeces(VBOXDISPIF_WDDM_DISPCFG *pCfg)
+{
+    for (UINT iter = 0; iter < pCfg->cPathInfoArray; ++iter)
+    {
+        vboxDispIfWddmDcSettingsInvalidateModeIndex(pCfg, (int)iter);
+    }
+
+    if (pCfg->pModeInfoArray)
+    {
+        free(pCfg->pModeInfoArray);
+        pCfg->pModeInfoArray = NULL;
+    }
+    pCfg->cModeInfoArray = 0;
+}
+
+static DWORD vboxDispIfWddmDcSettingsModeAdd(VBOXDISPIF_WDDM_DISPCFG *pCfg, UINT *pIdx)
+{
+    UINT32 cModeInfoArray = pCfg->cModeInfoArray + 1;
+    DISPLAYCONFIG_MODE_INFO *pModeInfoArray = (DISPLAYCONFIG_MODE_INFO *)malloc(cModeInfoArray * sizeof (DISPLAYCONFIG_MODE_INFO));
+    if (!pModeInfoArray)
+    {
+        WARN(("VBoxTray: (WDDM) malloc failed!\n"));
+        return ERROR_OUTOFMEMORY;
+    }
+
+    memcpy (pModeInfoArray, pCfg->pModeInfoArray, pCfg->cModeInfoArray * sizeof(DISPLAYCONFIG_MODE_INFO));
+    memset(&pModeInfoArray[cModeInfoArray-1], 0, sizeof (pModeInfoArray[0]));
+    free(pCfg->pModeInfoArray);
+    *pIdx = cModeInfoArray-1;
+    pCfg->pModeInfoArray = pModeInfoArray;
+    pCfg->cModeInfoArray = cModeInfoArray;
+    return ERROR_SUCCESS;
+}
+
+static DWORD vboxDispIfWddmDcSettingsUpdate(VBOXDISPIF_WDDM_DISPCFG *pCfg, int idx, DEVMODE *pDeviceMode, BOOL fInvalidateSrcMode, BOOL fEnable)
+{
+    UINT Id = pCfg->pPathInfoArray[idx].sourceInfo.id;
+
+    if (fInvalidateSrcMode)
+        pCfg->pPathInfoArray[idx].sourceInfo.modeInfoIdx = DISPLAYCONFIG_PATH_MODE_IDX_INVALID;
+    else if (pDeviceMode)
+    {
+        UINT iSrcMode = pCfg->pPathInfoArray[idx].sourceInfo.modeInfoIdx;
+        if (iSrcMode == DISPLAYCONFIG_PATH_MODE_IDX_INVALID)
+        {
+
+            WARN(("VBoxTray: (WDDM) no source mode index specified"));
+            DWORD winEr = vboxDispIfWddmDcSettingsModeAdd(pCfg, &iSrcMode);
+            if (winEr != ERROR_SUCCESS)
+            {
+                WARN(("VBoxTray:(WDDM) vboxDispIfWddmDcSettingsModeAdd Failed winEr %d\n", winEr));
+                return winEr;
+            }
+            pCfg->pPathInfoArray[idx].sourceInfo.modeInfoIdx = iSrcMode;
+        }
+
+        for (int i = 0; i < (int)pCfg->cPathInfoArray; ++i)
+        {
+            if (i == idx)
+                continue;
+
+            if (pCfg->pPathInfoArray[i].sourceInfo.modeInfoIdx == iSrcMode)
+            {
+                /* this is something we're not expecting/supporting */
+                WARN(("VBoxTray: (WDDM) multiple paths have the same mode index"));
+                return ERROR_NOT_SUPPORTED;
+            }
+        }
+
+        if (pDeviceMode->dmFields & DM_PELSWIDTH)
+            pCfg->pModeInfoArray[iSrcMode].sourceMode.width = pDeviceMode->dmPelsWidth;
+        if (pDeviceMode->dmFields & DM_PELSHEIGHT)
+            pCfg->pModeInfoArray[iSrcMode].sourceMode.height = pDeviceMode->dmPelsHeight;
+        if (pDeviceMode->dmFields & DM_POSITION)
+        {
+            pCfg->pModeInfoArray[iSrcMode].sourceMode.position.x = pDeviceMode->dmPosition.x;
+            pCfg->pModeInfoArray[iSrcMode].sourceMode.position.y = pDeviceMode->dmPosition.y;
+        }
+        if (pDeviceMode->dmFields & DM_BITSPERPEL)
+        {
+            switch (pDeviceMode->dmBitsPerPel)
+            {
+                case 32:
+                    pCfg->pModeInfoArray[iSrcMode].sourceMode.pixelFormat = DISPLAYCONFIG_PIXELFORMAT_32BPP;
+                    break;
+                case 24:
+                    pCfg->pModeInfoArray[iSrcMode].sourceMode.pixelFormat = DISPLAYCONFIG_PIXELFORMAT_24BPP;
+                    break;
+                case 16:
+                    pCfg->pModeInfoArray[iSrcMode].sourceMode.pixelFormat = DISPLAYCONFIG_PIXELFORMAT_16BPP;
+                    break;
+                case 8:
+                    pCfg->pModeInfoArray[iSrcMode].sourceMode.pixelFormat = DISPLAYCONFIG_PIXELFORMAT_8BPP;
+                    break;
+                default:
+                    LogRel(("VBoxTray: (WDDM) invalid bpp %d, using 32\n", pDeviceMode->dmBitsPerPel));
+                    pCfg->pModeInfoArray[iSrcMode].sourceMode.pixelFormat = DISPLAYCONFIG_PIXELFORMAT_32BPP;
+                    break;
+            }
+        }
+    }
+
+    pCfg->pPathInfoArray[idx].targetInfo.modeInfoIdx = DISPLAYCONFIG_PATH_MODE_IDX_INVALID;
+
+    if (fEnable)
+        pCfg->pPathInfoArray[idx].flags |= DISPLAYCONFIG_PATH_ACTIVE;
+    else
+        pCfg->pPathInfoArray[idx].flags &= ~DISPLAYCONFIG_PATH_ACTIVE;
+
+    return ERROR_SUCCESS;
+}
+
+static DWORD vboxDispIfWddmDcSet(VBOXDISPIF_WDDM_DISPCFG *pCfg, UINT fFlags)
+{
+    DWORD winEr = gCtx.pfnSetDisplayConfig(pCfg->cPathInfoArray, pCfg->pPathInfoArray, pCfg->cModeInfoArray, pCfg->pModeInfoArray, fFlags);
+    if (winEr != ERROR_SUCCESS)
+        Log(("VBoxTray:(WDDM) pfnSetDisplayConfig Failed for Flags 0x%x\n", fFlags));
+    return winEr;
+}
+
+static BOOL vboxDispIfWddmDcSettingsAdjustSupportedPaths(VBOXDISPIF_WDDM_DISPCFG *pCfg)
+{
+    BOOL fAdjusted = FALSE;
+    for (UINT iter = 0; iter < pCfg->cPathInfoArray; ++iter)
+    {
+        if (pCfg->pPathInfoArray[iter].sourceInfo.id == pCfg->pPathInfoArray[iter].targetInfo.id)
+            continue;
+
+        if (!(pCfg->pPathInfoArray[iter].flags & DISPLAYCONFIG_PATH_ACTIVE))
+            continue;
+
+        pCfg->pPathInfoArray[iter].flags &= ~DISPLAYCONFIG_PATH_ACTIVE;
+        fAdjusted = TRUE;
+    }
+
+    return fAdjusted;
+}
+
+static void vboxDispIfWddmDcSettingsAttachDisbledToPrimary(VBOXDISPIF_WDDM_DISPCFG *pCfg)
+{
+    for (UINT iter = 0; iter < pCfg->cPathInfoArray; ++iter)
+    {
+        if ((pCfg->pPathInfoArray[iter].flags & DISPLAYCONFIG_PATH_ACTIVE))
+            continue;
+
+        pCfg->pPathInfoArray[iter].sourceInfo.id = 0;
+        pCfg->pPathInfoArray[iter].sourceInfo.modeInfoIdx = DISPLAYCONFIG_PATH_MODE_IDX_INVALID;
+        pCfg->pPathInfoArray[iter].targetInfo.modeInfoIdx = DISPLAYCONFIG_PATH_MODE_IDX_INVALID;
+    }
+}
+
+static DWORD vboxDispIfWddmDcSettingsIncludeAllTargets(VBOXDISPIF_WDDM_DISPCFG *pCfg)
+{
+    UINT32 cDisplays = 0;
+    VBOXDISPIF_WDDM_DISPCFG AllCfg;
+    BOOL fAllCfgInited = FALSE;
+
+    DWORD winEr = vboxDispIfWddmDcQueryNumDisplays(&cDisplays);
+    if (winEr != ERROR_SUCCESS)
+    {
+        WARN(("VBoxTray:(WDDM) vboxDispIfWddmDcQueryNumDisplays Failed winEr %d\n", winEr));
+        return winEr;
+    }
+
+    DISPLAYCONFIG_PATH_INFO *pPathInfoArray = (DISPLAYCONFIG_PATH_INFO *)malloc(cDisplays * sizeof(DISPLAYCONFIG_PATH_INFO));
+    if (!pPathInfoArray)
+    {
+        WARN(("malloc failed\n"));
+        return ERROR_OUTOFMEMORY;
+    }
+
+    for (UINT i = 0; i < cDisplays; ++i)
+    {
+        int idx = vboxDispIfWddmDcSearchPath(pCfg, i, i);
+        if (idx < 0)
+        {
+            idx = vboxDispIfWddmDcSearchPath(pCfg, -1, i);
+            if (idx >= 0)
+            {
+                WARN(("VBoxTray:(WDDM) different source and target paare enabled, this is something we would not expect\n"));
+            }
+        }
+
+        if (idx >= 0)
+            pPathInfoArray[i] = pCfg->pPathInfoArray[idx];
+        else
+        {
+            if (!fAllCfgInited)
+            {
+                winEr = vboxDispIfWddmDcCreate(&AllCfg, QDC_ALL_PATHS);
+                if (winEr != ERROR_SUCCESS)
+                {
+                    WARN(("VBoxTray:(WDDM) vboxDispIfWddmDcCreate Failed winEr %d\n", winEr));
+                    free(pPathInfoArray);
+                    return winEr;
+                }
+                fAllCfgInited = TRUE;
+            }
+
+            idx = vboxDispIfWddmDcSearchPath(&AllCfg, i, i);
+            if (idx < 0)
+            {
+                WARN(("VBoxTray:(WDDM) %d %d path not supported\n", i, i));
+                idx = vboxDispIfWddmDcSearchPath(pCfg, -1, i);
+                if (idx < 0)
+                {
+                    WARN(("VBoxTray:(WDDM) %d %d path not supported\n", -1, i));
+                }
+            }
+
+            if (idx >= 0)
+            {
+                pPathInfoArray[i] = AllCfg.pPathInfoArray[idx];
+
+                if (pPathInfoArray[i].flags & DISPLAYCONFIG_PATH_ACTIVE)
+                {
+                    WARN(("VBoxTray:(WDDM) disabled path %d %d is marked active\n",
+                            pPathInfoArray[i].sourceInfo.id, pPathInfoArray[i].targetInfo.id));
+                    pPathInfoArray[i].flags &= ~DISPLAYCONFIG_PATH_ACTIVE;
+                }
+
+                Assert(pPathInfoArray[i].sourceInfo.modeInfoIdx == DISPLAYCONFIG_PATH_MODE_IDX_INVALID);
+                Assert(pPathInfoArray[i].sourceInfo.statusFlags == 0);
+
+                Assert(pPathInfoArray[i].targetInfo.modeInfoIdx == DISPLAYCONFIG_PATH_MODE_IDX_INVALID);
+                Assert(pPathInfoArray[i].targetInfo.outputTechnology == DISPLAYCONFIG_OUTPUT_TECHNOLOGY_HD15);
+                Assert(pPathInfoArray[i].targetInfo.rotation == DISPLAYCONFIG_ROTATION_IDENTITY);
+                Assert(pPathInfoArray[i].targetInfo.scaling == DISPLAYCONFIG_SCALING_PREFERRED);
+                Assert(pPathInfoArray[i].targetInfo.refreshRate.Numerator == 0);
+                Assert(pPathInfoArray[i].targetInfo.refreshRate.Denominator == 0);
+                Assert(pPathInfoArray[i].targetInfo.scanLineOrdering == DISPLAYCONFIG_SCANLINE_ORDERING_UNSPECIFIED);
+                Assert(pPathInfoArray[i].targetInfo.targetAvailable == TRUE);
+                Assert(pPathInfoArray[i].targetInfo.statusFlags == DISPLAYCONFIG_TARGET_FORCIBLE);
+
+                Assert(pPathInfoArray[i].flags == 0);
+            }
+            else
+            {
+                pPathInfoArray[i].sourceInfo.adapterId = pCfg->pPathInfoArray[0].sourceInfo.adapterId;
+                pPathInfoArray[i].sourceInfo.id = i;
+                pPathInfoArray[i].sourceInfo.modeInfoIdx = DISPLAYCONFIG_PATH_MODE_IDX_INVALID;
+                pPathInfoArray[i].sourceInfo.statusFlags = 0;
+
+                pPathInfoArray[i].targetInfo.adapterId = pPathInfoArray[i].sourceInfo.adapterId;
+                pPathInfoArray[i].targetInfo.id = i;
+                pPathInfoArray[i].targetInfo.modeInfoIdx = DISPLAYCONFIG_PATH_MODE_IDX_INVALID;
+                pPathInfoArray[i].targetInfo.outputTechnology = DISPLAYCONFIG_OUTPUT_TECHNOLOGY_HD15;
+                pPathInfoArray[i].targetInfo.rotation = DISPLAYCONFIG_ROTATION_IDENTITY;
+                pPathInfoArray[i].targetInfo.scaling = DISPLAYCONFIG_SCALING_PREFERRED;
+                pPathInfoArray[i].targetInfo.refreshRate.Numerator = 0;
+                pPathInfoArray[i].targetInfo.refreshRate.Denominator = 0;
+                pPathInfoArray[i].targetInfo.scanLineOrdering = DISPLAYCONFIG_SCANLINE_ORDERING_UNSPECIFIED;
+                pPathInfoArray[i].targetInfo.targetAvailable = TRUE;
+                pPathInfoArray[i].targetInfo.statusFlags = DISPLAYCONFIG_TARGET_FORCIBLE;
+
+                pPathInfoArray[i].flags = 0;
+            }
+        }
+    }
+
+    free(pCfg->pPathInfoArray);
+    pCfg->pPathInfoArray = pPathInfoArray;
+    pCfg->cPathInfoArray = cDisplays;
+    if (fAllCfgInited)
+        vboxDispIfWddmDcTerm(&AllCfg);
+
+    return ERROR_SUCCESS;
+}
+
+static DWORD vboxDispIfOpBegin(PCVBOXDISPIF pIf, VBOXDISPIF_OP *pOp)
+{
+    pOp->pIf = pIf;
+
+    HRESULT hr = vboxDispKmtOpenAdapter(&pIf->modeData.wddm.KmtCallbacks, &pOp->Adapter);
+    if (SUCCEEDED(hr))
+    {
+        hr = vboxDispKmtCreateDevice(&pOp->Adapter, &pOp->Device);
+        if (SUCCEEDED(hr))
+        {
+            hr = vboxDispKmtCreateContext(&pOp->Device, &pOp->Context, VBOXWDDM_CONTEXT_TYPE_CUSTOM_DISPIF_RESIZE,
+                    0, 0, NULL, 0ULL);
+            if (SUCCEEDED(hr))
+                return ERROR_SUCCESS;
+            else
+                WARN(("VBoxTray: vboxDispKmtCreateContext failed hr 0x%x", hr));
+
+            vboxDispKmtDestroyDevice(&pOp->Device);
+        }
+        else
+            WARN(("VBoxTray: vboxDispKmtCreateDevice failed hr 0x%x", hr));
+
+        vboxDispKmtCloseAdapter(&pOp->Adapter);
+    }
+
+    return hr;
+}
+
+static VOID vboxDispIfOpEnd(VBOXDISPIF_OP *pOp)
+{
+    vboxDispKmtDestroyContext(&pOp->Context);
+    vboxDispKmtDestroyDevice(&pOp->Device);
+    vboxDispKmtCloseAdapter(&pOp->Adapter);
+}
+
 /* display driver interface abstraction for XPDM & WDDM
  * with WDDM we can not use ExtEscape to communicate with our driver
@@ -60,7 +556,9 @@
 {
 #ifdef VBOX_WITH_WDDM
-    if (pIf->enmMode == VBOXDISPIF_MODE_WDDM)
+    if (pIf->enmMode >= VBOXDISPIF_MODE_WDDM)
     {
         vboxDispIfWddmTerm(pIf);
+
+        vboxDispKmtCallbacksTerm(&pIf->modeData.wddm.KmtCallbacks);
     }
 #endif
@@ -127,47 +625,14 @@
 
             /* this is vista and up */
-            HMODULE hGdi32 = GetModuleHandle("gdi32");
-            if (hGdi32 != NULL)
-            {
-                pIf->modeData.wddm.pfnD3DKMTOpenAdapterFromHdc = (PFND3DKMT_OPENADAPTERFROMHDC)GetProcAddress(hGdi32, "D3DKMTOpenAdapterFromHdc");
-                Log((__FUNCTION__"pfnD3DKMTOpenAdapterFromHdc = %p\n", pIf->modeData.wddm.pfnD3DKMTOpenAdapterFromHdc));
-                bSupported &= !!(pIf->modeData.wddm.pfnD3DKMTOpenAdapterFromHdc);
-
-                pIf->modeData.wddm.pfnD3DKMTOpenAdapterFromGdiDisplayName = (PFND3DKMT_OPENADAPTERFROMGDIDISPLAYNAME)GetProcAddress(hGdi32, "D3DKMTOpenAdapterFromGdiDisplayName");
-                Log((__FUNCTION__": pfnD3DKMTOpenAdapterFromGdiDisplayName = %p\n", pIf->modeData.wddm.pfnD3DKMTOpenAdapterFromGdiDisplayName));
-                bSupported &= !!(pIf->modeData.wddm.pfnD3DKMTOpenAdapterFromGdiDisplayName);
-
-                pIf->modeData.wddm.pfnD3DKMTCloseAdapter = (PFND3DKMT_CLOSEADAPTER)GetProcAddress(hGdi32, "D3DKMTCloseAdapter");
-                Log((__FUNCTION__": pfnD3DKMTCloseAdapter = %p\n", pIf->modeData.wddm.pfnD3DKMTCloseAdapter));
-                bSupported &= !!(pIf->modeData.wddm.pfnD3DKMTCloseAdapter);
-
-                pIf->modeData.wddm.pfnD3DKMTEscape = (PFND3DKMT_ESCAPE)GetProcAddress(hGdi32, "D3DKMTEscape");
-                Log((__FUNCTION__": pfnD3DKMTEscape = %p\n", pIf->modeData.wddm.pfnD3DKMTEscape));
-                bSupported &= !!(pIf->modeData.wddm.pfnD3DKMTCloseAdapter);
-
-                pIf->modeData.wddm.pfnD3DKMTInvalidateActiveVidPn = (PFND3DKMT_INVALIDATEACTIVEVIDPN)GetProcAddress(hGdi32, "D3DKMTInvalidateActiveVidPn");
-                Log((__FUNCTION__": pfnD3DKMTInvalidateActiveVidPn = %p\n", pIf->modeData.wddm.pfnD3DKMTInvalidateActiveVidPn));
-                bSupported &= !!(pIf->modeData.wddm.pfnD3DKMTInvalidateActiveVidPn);
-
-                pIf->modeData.wddm.pfnD3DKMTPollDisplayChildren = (PFND3DKMT_POLLDISPLAYCHILDREN)GetProcAddress(hGdi32, "D3DKMTPollDisplayChildren");
-                Log((__FUNCTION__": pfnD3DKMTPollDisplayChildren = %p\n", pIf->modeData.wddm.pfnD3DKMTPollDisplayChildren));
-                bSupported &= !!(pIf->modeData.wddm.pfnD3DKMTPollDisplayChildren);
-
-                if (!bSupported)
-                {
-                    Log((__FUNCTION__": one of pfnD3DKMT function pointers failed to initialize\n"));
-                    err = ERROR_NOT_SUPPORTED;
-                }
-            }
-            else
-            {
-                Log((__FUNCTION__": GetModuleHandle(gdi32) failed, err(%d)\n", GetLastError()));
-                err = ERROR_NOT_SUPPORTED;
-            }
-
+            HRESULT hr = vboxDispKmtCallbacksInit(&pIf->modeData.wddm.KmtCallbacks);
+            if (FAILED(hr))
+            {
+                WARN(("VBoxTray: vboxDispKmtCallbacksInit failed hr 0x%x\n", hr));
+                err = hr;
+            }
         }
         else
         {
-            Log((__FUNCTION__": GetModuleHandle(user32) failed, err(%d)\n", GetLastError()));
+            WARN((__FUNCTION__": GetModuleHandle(USER32) failed, err(%d)\n", GetLastError()));
             err = ERROR_NOT_SUPPORTED;
         }
@@ -175,5 +640,5 @@
     else
     {
-        Log((__FUNCTION__": can not switch to VBOXDISPIF_MODE_WDDM, because os is not Vista or upper\n"));
+        WARN((__FUNCTION__": can not switch to VBOXDISPIF_MODE_WDDM, because os is not Vista or upper\n"));
         err = ERROR_NOT_SUPPORTED;
     }
@@ -185,4 +650,9 @@
 
     return err;
+}
+
+static DWORD vboxDispIfSwitchToWDDM_W7(PVBOXDISPIF pIf)
+{
+    return vboxDispIfSwitchToWDDM(pIf);
 }
 
@@ -209,5 +679,5 @@
                 {
                     winEr = GetLastError();
-                    Log(("CreateDC failed %d", winEr));
+                    WARN(("CreateDC failed %d", winEr));
                     break;
                 }
@@ -218,172 +688,46 @@
         {
             winEr = GetLastError();
-            Log(("EnumDisplayDevices failed %d", winEr));
+            WARN(("EnumDisplayDevices failed %d", winEr));
             break;
         }
     }
 
-    Log(("vboxDispIfWDDMAdpHdcCreate failure branch %d", winEr));
+    WARN(("vboxDispIfWDDMAdpHdcCreate failure branch %d", winEr));
     return winEr;
 }
 
-
-typedef DECLCALLBACK(BOOLEAN) FNVBOXDISPIFWDDM_ADAPTEROP(PCVBOXDISPIF pIf, D3DKMT_HANDLE hAdapter, DISPLAY_DEVICE *pDev, PVOID pContext);
-typedef FNVBOXDISPIFWDDM_ADAPTEROP *PFNVBOXDISPIFWDDM_ADAPTEROP;
-static DWORD vboxDispIfWDDMAdapterOp(PCVBOXDISPIF pIf, int iDisplay, PFNVBOXDISPIFWDDM_ADAPTEROP pfnOp, PVOID pContext)
-{
-    D3DKMT_OPENADAPTERFROMHDC OpenAdapterData = {0};
-    DISPLAY_DEVICE DDev;
-    DWORD err = vboxDispIfWDDMAdpHdcCreate(iDisplay, &OpenAdapterData.hDc, &DDev);
-    Assert(err == NO_ERROR);
-    if (err == NO_ERROR)
-    {
-        NTSTATUS Status = pIf->modeData.wddm.pfnD3DKMTOpenAdapterFromHdc(&OpenAdapterData);
-        Assert(!Status);
-        if (!Status)
-        {
-            BOOLEAN bCloseAdapter = pfnOp(pIf, OpenAdapterData.hAdapter, &DDev, pContext);
-
-            if (bCloseAdapter)
-            {
-                D3DKMT_CLOSEADAPTER ClosaAdapterData = {0};
-                ClosaAdapterData.hAdapter = OpenAdapterData.hAdapter;
-                Status = pIf->modeData.wddm.pfnD3DKMTCloseAdapter(&ClosaAdapterData);
-                if (Status)
-                {
-                    Log((__FUNCTION__": pfnD3DKMTCloseAdapter failed, Status (0x%x)\n", Status));
-                }
-            }
-        }
-        else
-        {
-            Log((__FUNCTION__": pfnD3DKMTOpenAdapterFromGdiDisplayName failed, Status (0x%x)\n", Status));
-            err = ERROR_GEN_FAILURE;
-        }
-
-        DeleteDC(OpenAdapterData.hDc);
-    }
-    else
-        Log((__FUNCTION__": vboxDispIfWDDMAdpHdcCreate failed, winEr (%d)\n", err));
-
-    return err;
-}
-
-typedef struct
-{
-    NTSTATUS Status;
-    PVBOXDISPIFESCAPE pEscape;
-    int cbData;
-    D3DDDI_ESCAPEFLAGS EscapeFlags;
-} VBOXDISPIFWDDM_ESCAPEOP_CONTEXT, *PVBOXDISPIFWDDM_ESCAPEOP_CONTEXT;
-
-DECLCALLBACK(BOOLEAN) vboxDispIfEscapeWDDMOp(PCVBOXDISPIF pIf, D3DKMT_HANDLE hAdapter, DISPLAY_DEVICE *pDev, PVOID pContext)
-{
-    PVBOXDISPIFWDDM_ESCAPEOP_CONTEXT pCtx = (PVBOXDISPIFWDDM_ESCAPEOP_CONTEXT)pContext;
+static DWORD vboxDispIfEscapeWDDM(PCVBOXDISPIF pIf, PVBOXDISPIFESCAPE pEscape, int cbData, BOOL fHwAccess)
+{
+    DWORD winEr = ERROR_SUCCESS;
+    VBOXDISPKMT_ADAPTER Adapter;
+    HRESULT hr = vboxDispKmtOpenAdapter(&pIf->modeData.wddm.KmtCallbacks, &Adapter);
+    if (!SUCCEEDED(hr))
+    {
+        WARN(("VBoxTray: vboxDispKmtOpenAdapter failed hr 0x%x\n", hr));
+        return hr;
+    }
 
     D3DKMT_ESCAPE EscapeData = {0};
-    EscapeData.hAdapter = hAdapter;
+    EscapeData.hAdapter = Adapter.hAdapter;
     //EscapeData.hDevice = NULL;
     EscapeData.Type = D3DKMT_ESCAPE_DRIVERPRIVATE;
-    EscapeData.Flags = pCtx->EscapeFlags;
-    EscapeData.pPrivateDriverData = pCtx->pEscape;
-    EscapeData.PrivateDriverDataSize = VBOXDISPIFESCAPE_SIZE(pCtx->cbData);
+    if (fHwAccess)
+        EscapeData.Flags.HardwareAccess = 1;
+    EscapeData.pPrivateDriverData = pEscape;
+    EscapeData.PrivateDriverDataSize = VBOXDISPIFESCAPE_SIZE(cbData);
     //EscapeData.hContext = NULL;
 
-    pCtx->Status = pIf->modeData.wddm.pfnD3DKMTEscape(&EscapeData);
-
-    return TRUE;
-}
-
-static DWORD vboxDispIfEscapeWDDM(PCVBOXDISPIF pIf, PVBOXDISPIFESCAPE pEscape, int cbData, BOOL fHwAccess)
-{
-    VBOXDISPIFWDDM_ESCAPEOP_CONTEXT Ctx = {0};
-    Ctx.pEscape = pEscape;
-    Ctx.cbData = cbData;
-    if (fHwAccess)
-        Ctx.EscapeFlags.HardwareAccess = 1;
-    DWORD err = vboxDispIfWDDMAdapterOp(pIf, -1 /* iDisplay, -1 means primary */, vboxDispIfEscapeWDDMOp, &Ctx);
-    if (err == NO_ERROR)
-    {
-        if (!Ctx.Status)
-            err = NO_ERROR;
-        else
-        {
-            if (Ctx.Status == 0xC00000BBL) /* not supported */
-                err = ERROR_NOT_SUPPORTED;
-            else
-                err = ERROR_GEN_FAILURE;
-            Log((__FUNCTION__": pfnD3DKMTEscape failed, Status (0x%x)\n", Ctx.Status));
-        }
-    }
+    NTSTATUS Status = pIf->modeData.wddm.KmtCallbacks.pfnD3DKMTEscape(&EscapeData);
+    if (NT_SUCCESS(Status))
+        winEr = ERROR_SUCCESS;
     else
-        Log((__FUNCTION__": vboxDispIfWDDMAdapterOp failed, err (%d)\n", err));
-
-    return err;
-}
-
-typedef struct
-{
-    NTSTATUS Status;
-    VBOXWDDM_RECOMMENDVIDPN_SCREEN_INFO Info;
-} VBOXDISPIFWDDM_RESIZEOP_CONTEXT, *PVBOXDISPIFWDDM_RESIZEOP_CONTEXT;
-
-DECLCALLBACK(BOOLEAN) vboxDispIfResizeWDDMOp(PCVBOXDISPIF pIf, D3DKMT_HANDLE hAdapter, DISPLAY_DEVICE *pDev, PVOID pContext)
-{
-    PVBOXDISPIFWDDM_RESIZEOP_CONTEXT pCtx = (PVBOXDISPIFWDDM_RESIZEOP_CONTEXT)pContext;
-    D3DKMT_INVALIDATEACTIVEVIDPN IAVidPnData = {0};
-    uint32_t cbData = VBOXWDDM_RECOMMENDVIDPN_SIZE(1);
-    PVBOXWDDM_RECOMMENDVIDPN pData = (PVBOXWDDM_RECOMMENDVIDPN)malloc(cbData);
-    if (pData)
-    {
-        memset(pData, 0, cbData);
-        pData->cScreenInfos = 1;
-        memcpy(&pData->aScreenInfos[0], &pCtx->Info, sizeof (VBOXWDDM_RECOMMENDVIDPN_SCREEN_INFO));
-
-        IAVidPnData.hAdapter = hAdapter;
-        IAVidPnData.pPrivateDriverData = pData;
-        IAVidPnData.PrivateDriverDataSize = cbData;
-
-        pCtx->Status = pIf->modeData.wddm.pfnD3DKMTInvalidateActiveVidPn(&IAVidPnData);
-        Assert(!pCtx->Status);
-        if (pCtx->Status)
-            Log((__FUNCTION__": pfnD3DKMTInvalidateActiveVidPn failed, Status (0x%x)\n", pCtx->Status));
-
-        free(pData);
-    }
-    else
-    {
-        Log((__FUNCTION__": malloc failed\n"));
-        pCtx->Status = -1;
-    }
-
-    return TRUE;
-}
-
-static DWORD vboxDispIfResizeWDDM(PCVBOXDISPIF const pIf, ULONG Id, DWORD Width, DWORD Height, DWORD BitsPerPixel)
-{
-    VBOXDISPIFWDDM_RESIZEOP_CONTEXT Ctx = {0};
-    Ctx.Info.Id = Id;
-    Ctx.Info.Width = Width;
-    Ctx.Info.Height = Height;
-    Ctx.Info.BitsPerPixel = BitsPerPixel;
-    DWORD err = vboxDispIfWDDMAdapterOp(pIf, -1, /* (int)Id - always say -1 to use primary display since the display does not really matter here */
-            vboxDispIfResizeWDDMOp, &Ctx);
-    if (err == NO_ERROR)
-    {
-        if (!Ctx.Status)
-            err = NO_ERROR;
-        else
-        {
-            if (Ctx.Status == 0xC00000BBL) /* not supported */
-                err = ERROR_NOT_SUPPORTED;
-            else
-                err = ERROR_GEN_FAILURE;
-            Log((__FUNCTION__": vboxDispIfResizeWDDMOp failed, Status (0x%x)\n", Ctx.Status));
-        }
-    }
-    else
-        Log((__FUNCTION__": vboxDispIfWDDMAdapterOp failed, err (%d)\n", err));
-
-    return err;
+    {
+        WARN(("VBoxTray: pfnD3DKMTEscape failed Status 0x%x\n", Status));
+        winEr = ERROR_GEN_FAILURE;
+    }
+
+    vboxDispKmtCloseAdapter(&Adapter);
+
+    return winEr;
 }
 #endif
@@ -398,4 +742,5 @@
 #ifdef VBOX_WITH_WDDM
         case VBOXDISPIF_MODE_WDDM:
+        case VBOXDISPIF_MODE_WDDM_W7:
             return vboxDispIfEscapeWDDM(pIf, pEscape, cbData, TRUE /* BOOL fHwAccess */);
 #endif
@@ -415,4 +760,5 @@
 #ifdef VBOX_WITH_WDDM
         case VBOXDISPIF_MODE_WDDM:
+        case VBOXDISPIF_MODE_WDDM_W7:
             return vboxDispIfEscapeWDDM(pIf, pEscape, cbData, TRUE /* BOOL fHwAccess */);
 #endif
@@ -422,28 +768,4 @@
     }
 }
-
-static DWORD vboxDispIfResizeXPDM(PCVBOXDISPIF const pIf, ULONG Id, DWORD Width, DWORD Height, DWORD BitsPerPixel)
-{
-    return ERROR_NOT_SUPPORTED;
-}
-
-DWORD VBoxDispIfResize(PCVBOXDISPIF const pIf, ULONG Id, DWORD Width, DWORD Height, DWORD BitsPerPixel)
-{
-    switch (pIf->enmMode)
-    {
-        case VBOXDISPIF_MODE_XPDM_NT4:
-            return ERROR_NOT_SUPPORTED;
-        case VBOXDISPIF_MODE_XPDM:
-            return vboxDispIfResizeXPDM(pIf, Id, Width, Height, BitsPerPixel);
-#ifdef VBOX_WITH_WDDM
-        case VBOXDISPIF_MODE_WDDM:
-            return vboxDispIfResizeWDDM(pIf, Id, Width, Height, BitsPerPixel);
-#endif
-        default:
-            Log((__FUNCTION__": unknown mode (%d)\n", pIf->enmMode));
-            return ERROR_INVALID_PARAMETER;
-    }
-}
-
 
 #ifdef VBOX_WITH_WDDM
@@ -460,4 +782,7 @@
     UINT_PTR idTimer;
     PCVBOXDISPIF pIf;
+    UINT iChangedMode;
+    BOOL fEnable;
+    BOOL fExtDispSup;
     DISPLAY_DEVICE *paDisplayDevices;
     DEVMODE *paDeviceModes;
@@ -506,5 +831,5 @@
 }
 
-static DWORD vboxDispIfWddmValidateFixResize(PCVBOXDISPIF const pIf, DISPLAY_DEVICE *paDisplayDevices, DEVMODE *paDeviceModes, UINT cDevModes);
+//static DWORD vboxDispIfWddmValidateFixResize(PCVBOXDISPIF const pIf, DISPLAY_DEVICE *paDisplayDevices, DEVMODE *paDeviceModes, UINT cDevModes);
 
 static void vboxRrRetryReschedule()
@@ -512,5 +837,5 @@
 }
 
-static void VBoxRrRetrySchedule(PCVBOXDISPIF const pIf, DISPLAY_DEVICE *paDisplayDevices, DEVMODE *paDeviceModes, UINT cDevModes)
+static void VBoxRrRetrySchedule(PCVBOXDISPIF const pIf, UINT iChangedMode, BOOL fEnable, BOOL fExtDispSup, DISPLAY_DEVICE *paDisplayDevices, DEVMODE *paDeviceModes, UINT cDevModes)
 {
     PVBOXRR pMon = &g_VBoxRr;
@@ -519,4 +844,8 @@
 
     pMon->pIf = pIf;
+    pMon->iChangedMode = iChangedMode;
+    pMon->fEnable = fEnable;
+    pMon->fExtDispSup = fExtDispSup;
+
     if (cDevModes)
     {
@@ -549,5 +878,5 @@
     if (!pMon->idTimer)
     {
-        Log(("VBoxTray: SetTimer failed!, err %d\n", GetLastError()));
+        WARN(("VBoxTray: SetTimer failed!, err %d\n", GetLastError()));
         vboxRrRetryStopLocked();
     }
@@ -562,5 +891,5 @@
     if (pMon->pIf)
     {
-        DWORD dwErr = vboxDispIfWddmValidateFixResize(pMon->pIf, pMon->paDisplayDevices, pMon->paDeviceModes, pMon->cDevModes);
+        DWORD dwErr = vboxDispIfResizePerform(pMon->pIf, pMon->iChangedMode, pMon->fEnable, pMon->fExtDispSup, pMon->paDisplayDevices, pMon->paDeviceModes, pMon->cDevModes);
         if (ERROR_RETRY != dwErr)
             VBoxRrRetryStop();
@@ -634,5 +963,5 @@
         {
             DWORD winErr = GetLastError();
-            Log((__FUNCTION__": RegisterClass failed, winErr(%d)\n", winErr));
+            WARN((__FUNCTION__": RegisterClass failed, winErr(%d)\n", winErr));
             hr = E_FAIL;
         }
@@ -658,5 +987,5 @@
         {
             DWORD winErr = GetLastError();
-            Log((__FUNCTION__": CreateWindowEx failed, winErr(%d)\n", winErr));
+            WARN((__FUNCTION__": CreateWindowEx failed, winErr(%d)\n", winErr));
             hr = E_FAIL;
         }
@@ -673,5 +1002,5 @@
 
     DWORD winErr = GetLastError();
-    Log((__FUNCTION__": DestroyWindow failed, winErr(%d) for hWnd(0x%x)\n", winErr, hWnd));
+    WARN((__FUNCTION__": DestroyWindow failed, winErr(%d) for hWnd(0x%x)\n", winErr, hWnd));
 
     return HRESULT_FROM_WIN32(winErr);
@@ -731,5 +1060,4 @@
             DWORD winEr = GetLastError();
             hr = HRESULT_FROM_WIN32(winEr);
-            Assert(0);
             /* just ensure we never return success in this case */
             Assert(hr != S_OK);
@@ -737,5 +1065,5 @@
             if (hr == S_OK || hr == S_FALSE)
                 hr = E_FAIL;
-            Log(("VBoxTray: GetMessage returned -1, err %d\n", winEr));
+            WARN(("VBoxTray: GetMessage returned -1, err %d\n", winEr));
             VBoxRrRetryStop();
             break;
@@ -769,5 +1097,5 @@
     {
         DWORD winErr = GetLastError();
-        Log((__FUNCTION__": SetEvent failed, winErr = (%d)", winErr));
+        WARN((__FUNCTION__": SetEvent failed, winErr = (%d)", winErr));
         HRESULT tmpHr = HRESULT_FROM_WIN32(winErr);
         Assert(tmpHr != S_OK);
@@ -822,5 +1150,5 @@
         {
             DWORD winErr = GetLastError();
-            Log((__FUNCTION__": CreateThread failed, winErr = (%d)", winErr));
+            WARN((__FUNCTION__": CreateThread failed, winErr = (%d)", winErr));
             hr = HRESULT_FROM_WIN32(winErr);
             Assert(hr != S_OK);
@@ -831,5 +1159,5 @@
     {
         DWORD winErr = GetLastError();
-        Log((__FUNCTION__": CreateEvent failed, winErr = (%d)", winErr));
+        WARN((__FUNCTION__": CreateEvent failed, winErr = (%d)", winErr));
         hr = HRESULT_FROM_WIN32(winErr);
         Assert(hr != S_OK);
@@ -877,190 +1205,6 @@
 }
 
-
-typedef struct VBOXDISPIF_WDDM_INTERNAL
-{
-    PCVBOXDISPIF pIf;
-} VBOXDISPIF_WDDM_INTERNAL, *PVBOXDISPIF_WDDM_INTERNAL;
-
-static VBOXDISPIF_WDDM_INTERNAL g_VBoxDispIfWddm;
-
-static BOOL vboxDispIfWddmValidateResize(DISPLAY_DEVICE *paDisplayDevices, DEVMODE *paDeviceModes, UINT cDevModes)
-{
-    DISPLAY_DEVICE DisplayDevice;
-    int i = 0;
-    UINT cMatched = 0;
-    DEVMODE CurDevMode, RegDevMode;
-    for (int i = 0; ; ++i)
-    {
-        ZeroMemory(&DisplayDevice, sizeof(DISPLAY_DEVICE));
-        DisplayDevice.cb = sizeof(DISPLAY_DEVICE);
-
-        if (!EnumDisplayDevices (NULL, i, &DisplayDevice, 0))
-            break;
-
-        Log(("VBoxTray: vboxDispIfValidateResize: [%d(%d)] %s\n", i, cMatched, DisplayDevice.DeviceName));
-
-        BOOL bFetchDevice = FALSE;
-
-        if (DisplayDevice.StateFlags & DISPLAY_DEVICE_PRIMARY_DEVICE)
-        {
-            Log(("VBoxTray: vboxDispIfValidateResize: Found primary device. err %d\n", GetLastError ()));
-            bFetchDevice = TRUE;
-        }
-        else if (!(DisplayDevice.StateFlags & DISPLAY_DEVICE_MIRRORING_DRIVER))
-        {
-
-            Log(("VBoxTray: vboxDispIfValidateResize: Found secondary device. err %d\n", GetLastError ()));
-            bFetchDevice = TRUE;
-        }
-
-        if (bFetchDevice)
-        {
-            if (cMatched >= cDevModes)
-            {
-                Log(("VBoxTray: vboxDispIfValidateResize: %d >= %d\n", cDevModes, cMatched));
-                return FALSE;
-            }
-
-            /* First try to get the video mode stored in registry (ENUM_REGISTRY_SETTINGS).
-             * A secondary display could be not active at the moment and would not have
-             * a current video mode (ENUM_CURRENT_SETTINGS).
-             */
-            ZeroMemory(&RegDevMode, sizeof(RegDevMode));
-            RegDevMode.dmSize = sizeof(DEVMODE);
-            if (!EnumDisplaySettings((LPSTR)DisplayDevice.DeviceName,
-                 ENUM_REGISTRY_SETTINGS, &RegDevMode))
-            {
-                Log(("VBoxTray: vboxDispIfValidateResize: EnumDisplaySettings error %d\n", GetLastError ()));
-                return FALSE;
-            }
-
-            /* with Win8 WDDM Display-only driver, it seems like sometimes we get an auto-resize setting being stored in registry, although current settings do not match */
-            ZeroMemory(&CurDevMode, sizeof(CurDevMode));
-            CurDevMode.dmSize = sizeof(CurDevMode);
-            if (!EnumDisplaySettings((LPSTR)DisplayDevice.DeviceName,
-                 ENUM_CURRENT_SETTINGS, &CurDevMode))
-            {
-                /* ENUM_CURRENT_SETTINGS returns FALSE when the display is not active:
-                 * for example a disabled secondary display */
-                Log(("VBoxTray: vboxDispIfValidateResize: EnumDisplaySettings(ENUM_CURRENT_SETTINGS) error %d\n", GetLastError ()));
-                return FALSE;
-            }
-
-            /* No ENUM_REGISTRY_SETTINGS yet. Seen on Vista after installation.
-             * Get the current video mode then.
-             */
-            if (   RegDevMode.dmPelsWidth != 0
-                    && RegDevMode.dmPelsHeight == 0)
-            {
-                if (CurDevMode.dmBitsPerPel != RegDevMode.dmBitsPerPel
-                        || CurDevMode.dmPelsWidth != RegDevMode.dmPelsWidth
-                        || CurDevMode.dmPelsHeight != RegDevMode.dmPelsHeight
-                        || CurDevMode.dmPosition.x != RegDevMode.dmPosition.x
-                        || CurDevMode.dmPosition.y != RegDevMode.dmPosition.y)
-                {
-                    Log(("VBoxTray: vboxDispIfValidateResize: current settings do not match registry settings, trating as no-match"));
-                    return FALSE;
-                }
-            }
-
-            UINT j = 0;
-            for (; j < cDevModes; ++j)
-            {
-                if (!strncmp(DisplayDevice.DeviceName, paDisplayDevices[j].DeviceName, RT_ELEMENTS(CurDevMode.dmDeviceName)))
-                {
-                    if (paDeviceModes[j].dmBitsPerPel != CurDevMode.dmBitsPerPel
-                            || (paDeviceModes[j].dmPelsWidth & 0xfff8) != (CurDevMode.dmPelsWidth & 0xfff8)
-                            || (paDeviceModes[j].dmPelsHeight & 0xfff8) != (CurDevMode.dmPelsHeight & 0xfff8)
-                            || (paDeviceModes[j].dmPosition.x & 0xfff8) != (CurDevMode.dmPosition.x & 0xfff8)
-                            || (paDeviceModes[j].dmPosition.y & 0xfff8) != (CurDevMode.dmPosition.y & 0xfff8)
-                            || (paDisplayDevices[j].StateFlags & DISPLAY_DEVICE_ATTACHED_TO_DESKTOP) != (DisplayDevice.StateFlags & DISPLAY_DEVICE_ATTACHED_TO_DESKTOP))
-                    {
-                        return FALSE;
-                    }
-                    break;
-                }
-            }
-
-            if (j == cDevModes)
-                return FALSE;
-
-            ++cMatched;
-        }
-    }
-
-    return cMatched == cDevModes;
-}
-
-static DWORD vboxDispIfWddmValidateFixResize(PCVBOXDISPIF const pIf, DISPLAY_DEVICE *paDisplayDevices, DEVMODE *paDeviceModes, UINT cDevModes)
-{
-    if (vboxDispIfWddmValidateResize(paDisplayDevices, paDeviceModes, cDevModes))
-        return NO_ERROR;
-
-    LONG status = DISP_CHANGE_SUCCESSFUL;
-
-    /* now try to resize in a "regular" way */
-    /* Assign the new rectangles to displays. */
-    for (UINT i = 0; i < cDevModes; i++)
-    {
-        /* On Vista one must specify DM_BITSPERPEL.
-         * Note that the current mode dmBitsPerPel is already in the DEVMODE structure.
-         */
-        paDeviceModes[i].dmFields = DM_POSITION | DM_PELSHEIGHT | DM_PELSWIDTH | DM_BITSPERPEL;
-
-        Log(("VBoxTray: ResizeDisplayDevice: pfnChangeDisplaySettingsEx %x: %dx%dx%d at %d,%d\n",
-                pIf->modeData.wddm.pfnChangeDisplaySettingsEx,
-              paDeviceModes[i].dmPelsWidth,
-              paDeviceModes[i].dmPelsHeight,
-              paDeviceModes[i].dmBitsPerPel,
-              paDeviceModes[i].dmPosition.x,
-              paDeviceModes[i].dmPosition.y));
-
-        /* the miniport might have been adjusted the display mode stuff,
-         * adjust the paDeviceModes[i] by picking the closest available one */
-//        DEVMODE AdjustedMode = paDeviceModes[i];
-//        vboxDispIfAdjustMode(&paDisplayDevices[i], &AdjustedMode);
-
-        LONG tmpStatus = pIf->modeData.wddm.pfnChangeDisplaySettingsEx((LPSTR)paDisplayDevices[i].DeviceName,
-                                        &paDeviceModes[i], NULL, CDS_NORESET | CDS_UPDATEREGISTRY, NULL);
-        Log(("VBoxTray: ResizeDisplayDevice: ChangeDisplaySettingsEx position status %d, err %d\n", tmpStatus, GetLastError ()));
-        if (tmpStatus != DISP_CHANGE_SUCCESSFUL)
-        {
-            status = tmpStatus;
-        }
-    }
-
-    /* A second call to ChangeDisplaySettings updates the monitor. */
-    LONG tmpStatus = pIf->modeData.wddm.pfnChangeDisplaySettingsEx(NULL, NULL, NULL, 0, NULL);
-    Log(("VBoxTray: ResizeDisplayDevice: ChangeDisplaySettings update status %d\n", status));
-    if (tmpStatus == DISP_CHANGE_SUCCESSFUL)
-    {
-        if (status == DISP_CHANGE_SUCCESSFUL)
-        {
-            Log(("VBoxTray: resize succeeded\n"));
-            return NO_ERROR;
-        }
-    }
-    else
-    {
-        if (status == DISP_CHANGE_SUCCESSFUL)
-            status = tmpStatus;
-    }
-
-    if (status == DISP_CHANGE_FAILED)
-    {
-        Log(("VBoxTray: DISP_CHANGE_FAILED, retrying..\n"));
-        return ERROR_RETRY;
-    }
-
-    Log(("VBoxTray: resize failed with status %d\n", status));
-
-    return ERROR_GEN_FAILURE;
-}
-
 static DWORD vboxDispIfWddmInit(PCVBOXDISPIF pIf)
 {
-    memset(&g_VBoxDispIfWddm, 0, sizeof (g_VBoxDispIfWddm));
-    g_VBoxDispIfWddm.pIf = pIf;
     HRESULT hr = VBoxRrInit();
     if (SUCCEEDED(hr))
@@ -1068,5 +1212,6 @@
         return ERROR_SUCCESS;
     }
-    return ERROR_GEN_FAILURE;
+    WARN(("VBoxTray: VBoxRrInit failed hr 0x%x\n", hr));
+    return hr;
 }
 
@@ -1074,58 +1219,110 @@
 {
     VBoxRrTerm();
-    memset(&g_VBoxDispIfWddm, 0, sizeof (g_VBoxDispIfWddm));
-}
-
-typedef struct VBOXDISPIF_REINITMODES_OP
-{
-    VBOXDISPIFESCAPE_REINITVIDEOMODESBYMASK EscData;
-} VBOXDISPIF_REINITMODES_OP, *PVBOXDISPIF_REINITMODES_OP;
-
-static DECLCALLBACK(BOOLEAN) vboxDispIfReninitModesWDDMOp(PCVBOXDISPIF pIf, D3DKMT_HANDLE hAdapter, DISPLAY_DEVICE *pDev, PVOID pContext)
-{
-    PVBOXDISPIF_REINITMODES_OP pData = (PVBOXDISPIF_REINITMODES_OP)pContext;
-    VBOXDISPIFWDDM_ESCAPEOP_CONTEXT Ctx = {0};
-    Ctx.pEscape = &pData->EscData.EscapeHdr;
-    Ctx.cbData = sizeof (pData->EscData) - sizeof (pData->EscData.EscapeHdr);
-//    Ctx.EscapeFlags.HardwareAccess = 0;
-    DWORD err = vboxDispIfWDDMAdapterOp(pIf, -1 /* iDisplay, -1 means primary */, vboxDispIfEscapeWDDMOp, &Ctx);
-    if (err == NO_ERROR)
-    {
-        if (!Ctx.Status)
-            err = NO_ERROR;
-        else
-        {
-            if (Ctx.Status == 0xC00000BBL) /* not supported */
-                err = ERROR_NOT_SUPPORTED;
-            else
-                err = ERROR_GEN_FAILURE;
-            Log((__FUNCTION__": pfnD3DKMTEscape failed, Status (0x%x)\n", Ctx.Status));
-        }
-    }
+}
+
+static DWORD vboxDispIfQueryDisplayConnection(VBOXDISPIF_OP *pOp, UINT32 iDisplay, BOOL *pfConnected)
+{
+    if (pOp->pIf->enmMode == VBOXDISPIF_MODE_WDDM)
+    {
+        /* @todo: do we need ti impl it? */
+        *pfConnected = TRUE;
+        return ERROR_SUCCESS;
+    }
+
+    *pfConnected = FALSE;
+
+    VBOXDISPIF_WDDM_DISPCFG DispCfg;
+    DWORD winEr = vboxDispIfWddmDcCreate(&DispCfg, QDC_ALL_PATHS);
+    if (winEr != ERROR_SUCCESS)
+    {
+        WARN(("VBoxTray: (WDDM) Failed vboxDispIfWddmDcCreate winEr %d\n", winEr));
+        return winEr;
+    }
+
+    int idx = vboxDispIfWddmDcSearchPath(&DispCfg, iDisplay, iDisplay);
+    *pfConnected = (idx >= 0);
+
+    vboxDispIfWddmDcTerm(&DispCfg);
+
+    return ERROR_SUCCESS;
+}
+
+static DWORD vboxDispIfWaitDisplayDataInited(VBOXDISPIF_OP *pOp, const uint8_t *pu8DisplayMask)
+{
+    DWORD winEr = ERROR_SUCCESS;
+    do
+    {
+        Sleep(100);
+
+        D3DKMT_POLLDISPLAYCHILDREN PollData = {0};
+        PollData.hAdapter = pOp->Adapter.hAdapter;
+        PollData.NonDestructiveOnly = 1;
+        NTSTATUS Status = pOp->pIf->modeData.wddm.KmtCallbacks.pfnD3DKMTPollDisplayChildren(&PollData);
+        if (Status != 0)
+        {
+            Log(("VBoxTray: (WDDM) pfnD3DKMTPollDisplayChildren failed, Status (0x%x)\n", Status));
+            continue;
+        }
+
+        BOOL fFound = FALSE;
+#if 0
+        for (UINT i = 0; i < VBOXWDDM_SCREENMASK_SIZE; ++i)
+        {
+            if (pu8DisplayMask && !ASMBitTest(pu8DisplayMask, i))
+                continue;
+
+            BOOL fConnected = FALSE;
+            winEr = vboxDispIfQueryDisplayConnection(pOp, i, &fConnected);
+            if (winEr != ERROR_SUCCESS)
+            {
+                WARN(("VBoxTray: (WDDM) Failed vboxDispIfQueryDisplayConnection winEr %d\n", winEr));
+                return winEr;
+            }
+
+            if (!fConnected)
+            {
+                WARN(("VBoxTray: (WDDM) Display %d not connected, not expected\n", i));
+                fFound = TRUE;
+                break;
+            }
+        }
+#endif
+        if (!fFound)
+            break;
+    } while (1);
+
+    return winEr;
+}
+
+static DWORD vboxDispIfReninitModesWDDM(VBOXDISPIF_OP *pOp, const uint8_t *pScreenIdMask)
+{
+    DWORD winEr = ERROR_SUCCESS;
+    VBOXDISPIFESCAPE_REINITVIDEOMODESBYMASK EscData = {0};
+    EscData.EscapeHdr.escapeCode = VBOXESC_REINITVIDEOMODESBYMASK;
+    memcpy(EscData.ScreenMask, pScreenIdMask, sizeof (EscData.ScreenMask));
+
+    D3DKMT_ESCAPE EscapeData = {0};
+    EscapeData.hAdapter = pOp->Adapter.hAdapter;
+    EscapeData.hDevice = pOp->Device.hDevice;
+    EscapeData.hContext = pOp->Context.hContext;
+    EscapeData.Type = D3DKMT_ESCAPE_DRIVERPRIVATE;
+    EscapeData.Flags.HardwareAccess = 1;
+    EscapeData.pPrivateDriverData = &EscData;
+    EscapeData.PrivateDriverDataSize = sizeof (EscData);
+
+    NTSTATUS Status = pOp->pIf->modeData.wddm.KmtCallbacks.pfnD3DKMTEscape(&EscapeData);
+    if (NT_SUCCESS(Status))
+        winEr = ERROR_SUCCESS;
     else
-        Log((__FUNCTION__": vboxDispIfWDDMAdapterOp failed, err (%d)\n", err));
-
-    D3DKMT_POLLDISPLAYCHILDREN PollData = {0};
-    PollData.hAdapter = hAdapter;
-    PollData.NonDestructiveOnly = 1;
-    NTSTATUS Status = pIf->modeData.wddm.pfnD3DKMTPollDisplayChildren(&PollData);
-    if (Status != 0)
-    {
-        Log((__FUNCTION__": pfnD3DKMTPollDisplayChildren failed, Status (0x%x)\n", Status));
-    }
-    return TRUE;
-}
-
-static DWORD vboxDispIfReninitModesWDDM(PCVBOXDISPIF const pIf, uint8_t *pScreenIdMask, BOOL fReconnectDisplaysOnChange)
-{
-    VBOXDISPIF_REINITMODES_OP OpData = {0};
-    OpData.EscData.EscapeHdr.escapeCode = VBOXESC_REINITVIDEOMODESBYMASK;
-    if (fReconnectDisplaysOnChange)
-        OpData.EscData.EscapeHdr.u32CmdSpecific = VBOXWDDM_REINITVIDEOMODESBYMASK_F_RECONNECT_DISPLAYS_ON_CHANGE;
-
-    memcpy(OpData.EscData.ScreenMask, pScreenIdMask, sizeof (OpData.EscData.ScreenMask));
-
-    DWORD err = vboxDispIfWDDMAdapterOp(pIf, -1 /* iDisplay, -1 means primary */, vboxDispIfReninitModesWDDMOp, &OpData);
-    return err;
+    {
+        WARN(("VBoxTray: pfnD3DKMTEscape VBOXESC_REINITVIDEOMODESBYMASK failed Status 0x%x\n", Status));
+        winEr = ERROR_GEN_FAILURE;
+    }
+
+    winEr =  vboxDispIfWaitDisplayDataInited(pOp, pScreenIdMask);
+    if (winEr != NO_ERROR)
+        WARN(("VBoxTray: (WDDM) Failed vboxDispIfWaitDisplayDataInited winEr %d\n", winEr));
+
+    return winEr;
 }
 
@@ -1137,80 +1334,24 @@
 }
 
-static DWORD vboxDispIfAdjustMode(DISPLAY_DEVICE *pDisplayDevice, DEVMODE *pDeviceMode)
-{
-    DEVMODE CurMode;
-    DEVMODE BestMatchMode;
-    DWORD i = 0;
-    int64_t diffWH = INT64_MAX;
-    int diffBpp = INT32_MAX;
-    for (; ; ++i)
-    {
-        CurMode.dmSize = sizeof (CurMode);
-        CurMode.dmDriverExtra = 0;
-
-        if (!EnumDisplaySettings(pDisplayDevice->DeviceName, i, &CurMode))
-            break;
-
-        if (CurMode.dmPelsWidth == pDeviceMode->dmPelsWidth
-                && CurMode.dmPelsHeight == pDeviceMode->dmPelsHeight
-                && CurMode.dmBitsPerPel == pDeviceMode->dmBitsPerPel)
-        {
-            Log(("Exact match found"));
-            *pDeviceMode = CurMode;
-            return NO_ERROR;
-        }
-
-        int diffCurrW = RT_ABS((int)(CurMode.dmPelsWidth - pDeviceMode->dmPelsWidth));
-        int diffCurrH = RT_ABS((int)(CurMode.dmPelsHeight - pDeviceMode->dmPelsHeight));
-        int diffCurrBpp = RT_ABS((int)(CurMode.dmBitsPerPel - pDeviceMode->dmBitsPerPel)
-                                - 1 /* <- to make higher bpp take precedence over lower ones */
-                                );
-
-        int64_t diffCurrHW = (int64_t)diffCurrW*diffCurrW + (int64_t)diffCurrH*diffCurrH;
-
-        if (i == 0
-               || diffCurrHW < diffWH
-               || (diffCurrHW == diffWH && diffCurrBpp < diffBpp))
-        {
-            /* first run */
-            BestMatchMode = CurMode;
-            diffWH = diffCurrHW;
-            diffBpp = diffCurrBpp;
-            continue;
-        }
-    }
-
-    if (i == 0)
-    {
-        Log(("No modes found!"));
-        return NO_ERROR;
-    }
-
-    *pDeviceMode = BestMatchMode;
-    return NO_ERROR;
-}
-
-static DWORD vboxDispIfAdjustModeValues(PCVBOXDISPIF const pIf, DISPLAY_DEVICE *pDisplayDevice, DEVMODE *pDeviceMode)
-{
-    VBOXDISPIFESCAPE_ADJUSTVIDEOMODES Data = {0};
-    Data.EscapeHdr.escapeCode = VBOXESC_REINITVIDEOMODESBYMASK;
-    Data.EscapeHdr.u32CmdSpecific = 1;
-    Data.aScreenInfos[0].Mode.Id =
-    Data.aScreenInfos[0].Mode.Width = pDeviceMode->dmPelsWidth;
-    Data.aScreenInfos[0].Mode.Height = pDeviceMode->dmPelsHeight;
-    Data.aScreenInfos[0].Mode.BitsPerPixel = pDeviceMode->dmBitsPerPel;
-    if (pDeviceMode->dmPosition.x != 0 || pDeviceMode->dmPosition.y != 0) {
-        Data.aScreenInfos[0].Mode.PosX = pDeviceMode->dmPosition.x;
-        Data.aScreenInfos[0].Mode.PosY = pDeviceMode->dmPosition.y;
-    }
-    DWORD err = vboxDispIfEscapeWDDM(pIf, &Data.EscapeHdr, sizeof (Data) - sizeof (Data.EscapeHdr), TRUE);
-    if (err != NO_ERROR)
-    {
-        Log((__FUNCTION__": VBoxDispIfEscape failed with err (%d)\n", err));
-    }
-    return err;
-}
-
-DWORD vboxDispIfResizeModesWDDM(PCVBOXDISPIF const pIf, UINT iChangedMode, DISPLAY_DEVICE *paDisplayDevices, DEVMODE *paDeviceModes, UINT cDevModes)
+static DWORD vboxDispIfResizePerform(PCVBOXDISPIF const pIf, UINT iChangedMode, BOOL fEnable, BOOL fExtDispSup, DISPLAY_DEVICE *paDisplayDevices, DEVMODE *paDeviceModes, UINT cDevModes)
+{
+    DWORD winEr;
+    if (pIf->enmMode > VBOXDISPIF_MODE_WDDM)
+    {
+        winEr = vboxDispIfWddmResizeDisplay(pIf, iChangedMode, fEnable, paDisplayDevices, paDeviceModes, cDevModes);
+        if (winEr != NO_ERROR)
+            WARN(("VBoxTray: (WDDM) Failed vboxDispIfWddmResizeDisplay winEr %d\n", winEr));
+    }
+    else
+    {
+        winEr = EnableAndResizeDispDev(paDeviceModes, paDisplayDevices, cDevModes, iChangedMode, paDeviceModes[iChangedMode].dmPelsWidth, paDeviceModes[iChangedMode].dmPelsHeight,
+                paDeviceModes[iChangedMode].dmBitsPerPel, paDeviceModes[iChangedMode].dmPosition.x, paDeviceModes[iChangedMode].dmPosition.y, fEnable, fExtDispSup);
+        if (winEr != NO_ERROR)
+            WARN(("VBoxTray: (WDDM) Failed EnableAndResizeDispDev winEr %d\n", winEr));
+    }
+    return winEr;
+}
+
+DWORD vboxDispIfResizeModesWDDM(PCVBOXDISPIF const pIf, UINT iChangedMode, BOOL fEnable, BOOL fExtDispSup, DISPLAY_DEVICE *paDisplayDevices, DEVMODE *paDeviceModes, UINT cDevModes)
 {
     UINT cbVidPnInfo = VBOXWDDM_RECOMMENDVIDPN_SIZE(cDevModes);
@@ -1218,5 +1359,4 @@
     pVidPnInfo->cScreenInfos = cDevModes;
     D3DKMT_HANDLE hAdapter = NULL;
-    NTSTATUS Status;
     DWORD winEr = NO_ERROR;
     UINT i = 0;
@@ -1225,285 +1365,286 @@
     VBoxRrRetryStop();
 
-    for (; i < cDevModes; i++)
-    {
-        PVBOXWDDM_RECOMMENDVIDPN_SCREEN_INFO pInfo = &pVidPnInfo->aScreenInfos[i];
-        D3DKMT_OPENADAPTERFROMHDC OpenAdapterData = {0};
-        OpenAdapterData.hDc = CreateDC(NULL, paDisplayDevices[i].DeviceName, NULL, NULL);
-        if (!OpenAdapterData.hDc)
-        {
-            winEr = GetLastError();
-            Log(("VBoxTray: WARNING: Failed to get dc for display device %s, winEr %d\n", paDisplayDevices[i].DeviceName, winEr));
-            break;
-        }
-
-        Status = pIf->modeData.wddm.pfnD3DKMTOpenAdapterFromHdc(&OpenAdapterData);
-        Assert(!Status);
-        if (Status)
-        {
-            winEr = ERROR_GEN_FAILURE;
-            Log(("VBoxTray: WARNING: Failed to open adapter from dc, Status 0x%x\n", Status));
-            break;
-        }
-
-        pInfo->Id = OpenAdapterData.VidPnSourceId;
-        pInfo->Width = paDeviceModes[i].dmPelsWidth;
-        pInfo->Height = paDeviceModes[i].dmPelsHeight;
-        pInfo->BitsPerPixel = paDeviceModes[i].dmBitsPerPel;
-
-        if (i == iChangedMode && (paDeviceModes[i].dmPosition.x != 0 || paDeviceModes[i].dmPosition.y != 0) )
-        {
-                /* change position values only if not equal to 0*/
-                LogRel(("VBoxTray: (WDDM) Change Position x=%d*y=%d Display Device ID=%d\n", paDeviceModes[i].dmPosition.x, paDeviceModes[i].dmPosition.y, i));
-                pInfo->PosX = paDeviceModes[i].dmPosition.x;
-                pInfo->PosY =  paDeviceModes[i].dmPosition.y;
-        }
-
-        if (!hAdapter)
-        {
-            hAdapter = OpenAdapterData.hAdapter;
-        }
-        else
-        {
-            D3DKMT_CLOSEADAPTER ClosaAdapterData = {0};
-            ClosaAdapterData.hAdapter = OpenAdapterData.hAdapter;
-            Status = pIf->modeData.wddm.pfnD3DKMTCloseAdapter(&ClosaAdapterData);
-            if (Status)
-                Log(("VBoxTray: WARNING: Failed to close adapter, Status 0x%x\n", Status));
-        }
-    }
-
-    BOOL fAbleToInvalidateVidPn = FALSE;
-
-    if (0 && winEr == NO_ERROR)
-    {
-        Assert(hAdapter);
-
-        D3DKMT_INVALIDATEACTIVEVIDPN IAVidPnData = {0};
-        IAVidPnData.hAdapter = hAdapter;
-        IAVidPnData.pPrivateDriverData = pVidPnInfo;
-        IAVidPnData.PrivateDriverDataSize = cbVidPnInfo;
-
-        DWORD winEr = NO_ERROR;
-        Status = pIf->modeData.wddm.pfnD3DKMTInvalidateActiveVidPn(&IAVidPnData);
-        Assert(!Status);
-        if (Status)
-        {
-            Log((__FUNCTION__": pfnD3DKMTInvalidateActiveVidPn failed, Status (0x%x)\n", Status));
-            winEr = ERROR_GEN_FAILURE;
-        }
-        else
-        {
-            fAbleToInvalidateVidPn = TRUE;
-        }
-    }
-
-    if (hAdapter)
-    {
-        D3DKMT_CLOSEADAPTER ClosaAdapterData = {0};
-        ClosaAdapterData.hAdapter = hAdapter;
-        Status = pIf->modeData.wddm.pfnD3DKMTCloseAdapter(&ClosaAdapterData);
-        if (Status)
-            Log(("VBoxTray: WARNING: Failed to close adapter[2], Status 0x%x\n", Status));
-    }
-
-//    for (i = 0; i < cDevModes; i++)
-//    {
-//        vboxDispIfAdjustMode(&paDisplayDevices[i], &paDeviceModes[i]);
-//    }
-
-    if (fAbleToInvalidateVidPn)
-    {
-        Log(("VBoxTray: Invalidating VidPn Worked!\n"));
-        OSVERSIONINFO OSinfo;
-        OSinfo.dwOSVersionInfoSize = sizeof (OSinfo);
-        GetVersionEx (&OSinfo);
-         /* for win 7 and above calling ChangeDisplaySettingsEx to resize a specific display, is having
-          * a side affect for enabling all the monitors including the disabled ones. So using
-          * WDDM win 7 APIs to resize the display for OSes Win7 and above.
-          */
-        if (OSinfo.dwMajorVersion >= 6 && OSinfo.dwMinorVersion >= 1)
-            winEr = vboxDispIfWddmResizeDisplay(pIf, iChangedMode, paDisplayDevices, paDeviceModes, cDevModes);
-        else
-            winEr = vboxDispIfWddmValidateFixResize(pIf, paDisplayDevices, paDeviceModes, cDevModes);
-
-    }
-    else
-    {
-        Log(("VBoxTray: Falling back to monitor mode reinit\n"));
-        /* fallback impl needed for display-only driver
-         * since D3DKMTInvalidateActiveVidPn is not available for WDDM > 1.0:
-         * make the driver invalidate VidPn,
-         * which is done by emulating a monitor re-plug currently */
+    VBOXDISPIF_OP Op;
+
+    winEr = vboxDispIfOpBegin(pIf, &Op);
+    if (winEr != NO_ERROR)
+    {
+        WARN(("VBoxTray: vboxDispIfOpBegin failed winEr 0x%x", winEr));
+        return winEr;
+    }
+
+
+//        if (fEnable)
+    {
+
         uint8_t ScreenMask[VBOXWDDM_SCREENMASK_SIZE] = {0};
         ASMBitSet(ScreenMask, iChangedMode);
-        vboxDispIfReninitModesWDDM(pIf, ScreenMask, TRUE);
-
-        OSVERSIONINFO OSinfo;
-        OSinfo.dwOSVersionInfoSize = sizeof (OSinfo);
-        GetVersionEx (&OSinfo);
-        if (OSinfo.dwMajorVersion >= 6 && OSinfo.dwMinorVersion >= 1)
-            winEr = vboxDispIfWddmResizeDisplay(pIf, iChangedMode, paDisplayDevices, paDeviceModes, cDevModes);
-        else
-            winEr = vboxDispIfWddmValidateFixResize(pIf, paDisplayDevices, paDeviceModes, cDevModes);
-        Assert(winEr == NO_ERROR);
-    }
+        vboxDispIfReninitModesWDDM(&Op, ScreenMask);
+    }
+
+    winEr = vboxDispIfResizePerform(pIf, iChangedMode, fEnable, fExtDispSup, paDisplayDevices, paDeviceModes, cDevModes);
 
     if (winEr == ERROR_RETRY)
     {
-        VBoxRrRetrySchedule(pIf, paDisplayDevices, paDeviceModes, cDevModes);
+        VBoxRrRetrySchedule(pIf, iChangedMode, fEnable, fExtDispSup, paDisplayDevices, paDeviceModes, cDevModes);
         /* just pretend everything is fine so far */
         winEr = NO_ERROR;
     }
 
+    vboxDispIfOpEnd(&Op);
+
     return winEr;
 }
 
-DWORD vboxDispIfWddmEnableDisplay(PCVBOXDISPIF const pIf, UINT Id, bool fEnabled)
-{
-    DISPLAYCONFIG_PATH_INFO *pPathInfoArray;
-    DISPLAYCONFIG_MODE_INFO *pModeInfoArray;
-    UINT numPathArrayElements = 0;
-    UINT numModeInfoArrayElements = 0;
-    ULONG dwStatus;
-
-    dwStatus = gCtx.pfnGetDisplayConfigBufferSizes(fEnabled ? QDC_ALL_PATHS : QDC_ONLY_ACTIVE_PATHS, &numPathArrayElements, &numModeInfoArrayElements);
-    if (dwStatus != ERROR_SUCCESS)
-    {
-        LogFlow(("VBoxTray: (WDDM) Failed GetDisplayConfigBufferSizes \n"));
-        return dwStatus;
-    }
-    pPathInfoArray = (DISPLAYCONFIG_PATH_INFO *)malloc(numPathArrayElements * sizeof(DISPLAYCONFIG_PATH_INFO));
-     if (!pPathInfoArray)
-        return ERROR_OUTOFMEMORY;
-    pModeInfoArray = (DISPLAYCONFIG_MODE_INFO *)malloc(numModeInfoArrayElements * sizeof(DISPLAYCONFIG_MODE_INFO));
-    if (!pModeInfoArray )
-    {
-        if (pPathInfoArray)
-        {
-            free(pPathInfoArray);
-        }
-        return ERROR_OUTOFMEMORY;
-    }
-    dwStatus = gCtx.pfnQueryDisplayConfig(fEnabled ? QDC_ALL_PATHS : QDC_ONLY_ACTIVE_PATHS, &numPathArrayElements, pPathInfoArray,&numModeInfoArrayElements, pModeInfoArray, NULL);
-    if (dwStatus != ERROR_SUCCESS)
-    {
-        LogFlow(("VBoxTray: (WDDM) Failed QueryDisplayConfig \n"));
-        free(pPathInfoArray);
-        free(pModeInfoArray);
-        return dwStatus;
-    }
-    for (unsigned int i=0; i < numPathArrayElements; ++i)
-    {
-        LogRel(("Sourceid= %d and targetid = %d\n", pPathInfoArray[i].sourceInfo.id, pPathInfoArray[i].targetInfo.id));
-        if (pPathInfoArray[i].sourceInfo.id == Id)
-        {
-            if (fEnabled)
-            {
-                LogRel(("VBoxTray: (WDDM) Enable the Display Device i =%d \n", i));
-                pPathInfoArray[i].flags=DISPLAYCONFIG_PATH_ACTIVE;
+static DWORD vboxDispIfWddmEnableDisplays(PCVBOXDISPIF const pIf, UINT cIds, UINT *pIds, BOOL fEnabled, BOOL fSetTopology, DEVMODE *pDeviceMode)
+{
+    VBOXDISPIF_WDDM_DISPCFG DispCfg;
+
+    DWORD winEr;
+    int iPath;
+
+    winEr = vboxDispIfWddmDcCreate(&DispCfg, QDC_ONLY_ACTIVE_PATHS);
+    if (winEr != ERROR_SUCCESS)
+    {
+        WARN(("VBoxTray: (WDDM) Failed vboxDispIfWddmDcCreate winEr %d\n", winEr));
+        return winEr;
+    }
+
+    UINT cChangeIds = 0;
+    UINT *pChangeIds = (UINT*)alloca(cIds * sizeof (*pChangeIds));
+    if (!pChangeIds)
+    {
+        WARN(("VBoxTray: (WDDM) Failed to alloc change ids\n"));
+        winEr = ERROR_OUTOFMEMORY;
+        goto done;
+    }
+
+    for (UINT i = 0; i < cIds; ++i)
+    {
+        UINT Id = pIds[i];
+        bool fIsDup = false;
+        for (UINT j = 0; j < cChangeIds; ++j)
+        {
+            if (pChangeIds[j] == Id)
+            {
+                fIsDup = true;
                 break;
             }
-            else
-            {
-                LogRel(("VBoxTray: (WDDM) Disable the Display Device Path ID=%d and Sourceid=%d\n", i, pPathInfoArray[i].sourceInfo.id));
-                pPathInfoArray[i].flags=0;
-                break;
-            }
-        }
-    }
-    dwStatus = gCtx.pfnSetDisplayConfig(numPathArrayElements, pPathInfoArray, numModeInfoArrayElements, pModeInfoArray, (SDC_APPLY | SDC_SAVE_TO_DATABASE| SDC_ALLOW_CHANGES | SDC_USE_SUPPLIED_DISPLAY_CONFIG));
-    if (dwStatus != ERROR_SUCCESS)
-    {
-        free(pPathInfoArray);
-        free(pModeInfoArray);
-        LogRel(("VBoxTray:(WDDM) Failed to Enable/ disable the monitor."));
-        return dwStatus;
-    }
-    free(pPathInfoArray);
-    free(pModeInfoArray);
-    return ERROR_SUCCESS;
-}
-
-DWORD vboxDispIfWddmResizeDisplay(PCVBOXDISPIF const pIf, UINT Id, DISPLAY_DEVICE * paDisplayDevices, DEVMODE *paDeviceMode, UINT devModes)
-{
-    DISPLAYCONFIG_PATH_INFO *pPathInfoArray;
-    DISPLAYCONFIG_MODE_INFO *pModeInfoArray;
-    UINT numPathArrayElements = 0;
-    UINT numModeInfoArrayElements = 0;
-    ULONG dwStatus;
-    bool fFoundDisplay = false;
-
-    dwStatus = gCtx.pfnGetDisplayConfigBufferSizes(QDC_ONLY_ACTIVE_PATHS, &numPathArrayElements, &numModeInfoArrayElements);
-    if (dwStatus != ERROR_SUCCESS)
-    {
-        LogFlow(("VBoxTray: (WDDM) Failed GetDisplayConfigBufferSizes \n"));
-        return dwStatus;
-    }
-    pPathInfoArray = (DISPLAYCONFIG_PATH_INFO *)malloc(numPathArrayElements * sizeof(DISPLAYCONFIG_PATH_INFO));
-    if (!pPathInfoArray)
-        return ERROR_OUTOFMEMORY;
-    pModeInfoArray = (DISPLAYCONFIG_MODE_INFO *)malloc(numModeInfoArrayElements * sizeof(DISPLAYCONFIG_MODE_INFO));
-    if (!pModeInfoArray )
-    {
-        if (pPathInfoArray)
-        {
-            free(pPathInfoArray);
-        }
-        return ERROR_OUTOFMEMORY;
-    }
-    dwStatus = gCtx.pfnQueryDisplayConfig( QDC_ONLY_ACTIVE_PATHS, &numPathArrayElements, pPathInfoArray,&numModeInfoArrayElements, pModeInfoArray, NULL);
-    if (dwStatus != ERROR_SUCCESS)
-    {
-        LogFlow(("VBoxTray: (WDDM) Failed QueryDisplayConfig \n"));
-        free(pPathInfoArray);
-        free(pModeInfoArray);
-        return dwStatus;
-    }
-    LogFlow(("VBoxTray: NumPath =%d and NumMod=%d\n", numPathArrayElements, numModeInfoArrayElements));
-    for (UINT iter = 0; iter < numPathArrayElements; ++iter)
-    {
-        LogFlow(("Sourceid= %d and targetid = %d iter =%d and id = %d\n", pPathInfoArray[iter].sourceInfo.id, pPathInfoArray[iter].targetInfo.id, iter, Id));
-        if (pPathInfoArray[iter].sourceInfo.id == Id)
-        {
-            UINT iModIdx = pPathInfoArray[iter].sourceInfo.modeInfoIdx;
-            LogFlow(("VBoxTray: Mode Index = %d\n", iModIdx));
-            pModeInfoArray[iModIdx].sourceMode.width = paDeviceMode[Id].dmPelsWidth;
-            pModeInfoArray[iModIdx].sourceMode.height = paDeviceMode[Id].dmPelsHeight;
-            if(paDeviceMode[Id].dmPosition.x != 0 || paDeviceMode[Id].dmPosition.y != 0)
-            {
-                pModeInfoArray[iModIdx].sourceMode.position.x = paDeviceMode[Id].dmPosition.x;
-                pModeInfoArray[iModIdx].sourceMode.position.y = paDeviceMode[Id].dmPosition.y;
-            }
-            fFoundDisplay = true;
-            break;
-        }
-    }
-    if (fFoundDisplay)
-    {
-        /* Call SetDisplayConfig only if displaywith ID=Id has been found. */
-        LogFlow(("VBoxTray: Found Display with Id=%d\n", Id));
-        dwStatus = gCtx.pfnSetDisplayConfig(numPathArrayElements, pPathInfoArray, numModeInfoArrayElements, pModeInfoArray,(SDC_APPLY | SDC_SAVE_TO_DATABASE| SDC_ALLOW_CHANGES | SDC_USE_SUPPLIED_DISPLAY_CONFIG));
-        if (dwStatus != ERROR_SUCCESS)
-        {
-            LogRel(("VBoxTray:(WDDM) Failed to resize the monitor.\n"));
-            free(pPathInfoArray);
-            free(pModeInfoArray);
-
-            if (dwStatus == ERROR_GEN_FAILURE)
-            {
-                LogRel(("VBoxTray:(WDDM) going to retry\n"));
-                return ERROR_RETRY; /* <- to make sure we retry */
-            }
-            return dwStatus;
-        }
-    }
-    free(pPathInfoArray);
-    free(pModeInfoArray);
-    return ERROR_SUCCESS;
+        }
+
+        if (fIsDup)
+            continue;
+
+        iPath = vboxDispIfWddmDcSearchPath(&DispCfg, Id, Id);
+
+        if (!((iPath >= 0) && (DispCfg.pPathInfoArray[iPath].flags & DISPLAYCONFIG_PATH_ACTIVE)) != !fEnabled)
+        {
+            pChangeIds[cChangeIds] = Id;
+            ++cChangeIds;
+        }
+    }
+
+    if (cChangeIds == 0)
+    {
+        Log(("VBoxTray: (WDDM) vboxDispIfWddmEnableDisplay: settings are up to date\n"));
+        winEr = ERROR_SUCCESS;
+        goto done;
+    }
+
+    /* we want to set primary for every disabled for non-topoly mode only */
+    winEr = vboxDispIfWddmDcSettingsIncludeAllTargets(&DispCfg);
+    if (winEr != ERROR_SUCCESS)
+    {
+        WARN(("VBoxTray: (WDDM) Failed vboxDispIfWddmDcSettingsIncludeAllTargets winEr %d\n", winEr));
+        return winEr;
+    }
+
+    if (fSetTopology)
+        vboxDispIfWddmDcSettingsInvalidateModeIndeces(&DispCfg);
+
+    for (UINT i = 0; i < cChangeIds; ++i)
+    {
+        UINT Id = pChangeIds[i];
+        /* re-query paths */
+        iPath = vboxDispIfWddmDcSearchPath(&DispCfg, -1, Id);
+        if (iPath < 0)
+        {
+            WARN(("VBoxTray: (WDDM) path index not found while it should"));
+            winEr = ERROR_GEN_FAILURE;
+            goto done;
+        }
+
+        winEr = vboxDispIfWddmDcSettingsUpdate(&DispCfg, iPath, pDeviceMode, !fEnabled || fSetTopology, fEnabled);
+        if (winEr != ERROR_SUCCESS)
+        {
+            WARN(("VBoxTray: (WDDM) Failed vboxDispIfWddmDcSettingsUpdate winEr %d\n", winEr));
+            goto done;
+        }
+    }
+
+    if (!fSetTopology)
+        vboxDispIfWddmDcSettingsAttachDisbledToPrimary(&DispCfg);
+
+#if 0
+    /* ensure the zero-index (primary) screen is enabled */
+    iPath = vboxDispIfWddmDcSearchPath(&DispCfg, 0, 0);
+    if (iPath < 0)
+    {
+        WARN(("VBoxTray: (WDDM) path index not found while it should"));
+        winEr = ERROR_GEN_FAILURE;
+        goto done;
+    }
+
+    winEr = vboxDispIfWddmDcSettingsUpdate(&DispCfg, iPath, /* just re-use device node here*/ pDeviceMode, fSetTopology, TRUE);
+    if (winEr != ERROR_SUCCESS)
+    {
+        WARN(("VBoxTray: (WDDM) Failed vboxDispIfWddmDcSettingsUpdate winEr %d\n", winEr));
+        goto done;
+    }
+#endif
+
+    UINT fSetFlags = !fSetTopology ? (SDC_USE_SUPPLIED_DISPLAY_CONFIG) : (SDC_ALLOW_PATH_ORDER_CHANGES | SDC_TOPOLOGY_SUPPLIED);
+    winEr = vboxDispIfWddmDcSet(&DispCfg, fSetFlags | SDC_VALIDATE);
+    if (winEr != ERROR_SUCCESS)
+    {
+        if (!fSetTopology)
+        {
+            WARN(("VBoxTray: (WDDM) vboxDispIfWddmDcSet validation failed winEr, trying with changes %d\n", winEr));
+            fSetFlags |= SDC_ALLOW_CHANGES;
+        }
+        else
+        {
+            Log(("VBoxTray: (WDDM) vboxDispIfWddmDcSet topology validation failed winEr %d\n", winEr));
+            goto done;
+        }
+    }
+
+    if (!fSetTopology)
+        fSetFlags |= SDC_SAVE_TO_DATABASE;
+
+    winEr = vboxDispIfWddmDcSet(&DispCfg, fSetFlags | SDC_APPLY);
+    if (winEr != ERROR_SUCCESS)
+        WARN(("VBoxTray: (WDDM) vboxDispIfWddmDcSet apply failed winEr %d\n", winEr));
+
+done:
+    vboxDispIfWddmDcTerm(&DispCfg);
+
+    return winEr;
+}
+
+static DWORD vboxDispIfWddmEnableDisplaysTryingTopology(PCVBOXDISPIF const pIf, UINT cIds, UINT *pIds, BOOL fEnable)
+{
+    DWORD winEr = vboxDispIfWddmEnableDisplays(pIf, cIds, pIds, fEnable, FALSE, NULL);
+    if (winEr != ERROR_SUCCESS)
+    {
+        if (fEnable)
+            WARN(("VBoxTray: (WDDM) Failed vboxDispIfWddmEnableDisplay mode winEr %d\n", winEr));
+        else
+            Log(("VBoxTray: (WDDM) Failed vboxDispIfWddmEnableDisplay mode winEr %d\n", winEr));
+        winEr = vboxDispIfWddmEnableDisplays(pIf, cIds, pIds, fEnable, TRUE, NULL);
+        if (winEr != ERROR_SUCCESS)
+            WARN(("VBoxTray: (WDDM) Failed vboxDispIfWddmEnableDisplay mode winEr %d\n", winEr));
+    }
+
+    return winEr;
+}
+
+static DWORD vboxDispIfWddmResizeDisplay(PCVBOXDISPIF const pIf, UINT Id, BOOL fEnable, DISPLAY_DEVICE * paDisplayDevices, DEVMODE *paDeviceMode, UINT devModes)
+{
+    VBOXDISPIF_WDDM_DISPCFG DispCfg;
+    DWORD winEr;
+    int iPath;
+
+    winEr = vboxDispIfWddmDcCreate(&DispCfg, QDC_ONLY_ACTIVE_PATHS);
+    if (winEr != ERROR_SUCCESS)
+    {
+        WARN(("VBoxTray: (WDDM) Failed vboxDispIfWddmDcCreate\n"));
+        return winEr;
+    }
+
+    iPath = vboxDispIfWddmDcSearchActivePath(&DispCfg, Id, Id);
+
+    if (iPath < 0)
+    {
+        vboxDispIfWddmDcTerm(&DispCfg);
+
+        if (!fEnable)
+        {
+            /* nothing to be done here, just leave */
+            return ERROR_SUCCESS;
+        }
+
+        winEr = vboxDispIfWddmEnableDisplaysTryingTopology(pIf, 1, &Id, fEnable);
+        if (winEr != ERROR_SUCCESS)
+        {
+            WARN(("VBoxTray: (WDDM) Failed vboxDispIfWddmEnableDisplaysTryingTopology winEr %d\n", winEr));
+            return winEr;
+        }
+
+        winEr = vboxDispIfWddmDcCreate(&DispCfg, QDC_ONLY_ACTIVE_PATHS);
+        if (winEr != ERROR_SUCCESS)
+        {
+            WARN(("VBoxTray: (WDDM) Failed vboxDispIfWddmDcCreate winEr %d\n", winEr));
+            return winEr;
+        }
+
+        iPath = vboxDispIfWddmDcSearchPath(&DispCfg, Id, Id);
+        if (iPath < 0)
+        {
+            WARN(("VBoxTray: (WDDM) path (%d) is still disabled, going to retry winEr %d\n", winEr));
+            vboxDispIfWddmDcTerm(&DispCfg);
+            return ERROR_RETRY;
+        }
+    }
+
+    Assert(iPath >= 0);
+
+    if (!fEnable)
+    {
+        /* need to disable it, and we are done */
+        vboxDispIfWddmDcTerm(&DispCfg);
+
+        winEr = vboxDispIfWddmEnableDisplaysTryingTopology(pIf, 1, &Id, fEnable);
+        if (winEr != ERROR_SUCCESS)
+        {
+            WARN(("VBoxTray: (WDDM) Failed vboxDispIfWddmEnableDisplaysTryingTopology winEr %d\n", winEr));
+            return winEr;
+        }
+
+        return winEr;
+    }
+
+    Assert(fEnable);
+
+    winEr = vboxDispIfWddmDcSettingsUpdate(&DispCfg, iPath, &paDeviceMode[Id], FALSE, fEnable);
+    if (winEr != ERROR_SUCCESS)
+    {
+        WARN(("VBoxTray: (WDDM) Failed vboxDispIfWddmDcSettingsUpdate\n"));
+        vboxDispIfWddmDcTerm(&DispCfg);
+        return winEr;
+    }
+
+    UINT fSetFlags = SDC_USE_SUPPLIED_DISPLAY_CONFIG;
+    winEr = vboxDispIfWddmDcSet(&DispCfg, fSetFlags | SDC_VALIDATE);
+    if (winEr != ERROR_SUCCESS)
+    {
+        WARN(("VBoxTray:(WDDM) pfnSetDisplayConfig Failed to validate winEr %d.\n", winEr));
+        fSetFlags |= SDC_ALLOW_CHANGES;
+    }
+
+    winEr = vboxDispIfWddmDcSet(&DispCfg, fSetFlags | SDC_SAVE_TO_DATABASE | SDC_APPLY);
+    if (winEr != ERROR_SUCCESS)
+    {
+        WARN(("VBoxTray:(WDDM) pfnSetDisplayConfig Failed to validate winEr %d.\n", winEr));
+    }
+
+    vboxDispIfWddmDcTerm(&DispCfg);
+
+    return winEr;
 }
 
 #endif /* VBOX_WITH_WDDM */
 
-DWORD VBoxDispIfResizeModes(PCVBOXDISPIF const pIf, UINT iChangedMode, DISPLAY_DEVICE *paDisplayDevices, DEVMODE *paDeviceModes, UINT cDevModes)
+DWORD VBoxDispIfResizeModes(PCVBOXDISPIF const pIf, UINT iChangedMode, BOOL fEnable, BOOL fExtDispSup, DISPLAY_DEVICE *paDisplayDevices, DEVMODE *paDeviceModes, UINT cDevModes)
 {
     switch (pIf->enmMode)
@@ -1515,8 +1656,9 @@
 #ifdef VBOX_WITH_WDDM
         case VBOXDISPIF_MODE_WDDM:
-            return vboxDispIfResizeModesWDDM(pIf, iChangedMode, paDisplayDevices, paDeviceModes, cDevModes);
+        case VBOXDISPIF_MODE_WDDM_W7:
+            return vboxDispIfResizeModesWDDM(pIf, iChangedMode, fEnable, fExtDispSup, paDisplayDevices, paDeviceModes, cDevModes);
 #endif
         default:
-            Log((__FUNCTION__": unknown mode (%d)\n", pIf->enmMode));
+            WARN((__FUNCTION__": unknown mode (%d)\n", pIf->enmMode));
             return ERROR_INVALID_PARAMETER;
     }
@@ -1533,26 +1675,193 @@
 #ifdef VBOX_WITH_WDDM
         case VBOXDISPIF_MODE_WDDM:
+        case VBOXDISPIF_MODE_WDDM_W7:
             return vboxDispIfCancelPendingResizeWDDM(pIf);
 #endif
         default:
-            Log((__FUNCTION__": unknown mode (%d)\n", pIf->enmMode));
+            WARN((__FUNCTION__": unknown mode (%d)\n", pIf->enmMode));
             return ERROR_INVALID_PARAMETER;
     }
 }
 
-DWORD VBoxDispIfReninitModes(PCVBOXDISPIF const pIf, uint8_t *pScreenIdMask, BOOL fReconnectDisplaysOnChange)
+static DWORD vboxDispIfConfigureTargetsWDDM(VBOXDISPIF_OP *pOp, uint32_t *pcConnected)
+{
+    VBOXDISPIFESCAPE EscapeHdr = {0};
+    EscapeHdr.escapeCode = VBOXESC_CONFIGURETARGETS;
+    EscapeHdr.u32CmdSpecific = 0;
+
+    D3DKMT_ESCAPE EscapeData = {0};
+    EscapeData.hAdapter = pOp->Adapter.hAdapter;
+    EscapeData.hDevice = pOp->Device.hDevice;
+    EscapeData.hContext = pOp->Context.hContext;
+    EscapeData.Type = D3DKMT_ESCAPE_DRIVERPRIVATE;
+    EscapeData.Flags.HardwareAccess = 1;
+    EscapeData.pPrivateDriverData = &EscapeHdr;
+    EscapeData.PrivateDriverDataSize = sizeof (EscapeHdr);
+
+    NTSTATUS Status = pOp->pIf->modeData.wddm.KmtCallbacks.pfnD3DKMTEscape(&EscapeData);
+    if (NT_SUCCESS(Status))
+    {
+        if (pcConnected)
+            *pcConnected = EscapeHdr.u32CmdSpecific;
+        return NO_ERROR;
+    }
+    WARN(("VBoxTray: pfnD3DKMTEscape VBOXESC_CONFIGURETARGETS failed Status 0x%x\n", Status));
+    return Status;
+}
+
+static DWORD vboxDispIfResizeStartedWDDMOp(VBOXDISPIF_OP *pOp)
+{
+    DWORD NumDevices = VBoxGetDisplayConfigCount();
+    if (NumDevices == 0)
+    {
+        WARN(("VBoxTray: vboxDispIfResizeStartedWDDMOp: Zero devices found\n"));
+        return ERROR_GEN_FAILURE;
+    }
+
+#ifdef DEBUG_misha
+    {
+        UINT cDcDisplays;
+        DWORD winEr2 = vboxDispIfWddmDcQueryNumDisplays(&cDcDisplays);
+        Assert(cDcDisplays == NumDevices);
+        /* testing */
+        Assert(cDcDisplays == 2);
+    }
+#endif
+    DISPLAY_DEVICE *paDisplayDevices = (DISPLAY_DEVICE *)alloca (sizeof (DISPLAY_DEVICE) * NumDevices);
+    DEVMODE *paDeviceModes = (DEVMODE *)alloca (sizeof (DEVMODE) * NumDevices);
+    DWORD DevNum = 0;
+    DWORD DevPrimaryNum = 0;
+
+    DWORD winEr = VBoxGetDisplayConfig(NumDevices, &DevPrimaryNum, &DevNum, paDisplayDevices, paDeviceModes);
+    if (winEr != NO_ERROR)
+    {
+        WARN(("VBoxTray: vboxDispIfResizeStartedWDDMOp: VBoxGetDisplayConfig failed, %d\n", winEr));
+        return winEr;
+    }
+
+    if (NumDevices != DevNum)
+        WARN(("VBoxTray: vboxDispIfResizeStartedWDDMOp: NumDevices(%d) != DevNum(%d)\n", NumDevices, DevNum));
+
+
+    uint32_t cConnected = 0;
+    winEr = vboxDispIfConfigureTargetsWDDM(pOp, &cConnected);
+    if (winEr != NO_ERROR)
+    {
+        WARN(("VBoxTray: vboxDispIfConfigureTargetsWDDM failed winEr 0x%x\n", winEr));
+        return winEr;
+    }
+
+    if (!cConnected)
+    {
+        Log(("VBoxTray: all targets already connected, nothing to do\n"));
+        return NO_ERROR;
+    }
+
+    winEr = vboxDispIfWaitDisplayDataInited(pOp, NULL);
+    if (winEr != NO_ERROR)
+        WARN(("VBoxTray: vboxDispIfResizeStartedWDDMOp: vboxDispIfWaitDisplayDataInited failed winEr 0x%x\n", winEr));
+
+    DWORD NewNumDevices = VBoxGetDisplayConfigCount();
+    if (NewNumDevices == 0)
+    {
+        WARN(("VBoxTray: vboxDispIfResizeStartedWDDMOp: Zero devices found\n"));
+        return ERROR_GEN_FAILURE;
+    }
+
+    if (NewNumDevices != NumDevices)
+        WARN(("VBoxTray: vboxDispIfResizeStartedWDDMOp: NumDevices(%d) != NewNumDevices(%d)\n", NumDevices, NewNumDevices));
+
+    DISPLAY_DEVICE *paNewDisplayDevices = (DISPLAY_DEVICE *)alloca (sizeof (DISPLAY_DEVICE) * NewNumDevices);
+    DEVMODE *paNewDeviceModes = (DEVMODE *)alloca (sizeof (DEVMODE) * NewNumDevices);
+    DWORD NewDevNum = 0;
+    DWORD NewDevPrimaryNum = 0;
+
+    winEr = VBoxGetDisplayConfig(NewNumDevices, &NewDevPrimaryNum, &NewDevNum, paNewDisplayDevices, paNewDeviceModes);
+    if (winEr != NO_ERROR)
+    {
+        WARN(("VBoxTray: vboxDispIfResizeStartedWDDMOp: VBoxGetDisplayConfig failed for new devices, %d\n", winEr));
+        return winEr;
+    }
+
+    if (NewNumDevices != NewDevNum)
+        WARN(("VBoxTray: vboxDispIfResizeStartedWDDMOp: NewNumDevices(%d) != NewDevNum(%d)\n", NewNumDevices, NewDevNum));
+
+    DWORD minDevNum = RT_MIN(DevNum, NewDevNum);
+    UINT *pIds = (UINT*)alloca (sizeof (UINT) * minDevNum);
+    UINT cIds = 0;
+    for (DWORD i = 0; i < minDevNum; ++i)
+    {
+        if ((paNewDisplayDevices[i].StateFlags & DISPLAY_DEVICE_ACTIVE)
+                && !(paDisplayDevices[i].StateFlags & DISPLAY_DEVICE_ACTIVE))
+        {
+            pIds[cIds] = i;
+            ++cIds;
+        }
+    }
+
+    if (!cIds)
+    {
+        /* this is something we would not regularly expect */
+        WARN(("VBoxTray: all targets already have proper config, nothing to do\n"));
+        return NO_ERROR;
+    }
+
+    if (pOp->pIf->enmMode > VBOXDISPIF_MODE_WDDM)
+    {
+        winEr = vboxDispIfWddmEnableDisplaysTryingTopology(pOp->pIf, cIds, pIds, FALSE);
+        if (winEr != NO_ERROR)
+            WARN(("VBoxTray: vboxDispIfWddmEnableDisplaysTryingTopology failed to record current settings, %d, ignoring\n", winEr));
+    }
+    else
+    {
+        for (DWORD i = 0; i < cIds; ++i)
+        {
+            winEr = EnableAndResizeDispDev(paNewDeviceModes, paNewDisplayDevices, NewDevNum, i, 0, 0, 0, 0, 0, FALSE, TRUE);
+            if (winEr != NO_ERROR)
+                WARN(("VBoxTray: vboxDispIfResizeStartedWDDMOp: EnableAndResizeDispDev failed winEr 0x%x\n", winEr));
+        }
+    }
+
+    return winEr;
+}
+
+
+static DWORD vboxDispIfResizeStartedWDDM(PCVBOXDISPIF const pIf)
+{
+    VBOXDISPIF_OP Op;
+
+    DWORD winEr = vboxDispIfOpBegin(pIf, &Op);
+    if (winEr != NO_ERROR)
+    {
+        WARN(("VBoxTray: vboxDispIfOpBegin failed winEr 0x%x\n", winEr));
+        return winEr;
+    }
+
+    winEr = vboxDispIfResizeStartedWDDMOp(&Op);
+    if (winEr != NO_ERROR)
+    {
+        WARN(("VBoxTray: vboxDispIfResizeStartedWDDMOp failed winEr 0x%x\n", winEr));
+    }
+
+    vboxDispIfOpEnd(&Op);
+
+    return winEr;
+}
+
+DWORD VBoxDispIfResizeStarted(PCVBOXDISPIF const pIf)
 {
     switch (pIf->enmMode)
     {
         case VBOXDISPIF_MODE_XPDM_NT4:
-            return ERROR_NOT_SUPPORTED;
+            return NO_ERROR;
         case VBOXDISPIF_MODE_XPDM:
-            return ERROR_NOT_SUPPORTED;
+            return NO_ERROR;
 #ifdef VBOX_WITH_WDDM
         case VBOXDISPIF_MODE_WDDM:
-            return vboxDispIfReninitModesWDDM(pIf, pScreenIdMask, fReconnectDisplaysOnChange);
+        case VBOXDISPIF_MODE_WDDM_W7:
+            return vboxDispIfResizeStartedWDDM(pIf);
 #endif
         default:
-            Log((__FUNCTION__": unknown mode (%d)\n", pIf->enmMode));
+            WARN((__FUNCTION__": unknown mode (%d)\n", pIf->enmMode));
             return ERROR_INVALID_PARAMETER;
     }
@@ -1583,5 +1892,5 @@
             if (!bSupported)
             {
-                Log((__FUNCTION__": pfnChangeDisplaySettingsEx function pointer failed to initialize\n"));
+                WARN((__FUNCTION__": pfnChangeDisplaySettingsEx function pointer failed to initialize\n"));
                 err = ERROR_NOT_SUPPORTED;
             }
@@ -1589,5 +1898,5 @@
         else
         {
-            Log((__FUNCTION__": failed to get user32 handle, err (%d)\n", GetLastError()));
+            WARN((__FUNCTION__": failed to get USER32 handle, err (%d)\n", GetLastError()));
             err = ERROR_NOT_SUPPORTED;
         }
@@ -1595,5 +1904,5 @@
     else
     {
-        Log((__FUNCTION__": can not switch to VBOXDISPIF_MODE_XPDM, because os is not >= w2k\n"));
+        WARN((__FUNCTION__": can not switch to VBOXDISPIF_MODE_XPDM, because os is not >= w2k\n"));
         err = ERROR_NOT_SUPPORTED;
     }
@@ -1613,7 +1922,9 @@
 
 #ifdef VBOX_WITH_WDDM
-    if (pIf->enmMode == VBOXDISPIF_MODE_WDDM)
+    if (pIf->enmMode >= VBOXDISPIF_MODE_WDDM)
     {
         vboxDispIfWddmTerm(pIf);
+
+        vboxDispKmtCallbacksTerm(&pIf->modeData.wddm.KmtCallbacks);
     }
 #endif
@@ -1631,5 +1942,5 @@
             }
             else
-                Log((__FUNCTION__": failed to switch to XPDM_NT4 mode, err (%d)\n", err));
+                WARN((__FUNCTION__": failed to switch to XPDM_NT4 mode, err (%d)\n", err));
             break;
         case VBOXDISPIF_MODE_XPDM:
@@ -1642,5 +1953,5 @@
             }
             else
-                Log((__FUNCTION__": failed to switch to XPDM mode, err (%d)\n", err));
+                WARN((__FUNCTION__": failed to switch to XPDM mode, err (%d)\n", err));
             break;
 #ifdef VBOX_WITH_WDDM
@@ -1655,5 +1966,18 @@
             }
             else
-                Log((__FUNCTION__": failed to switch to WDDM mode, err (%d)\n", err));
+                WARN((__FUNCTION__": failed to switch to WDDM mode, err (%d)\n", err));
+            break;
+        }
+        case VBOXDISPIF_MODE_WDDM_W7:
+        {
+            Log((__FUNCTION__": request to switch to VBOXDISPIF_MODE_WDDM_W7\n"));
+            err = vboxDispIfSwitchToWDDM_W7(pIf);
+            if (err == NO_ERROR)
+            {
+                Log((__FUNCTION__": successfully switched to WDDM mode\n"));
+                pIf->enmMode = VBOXDISPIF_MODE_WDDM_W7;
+            }
+            else
+                WARN((__FUNCTION__": failed to switch to WDDM mode, err (%d)\n", err));
             break;
         }
@@ -1665,2 +1989,131 @@
     return err;
 }
+
+static DWORD vboxDispIfSeamlesCreateWDDM(PCVBOXDISPIF const pIf, VBOXDISPIF_SEAMLESS *pSeamless, HANDLE hEvent)
+{
+    HRESULT hr = vboxDispKmtOpenAdapter(&pIf->modeData.wddm.KmtCallbacks, &pSeamless->modeData.wddm.Adapter);
+    if (SUCCEEDED(hr))
+    {
+        hr = vboxDispKmtCreateDevice(&pSeamless->modeData.wddm.Adapter, &pSeamless->modeData.wddm.Device);
+        if (SUCCEEDED(hr))
+        {
+            hr = vboxDispKmtCreateContext(&pSeamless->modeData.wddm.Device, &pSeamless->modeData.wddm.Context, VBOXWDDM_CONTEXT_TYPE_CUSTOM_DISPIF_SEAMLESS,
+                    0, 0, hEvent, 0ULL);
+            if (SUCCEEDED(hr))
+                return ERROR_SUCCESS;
+            else
+                WARN(("VBoxTray: vboxDispKmtCreateContext failed hr 0x%x", hr));
+
+            vboxDispKmtDestroyDevice(&pSeamless->modeData.wddm.Device);
+        }
+        else
+            WARN(("VBoxTray: vboxDispKmtCreateDevice failed hr 0x%x", hr));
+
+        vboxDispKmtCloseAdapter(&pSeamless->modeData.wddm.Adapter);
+    }
+
+    return hr;
+}
+
+static DWORD vboxDispIfSeamlesTermWDDM(VBOXDISPIF_SEAMLESS *pSeamless)
+{
+    vboxDispKmtDestroyContext(&pSeamless->modeData.wddm.Context);
+    vboxDispKmtDestroyDevice(&pSeamless->modeData.wddm.Device);
+    vboxDispKmtCloseAdapter(&pSeamless->modeData.wddm.Adapter);
+
+    return NO_ERROR;
+}
+
+static DWORD vboxDispIfSeamlesSubmitWDDM(VBOXDISPIF_SEAMLESS *pSeamless, VBOXDISPIFESCAPE *pData, int cbData)
+{
+    D3DKMT_ESCAPE EscapeData = {0};
+    EscapeData.hAdapter = pSeamless->modeData.wddm.Adapter.hAdapter;
+    EscapeData.hDevice = pSeamless->modeData.wddm.Device.hDevice;
+    EscapeData.hContext = pSeamless->modeData.wddm.Context.hContext;
+    EscapeData.Type = D3DKMT_ESCAPE_DRIVERPRIVATE;
+    EscapeData.Flags.HardwareAccess = 1;
+    EscapeData.pPrivateDriverData = pData;
+    EscapeData.PrivateDriverDataSize = VBOXDISPIFESCAPE_SIZE(cbData);
+
+    NTSTATUS Status = pSeamless->pIf->modeData.wddm.KmtCallbacks.pfnD3DKMTEscape(&EscapeData);
+    if (NT_SUCCESS(Status))
+        return ERROR_SUCCESS;
+
+    WARN(("VBoxTray: pfnD3DKMTEscape Seamless failed Status 0x%x\n", Status));
+    return Status;
+}
+
+DWORD VBoxDispIfSeamlesCreate(PCVBOXDISPIF const pIf, VBOXDISPIF_SEAMLESS *pSeamless, HANDLE hEvent)
+{
+    memset(pSeamless, 0, sizeof (*pSeamless));
+    pSeamless->pIf = pIf;
+
+    switch (pIf->enmMode)
+    {
+        case VBOXDISPIF_MODE_XPDM_NT4:
+        case VBOXDISPIF_MODE_XPDM:
+            return NO_ERROR;
+#ifdef VBOX_WITH_WDDM
+        case VBOXDISPIF_MODE_WDDM:
+        case VBOXDISPIF_MODE_WDDM_W7:
+            return vboxDispIfSeamlesCreateWDDM(pIf, pSeamless, hEvent);
+#endif
+        default:
+            WARN(("VBoxTray: VBoxDispIfSeamlesCreate: invalid mode %d\n", pIf->enmMode));
+            return ERROR_INVALID_PARAMETER;
+    }
+}
+
+DWORD VBoxDispIfSeamlesTerm(VBOXDISPIF_SEAMLESS *pSeamless)
+{
+    PCVBOXDISPIF const pIf = pSeamless->pIf;
+    DWORD winEr;
+    switch (pIf->enmMode)
+    {
+        case VBOXDISPIF_MODE_XPDM_NT4:
+        case VBOXDISPIF_MODE_XPDM:
+            winEr = NO_ERROR;
+            break;
+#ifdef VBOX_WITH_WDDM
+        case VBOXDISPIF_MODE_WDDM:
+        case VBOXDISPIF_MODE_WDDM_W7:
+            winEr = vboxDispIfSeamlesTermWDDM(pSeamless);
+            break;
+#endif
+        default:
+            WARN(("VBoxTray: VBoxDispIfSeamlesTerm: invalid mode %d\n", pIf->enmMode));
+            winEr = ERROR_INVALID_PARAMETER;
+            break;
+    }
+
+    if (winEr == NO_ERROR)
+        memset(pSeamless, 0, sizeof (*pSeamless));
+
+    return winEr;
+}
+
+DWORD VBoxDispIfSeamlesSubmit(VBOXDISPIF_SEAMLESS *pSeamless, VBOXDISPIFESCAPE *pData, int cbData)
+{
+    PCVBOXDISPIF const pIf = pSeamless->pIf;
+
+    if (pData->escapeCode != VBOXESC_SETVISIBLEREGION)
+    {
+        WARN(("VBoxTray: invalid escape code for Seamless submit %d\n", pData->escapeCode));
+        return ERROR_INVALID_PARAMETER;
+    }
+
+    switch (pIf->enmMode)
+    {
+        case VBOXDISPIF_MODE_XPDM_NT4:
+        case VBOXDISPIF_MODE_XPDM:
+            return VBoxDispIfEscape(pIf, pData, cbData);
+#ifdef VBOX_WITH_WDDM
+        case VBOXDISPIF_MODE_WDDM:
+        case VBOXDISPIF_MODE_WDDM_W7:
+            return vboxDispIfSeamlesSubmitWDDM(pSeamless, pData, cbData);
+#endif
+        default:
+            WARN(("VBoxTray: VBoxDispIfSeamlesSubmit: invalid mode %d\n", pIf->enmMode));
+            return ERROR_INVALID_PARAMETER;
+    }
+}
Index: trunk/src/VBox/Additions/WINNT/VBoxTray/VBoxDispIf.h
===================================================================
--- trunk/src/VBox/Additions/WINNT/VBoxTray/VBoxDispIf.h	(revision 48058)
+++ trunk/src/VBox/Additions/WINNT/VBoxTray/VBoxDispIf.h	(revision 48070)
@@ -19,4 +19,5 @@
 # define D3DKMDT_SPECIAL_MULTIPLATFORM_TOOL
 # include <d3dkmthk.h>
+# include "../Graphics/Video/disp/wddm/VBoxDispKmt.h"
 #endif
 
@@ -30,4 +31,5 @@
 #ifdef VBOX_WITH_WDDM
     , VBOXDISPIF_MODE_WDDM
+    , VBOXDISPIF_MODE_WDDM_W7
 #endif
 } VBOXDISPIF_MODE;
@@ -59,14 +61,5 @@
             BOOL (WINAPI * pfnEnumDisplayDevices)(IN LPCSTR lpDevice, IN DWORD iDevNum, OUT PDISPLAY_DEVICEA lpDisplayDevice, IN DWORD dwFlags);
 
-            /* open adapter */
-            PFND3DKMT_OPENADAPTERFROMHDC pfnD3DKMTOpenAdapterFromHdc;
-            PFND3DKMT_OPENADAPTERFROMGDIDISPLAYNAME pfnD3DKMTOpenAdapterFromGdiDisplayName;
-            /* close adapter */
-            PFND3DKMT_CLOSEADAPTER pfnD3DKMTCloseAdapter;
-            /* escape */
-            PFND3DKMT_ESCAPE pfnD3DKMTEscape;
-            /* auto resize support */
-            PFND3DKMT_INVALIDATEACTIVEVIDPN pfnD3DKMTInvalidateActiveVidPn;
-            PFND3DKMT_POLLDISPLAYCHILDREN pfnD3DKMTPollDisplayChildren;
+            VBOXDISPKMT_CALLBACKS KmtCallbacks;
         } wddm;
 #endif
@@ -84,8 +77,33 @@
 DWORD VBoxDispIfEscape(PCVBOXDISPIF const pIf, PVBOXDISPIFESCAPE pEscape, int cbData);
 DWORD VBoxDispIfEscapeInOut(PCVBOXDISPIF const pIf, PVBOXDISPIFESCAPE pEscape, int cbData);
-DWORD VBoxDispIfResize(PCVBOXDISPIF const pIf, ULONG Id, DWORD Width, DWORD Height, DWORD BitsPerPixel);
-DWORD VBoxDispIfResizeModes(PCVBOXDISPIF const pIf, UINT iChangedMode, DISPLAY_DEVICE *paDisplayDevices, DEVMODE *paDeviceModes, UINT cDevModes);
+DWORD VBoxDispIfResizeModes(PCVBOXDISPIF const pIf, UINT iChangedMode, BOOL fEnable, BOOL fExtDispSup, DISPLAY_DEVICE *paDisplayDevices, DEVMODE *paDeviceModes, UINT cDevModes);
 DWORD VBoxDispIfCancelPendingResize(PCVBOXDISPIF const pIf);
-DWORD vboxDispIfWddmEnableDisplay(PCVBOXDISPIF const pIf, UINT Id, bool fEnabled);
-DWORD vboxDispIfWddmResizeDisplay(PCVBOXDISPIF const pIf, UINT Id, DISPLAY_DEVICE * paDisplayDevices, DEVMODE *paDeviceMode, UINT devModes);
-//DWORD VBoxDispIfReninitModes(PCVBOXDISPIF const pIf, uint8_t *pScreenIdMask, BOOL fReconnectDisplaysOnChange);
+
+DWORD VBoxDispIfResizeStarted(PCVBOXDISPIF const pIf);
+
+
+typedef struct VBOXDISPIF_SEAMLESS
+{
+    PCVBOXDISPIF pIf;
+
+    union
+    {
+#ifdef VBOX_WITH_WDDM
+        struct
+        {
+            VBOXDISPKMT_ADAPTER Adapter;
+            VBOXDISPKMT_DEVICE Device;
+            VBOXDISPKMT_CONTEXT Context;
+        } wddm;
+#endif
+    } modeData;
+} VBOXDISPIF_SEAMLESS;
+
+DECLINLINE(bool) VBoxDispIfSeamlesIsValid(VBOXDISPIF_SEAMLESS *pSeamless)
+{
+    return !!pSeamless->pIf;
+}
+
+DWORD VBoxDispIfSeamlesCreate(PCVBOXDISPIF const pIf, VBOXDISPIF_SEAMLESS *pSeamless, HANDLE hEvent);
+DWORD VBoxDispIfSeamlesTerm(VBOXDISPIF_SEAMLESS *pSeamless);
+DWORD VBoxDispIfSeamlesSubmit(VBOXDISPIF_SEAMLESS *pSeamless, VBOXDISPIFESCAPE *pData, int cbData);
Index: trunk/src/VBox/Additions/WINNT/VBoxTray/VBoxDisplay.cpp
===================================================================
--- trunk/src/VBox/Additions/WINNT/VBoxTray/VBoxDisplay.cpp	(revision 48058)
+++ trunk/src/VBox/Additions/WINNT/VBoxTray/VBoxDisplay.cpp	(revision 48070)
@@ -90,5 +90,6 @@
                 Log(("VBoxTray: VBoxDisplayInit: WDDM driver is installed, switching display driver if to WDDM mode\n"));
                 /* this is hacky, but the most easiest way */
-                DWORD err = VBoxDispIfSwitchMode(const_cast<PVBOXDISPIF>(&pEnv->dispIf), VBOXDISPIF_MODE_WDDM, NULL /* old mode, we don't care about it */);
+                VBOXDISPIF_MODE enmMode = (OSinfo.dwMajorVersion > 6 || OSinfo.dwMinorVersion > 0) ? VBOXDISPIF_MODE_WDDM_W7 : VBOXDISPIF_MODE_WDDM;
+                DWORD err = VBoxDispIfSwitchMode(const_cast<PVBOXDISPIF>(&pEnv->dispIf), enmMode, NULL /* old mode, we don't care about it */);
                 if (err == NO_ERROR)
                     Log(("VBoxTray: VBoxDisplayInit: DispIf switched to WDDM mode successfully\n"));
@@ -213,6 +214,6 @@
 }
 
-static DWORD EnableAndResizeDispDev(DEVMODE *paDeviceModes, DISPLAY_DEVICE *paDisplayDevices, DWORD totalDispNum, UINT Id, DWORD aWidth, DWORD aHeight,
-                                    DWORD aBitsPerPixel, DWORD aPosX, DWORD aPosY, BOOL fEnabled, BOOL fExtDispSup, VBOXDISPLAYCONTEXT *pCtx)
+DWORD EnableAndResizeDispDev(DEVMODE *paDeviceModes, DISPLAY_DEVICE *paDisplayDevices, DWORD totalDispNum, UINT Id, DWORD aWidth, DWORD aHeight,
+                                    DWORD aBitsPerPixel, DWORD aPosX, DWORD aPosY, BOOL fEnabled, BOOL fExtDispSup)
 {
     DISPLAY_DEVICE displayDeviceTmp;
@@ -307,30 +308,12 @@
     }
     return dwStatus;
- }
-
-/* Returns TRUE to try again. */
-static BOOL ResizeDisplayDevice(UINT Id, DWORD Width, DWORD Height, DWORD BitsPerPixel,
-                                BOOL fEnabled, DWORD dwNewPosX, DWORD dwNewPosY,
-                                VBOXDISPLAYCONTEXT *pCtx, BOOL fExtDispSup)
+}
+
+DWORD VBoxGetDisplayConfigCount()
 {
-    BOOL fDispAlreadyEnabled = false; /* check whether the monitor with ID is already enabled. */
-    BOOL fModeReset = (Width == 0 && Height == 0 && BitsPerPixel == 0 &&
-                       dwNewPosX == 0 && dwNewPosY == 0);
-    BOOL fChangePosRequest = false; /* change in position requested */
-
-    Log(("VBoxTray: ResizeDisplayDevice Width= %d, Height=%d , PosX=%d and PosY=%d \
-         fEnabled = %d, fExtDisSup = %d\n",
-          Width, Height, dwNewPosX, dwNewPosY, fEnabled, fExtDispSup));
-
-    if (!gCtx.fAnyX)
-        Width &= 0xFFF8;
-
     DISPLAY_DEVICE DisplayDevice;
-    DWORD dwStatus;
 
     ZeroMemory(&DisplayDevice, sizeof(DISPLAY_DEVICE));
     DisplayDevice.cb = sizeof(DISPLAY_DEVICE);
-
-    VBoxDispIfCancelPendingResize(&pCtx->pEnv->dispIf);
 
     /* Find out how many display devices the system has */
@@ -358,24 +341,19 @@
     }
 
-    Log(("VBoxTray: ResizeDisplayDevice: Found total %d devices. err %d\n", NumDevices, GetLastError ()));
-
-    if (NumDevices == 0 || Id >= NumDevices)
-    {
-        Log(("VBoxTray: ResizeDisplayDevice: Requested identifier %d is invalid. err %d\n", Id, GetLastError ()));
-        return FALSE;
-    }
-
-    DISPLAY_DEVICE *paDisplayDevices = (DISPLAY_DEVICE *)alloca (sizeof (DISPLAY_DEVICE) * NumDevices);
-    DEVMODE *paDeviceModes = (DEVMODE *)alloca (sizeof (DEVMODE) * NumDevices);
-    RECTL *paRects = (RECTL *)alloca (sizeof (RECTL) * NumDevices);
-
+    return NumDevices;
+}
+
+DWORD VBoxGetDisplayConfig(const DWORD NumDevices, DWORD *pDevPrimaryNum, DWORD *pNumDevices, DISPLAY_DEVICE *paDisplayDevices, DEVMODE *paDeviceModes)
+{
     /* Fetch information about current devices and modes. */
     DWORD DevNum = 0;
     DWORD DevPrimaryNum = 0;
 
+    DISPLAY_DEVICE DisplayDevice;
+
     ZeroMemory(&DisplayDevice, sizeof(DISPLAY_DEVICE));
     DisplayDevice.cb = sizeof(DISPLAY_DEVICE);
 
-    i = 0;
+    DWORD i = 0;
     while (EnumDisplayDevices (NULL, i, &DisplayDevice, 0))
     {
@@ -401,6 +379,6 @@
             if (DevNum >= NumDevices)
             {
-                Log(("VBoxTray: ResizeDisplayDevice: %d >= %d\n", NumDevices, DevNum));
-                return FALSE;
+                WARN(("VBoxTray: ResizeDisplayDevice: %d >= %d\n", NumDevices, DevNum));
+                return ERROR_BUFFER_OVERFLOW;
             }
 
@@ -438,50 +416,5 @@
             }
 
-            if (fExtDispSup)
-            {
-                LogRel(("VBoxTray: Extended Display Support.\n"));
-                Log(("VBoxTray: ResizeDisplayDevice1: %dx%dx%d at %d,%d . Id = %d and DevNum=%d, fEnabled=%d\n",
-                      paDeviceModes[Id].dmPelsWidth,
-                      paDeviceModes[Id].dmPelsHeight,
-                      paDeviceModes[Id].dmBitsPerPel,
-                      paDeviceModes[Id].dmPosition.x,
-                      paDeviceModes[Id].dmPosition.y,
-                      Id, DevNum, fEnabled));
-                if ((DevNum == Id && fEnabled == 1))
-                {
-                    /* Calculation of new position for enabled
-                     * secondary monitor .
-                     */
-                    /* Used when a secondary monitor just needs to be enabled, without any
-                     * change in its position
-                     */
-                     if (dwNewPosX != 0)
-                    {
-                        LogRel(("VBoxTray: Setting Rectangle position x=%d*y=%d\n", dwNewPosX, dwNewPosY));
-                        paDeviceModes[DevNum].dmPosition.x = dwNewPosX;
-                        paDeviceModes[DevNum].dmPosition.y = dwNewPosY;
-                        fChangePosRequest = true;
-                    }
-                    paRects[DevNum].left   = paDeviceModes[DevNum].dmPosition.x;
-                    paRects[DevNum].top    = paDeviceModes[DevNum].dmPosition.y;
-                    paRects[DevNum].right  = paDeviceModes[DevNum].dmPosition.x + paDeviceModes[DevNum].dmPelsWidth;
-                    paRects[DevNum].bottom = paDeviceModes[DevNum].dmPosition.y + paDeviceModes[DevNum].dmPelsHeight;
-                }
-                else
-                {
-                    paRects[DevNum].left   = paDeviceModes[DevNum].dmPosition.x;
-                    paRects[DevNum].top    = paDeviceModes[DevNum].dmPosition.y;
-                    paRects[DevNum].right  = paDeviceModes[DevNum].dmPosition.x + paDeviceModes[DevNum].dmPelsWidth;
-                    paRects[DevNum].bottom = paDeviceModes[DevNum].dmPosition.y + paDeviceModes[DevNum].dmPelsHeight;
-                }
-            }
-            else
-            {
-                    LogRel(("VBoxTray: NO Ext Display Support \n"));
-                    paRects[DevNum].left   = paDeviceModes[DevNum].dmPosition.x;
-                    paRects[DevNum].top    = paDeviceModes[DevNum].dmPosition.y;
-                    paRects[DevNum].right  = paDeviceModes[DevNum].dmPosition.x + paDeviceModes[DevNum].dmPelsWidth;
-                    paRects[DevNum].bottom = paDeviceModes[DevNum].dmPosition.y + paDeviceModes[DevNum].dmPelsHeight;
-            }
+
             DevNum++;
         }
@@ -491,4 +424,80 @@
         i++;
     }
+
+    *pNumDevices = DevNum;
+
+    return NO_ERROR;
+}
+
+/* Returns TRUE to try again. */
+static BOOL ResizeDisplayDevice(UINT Id, DWORD Width, DWORD Height, DWORD BitsPerPixel,
+                                BOOL fEnabled, DWORD dwNewPosX, DWORD dwNewPosY,
+                                VBOXDISPLAYCONTEXT *pCtx, BOOL fExtDispSup)
+{
+    BOOL fDispAlreadyEnabled = false; /* check whether the monitor with ID is already enabled. */
+    BOOL fModeReset = (Width == 0 && Height == 0 && BitsPerPixel == 0 &&
+                       dwNewPosX == 0 && dwNewPosY == 0);
+    DWORD dmFields = 0;
+
+    Log(("VBoxTray: ResizeDisplayDevice Width= %d, Height=%d , PosX=%d and PosY=%d \
+         fEnabled = %d, fExtDisSup = %d\n",
+          Width, Height, dwNewPosX, dwNewPosY, fEnabled, fExtDispSup));
+
+    if (!gCtx.fAnyX)
+        Width &= 0xFFF8;
+
+    VBoxDispIfCancelPendingResize(&pCtx->pEnv->dispIf);
+
+    DWORD NumDevices = VBoxGetDisplayConfigCount();
+
+    if (NumDevices == 0 || Id >= NumDevices)
+    {
+        WARN(("VBoxTray: ResizeDisplayDevice: Requested identifier %d is invalid. err %d\n", Id, GetLastError ()));
+        return FALSE;
+    }
+
+    Log(("VBoxTray: ResizeDisplayDevice: Found total %d devices. err %d\n", NumDevices, GetLastError ()));
+
+    DISPLAY_DEVICE *paDisplayDevices = (DISPLAY_DEVICE *)alloca (sizeof (DISPLAY_DEVICE) * NumDevices);
+    DEVMODE *paDeviceModes = (DEVMODE *)alloca (sizeof (DEVMODE) * NumDevices);
+    RECTL *paRects = (RECTL *)alloca (sizeof (RECTL) * NumDevices);
+    DWORD DevNum = 0;
+    DWORD DevPrimaryNum = 0;
+    DWORD dwStatus = VBoxGetDisplayConfig(NumDevices, &DevPrimaryNum, &DevNum, paDisplayDevices, paDeviceModes);
+    if (dwStatus != NO_ERROR)
+    {
+        WARN(("VBoxTray: ResizeDisplayDevice: VBoxGetDisplayConfig failed, %d\n", dwStatus));
+        return dwStatus;
+    }
+
+    if (NumDevices != DevNum)
+        WARN(("VBoxTray: ResizeDisplayDevice: NumDevices(%d) != DevNum(%d)\n", NumDevices, DevNum));
+
+    DWORD i = 0;
+
+    for (i = 0; i < DevNum; ++i)
+    {
+        if (fExtDispSup)
+        {
+            LogRel(("VBoxTray: Extended Display Support.\n"));
+            Log(("VBoxTray: ResizeDisplayDevice1: %dx%dx%d at %d,%d . Id = %d and DevNum=%d, fEnabled=%d\n",
+                  paDeviceModes[Id].dmPelsWidth,
+                  paDeviceModes[Id].dmPelsHeight,
+                  paDeviceModes[Id].dmBitsPerPel,
+                  paDeviceModes[Id].dmPosition.x,
+                  paDeviceModes[Id].dmPosition.y,
+                  Id, DevNum, fEnabled));
+        }
+        else
+        {
+            LogRel(("VBoxTray: NO Ext Display Support \n"));
+        }
+
+        paRects[i].left   = paDeviceModes[i].dmPosition.x;
+        paRects[i].top    = paDeviceModes[i].dmPosition.y;
+        paRects[i].right  = paDeviceModes[i].dmPosition.x + paDeviceModes[i].dmPelsWidth;
+        paRects[i].bottom = paDeviceModes[i].dmPosition.y + paDeviceModes[i].dmPelsHeight;
+    }
+
     /* Keep a record if the display with ID is already active or not. */
     if (paDisplayDevices[Id].StateFlags & DISPLAY_DEVICE_ACTIVE)
@@ -504,12 +513,26 @@
      */
     if (Width == 0)
-    {
         Width = paRects[Id].right - paRects[Id].left;
-    }
+    else
+        dmFields |= DM_PELSWIDTH;
 
     if (Height == 0)
-    {
         Height = paRects[Id].bottom - paRects[Id].top;
-    }
+    else
+        dmFields |= DM_PELSHEIGHT;
+
+    if (BitsPerPixel == 0)
+        BitsPerPixel = paDeviceModes[Id].dmBitsPerPel;
+    else
+        dmFields |= DM_BITSPERPEL;
+
+    if (!dwNewPosX && !dwNewPosY)
+    {
+        /* @fixme: zero position is a valid state, so another values should be used as a special case !!! */
+        dwNewPosX = paRects[Id].left;
+        dwNewPosY = paRects[Id].top;
+    }
+    else
+        dmFields |= DM_POSITION;
 
     /* Check whether a mode reset or a change is requested.
@@ -529,5 +552,7 @@
      * all rect conditions are true. Thus in this case nothing has to be done.
      */
-    if ( !fModeReset && fEnabled && fDispAlreadyEnabled && !fChangePosRequest
+    if ( !fModeReset && (!fEnabled == !fDispAlreadyEnabled)
+        && paRects[Id].left == dwNewPosX
+        && paRects[Id].top == dwNewPosY
         && paRects[Id].right - paRects[Id].left == Width
         && paRects[Id].bottom - paRects[Id].top == Height
@@ -538,5 +563,6 @@
     }
 
-    hlpResizeRect(paRects, NumDevices, DevPrimaryNum, Id, Width, Height);
+    hlpResizeRect(paRects, NumDevices, DevPrimaryNum, Id,
+            fEnabled ? Width : 0, fEnabled ? Height : 0, dwNewPosX, dwNewPosY);
 #ifdef Log
     for (i = 0; i < NumDevices; i++)
@@ -561,27 +587,17 @@
             paDeviceModes[i].dmPelsHeight = paRects[i].bottom - paRects[i].top;
 
+            if (i == Id)
+                paDeviceModes[i].dmBitsPerPel = BitsPerPixel;
+
+            paDeviceModes[i].dmFields |= dmFields;
+
             /* On Vista one must specify DM_BITSPERPEL.
              * Note that the current mode dmBitsPerPel is already in the DEVMODE structure.
              */
-            paDeviceModes[i].dmFields = DM_PELSHEIGHT | DM_PELSWIDTH | DM_BITSPERPEL;
-
-            if (i == Id && BitsPerPixel != 0)
+            if (!(paDeviceModes[i].dmFields & DM_BITSPERPEL))
             {
-                LogRel(("VBoxTray: (WDDM)Changing resolution and position. \n"));
-                /* Change dmBitsPerPel if requested. */
-                paDeviceModes[i].dmBitsPerPel = BitsPerPixel;
-                paDeviceModes[i].dmPelsWidth = Width;
-                paDeviceModes[i].dmPelsHeight = Height;
-                if (dwNewPosX != 0 || dwNewPosY != 0)
-                {
-                    paDeviceModes[Id].dmPosition.x = dwNewPosX;
-                    paDeviceModes[Id].dmPosition.y = dwNewPosY;
-                }
-                else
-                {
-                    paDeviceModes[i].dmFields |= DM_POSITION;
-                    paDeviceModes[Id].dmPosition.x = 0;
-                    paDeviceModes[Id].dmPosition.y = 0;
-                }
+                WARN(("VBoxTray: (WDDM) no DM_BITSPERPEL\n"));
+                paDeviceModes[i].dmFields |= DM_BITSPERPEL;
+                paDeviceModes[i].dmBitsPerPel = 32;
             }
 
@@ -593,53 +609,17 @@
                   paDeviceModes[i].dmPosition.x,
                   paDeviceModes[i].dmPosition.y));
-
-        }
-        /* Reques to enable /disable the secondary Display Device. Won't take the resize request now.*/
-        if (!fDispAlreadyEnabled && fEnabled || fDispAlreadyEnabled && !fEnabled)
-        {
-              OSVERSIONINFO OSinfo;
-              OSinfo.dwOSVersionInfoSize = sizeof (OSinfo);
-              GetVersionEx (&OSinfo);
-
-              /* for win 7 and above */
-              if (OSinfo.dwMajorVersion >= 6 && OSinfo.dwMinorVersion >= 1)
-              {
-                  LogRel(("VBoxTray: (WDDM) Request to enable/disable %d display device\n", fEnabled));
-                  DWORD dwStatus = vboxDispIfWddmEnableDisplay(&pCtx->pEnv->dispIf, Id, RT_BOOL(fEnabled));
-                  if(dwStatus != ERROR_SUCCESS)
-                  {
-                      /* Not going to retry for enabling or disabling of the secondary display device.*/
-                      LogRel(("VBoxTray: (WDDM) Failed to enable the Display Device \n"));
-                  }
-              }
-              else /* case: vista in wddm mode. SetDisplayConfig APIs etc is not avilable in this mode. */
-              {
-                  /* use traditional approach of ChangeDisplaySettingEx to enable/disable secondary monitor for Vista WDDM mode.*/
-                  dwStatus = EnableAndResizeDispDev(paDeviceModes, paDisplayDevices, DevNum,  Id, Width, Height, BitsPerPixel,
-                                                    dwNewPosX, dwNewPosY, fEnabled, fExtDispSup, pCtx);
-                  if (dwStatus != DISP_CHANGE_SUCCESSFUL )
-                  {
-                      /* Successfully set new video mode or our driver can not set
-                       * the requested mode. Stop trying.
-                       */
-                       LogRel(("VBoxTray: (WDDM) Failed to enable/disable the Display Device \n"));
-                  }
-              }
-              return FALSE; /* for enable disable not retrying */
-        }
-        else
-        {
-            /* Resize request. Secondary display device should be in an enabled state. */
-            LogRel(("VBoxTray: (WDDM) Request to resize the display \n"));
-            DWORD err = VBoxDispIfResizeModes(&pCtx->pEnv->dispIf, Id, paDisplayDevices, paDeviceModes, NumDevices);
-            if (err == NO_ERROR || err != ERROR_RETRY)
-            {
-                if (err == NO_ERROR)
-                    LogRel(("VBoxTray: VBoxDisplayThread: (WDDM) VBoxDispIfResizeModes succeeded\n"));
-                else
-                    LogRel(("VBoxTray: VBoxDisplayThread: (WDDM) Failure VBoxDispIfResizeModes (%d)\n", err));
-                return FALSE;
-            }
-        }
+        }
+
+        Log(("VBoxTray: (WDDM) Request to resize the displa\n"));
+        DWORD err = VBoxDispIfResizeModes(&pCtx->pEnv->dispIf, Id, fEnabled, fExtDispSup, paDisplayDevices, paDeviceModes, DevNum);
+        if (err == NO_ERROR || err != ERROR_RETRY)
+        {
+            if (err == NO_ERROR)
+                Log(("VBoxTray: VBoxDisplayThread: (WDDM) VBoxDispIfResizeModes succeeded\n"));
+            else
+               WARN(("VBoxTray: VBoxDisplayThread: (WDDM) Failure VBoxDispIfResizeModes (%d)\n", err));
+            return FALSE;
+        }
+
         Log(("VBoxTray: ResizeDisplayDevice: (WDDM) RETRY requested\n"));
         return TRUE;
@@ -695,5 +675,5 @@
          Id, Width, Height, dwNewPosX, dwNewPosY, fEnabled, fExtDispSup));
     dwStatus = EnableAndResizeDispDev(paDeviceModes, paDisplayDevices, DevNum, Id, Width, Height, BitsPerPixel,
-                                      dwNewPosX, dwNewPosY, fEnabled, fExtDispSup, pCtx);
+                                      dwNewPosX, dwNewPosY, fEnabled, fExtDispSup);
     if (dwStatus == DISP_CHANGE_SUCCESSFUL || dwStatus == DISP_CHANGE_BADMODE)
     {
@@ -730,4 +710,6 @@
 
     PostMessage(ghwndToolWindow, WM_VBOX_GRAPHICS_SUPPORTED, 0, 0);
+
+    VBoxDispIfResizeStarted(&pCtx->pEnv->dispIf);
 
     do
@@ -979,5 +961,6 @@
             if (waitEvent.u32EventFlagsOut & VMMDEV_EVENT_MOUSE_CAPABILITIES_CHANGED)
                 hlpReloadCursor();
-        } else
+        }
+        else
         {
             Log(("VBoxTray: VBoxDisplayThread: error 0 from DeviceIoControl VBOXGUEST_IOCTL_WAITEVENT\n"));
Index: trunk/src/VBox/Additions/WINNT/VBoxTray/VBoxDisplay.h
===================================================================
--- trunk/src/VBox/Additions/WINNT/VBoxTray/VBoxDisplay.h	(revision 48058)
+++ trunk/src/VBox/Additions/WINNT/VBoxTray/VBoxDisplay.h	(revision 48070)
@@ -23,4 +23,7 @@
 void               VBoxDisplayDestroy (const VBOXSERVICEENV *pEnv, void *pInstance);
 
+DWORD VBoxGetDisplayConfigCount();
+DWORD VBoxGetDisplayConfig(const DWORD NumDevices, DWORD *pDevPrimaryNum, DWORD *pNumDevices, DISPLAY_DEVICE *paDisplayDevices, DEVMODE *paDeviceModes);
+
 #ifndef VBOX_WITH_WDDM
 static bool isVBoxDisplayDriverActive (void);
Index: trunk/src/VBox/Additions/WINNT/VBoxTray/VBoxHelpers.cpp
===================================================================
--- trunk/src/VBox/Additions/WINNT/VBoxTray/VBoxHelpers.cpp	(revision 48058)
+++ trunk/src/VBox/Additions/WINNT/VBoxTray/VBoxHelpers.cpp	(revision 48070)
@@ -112,5 +112,6 @@
 
 void hlpResizeRect(RECTL *paRects, unsigned nRects, unsigned uPrimary,
-                   unsigned uResized, int iNewWidth, int iNewHeight)
+                   unsigned uResized, int iNewWidth, int iNewHeight,
+                   int iNewPosX, int iNewPosY)
 {
     DDCLOG(("nRects %d, iPrimary %d, iResized %d, NewWidth %d, NewHeight %d\n", nRects, uPrimary, uResized, iNewWidth, iNewHeight));
@@ -120,4 +121,8 @@
     paNewRects[uResized].right += iNewWidth - (paNewRects[uResized].right - paNewRects[uResized].left);
     paNewRects[uResized].bottom += iNewHeight - (paNewRects[uResized].bottom - paNewRects[uResized].top);
+    paNewRects[uResized].right += iNewPosX - paNewRects[uResized].left;
+    paNewRects[uResized].bottom += iNewPosY - paNewRects[uResized].top;
+    paNewRects[uResized].left = iNewPosX;
+    paNewRects[uResized].top = iNewPosY;
 
     /* Verify all pairs of originally adjacent rectangles for all 4 directions.
Index: trunk/src/VBox/Additions/WINNT/VBoxTray/VBoxHelpers.h
===================================================================
--- trunk/src/VBox/Additions/WINNT/VBoxTray/VBoxHelpers.h	(revision 48058)
+++ trunk/src/VBox/Additions/WINNT/VBoxTray/VBoxHelpers.h	(revision 48070)
@@ -29,5 +29,5 @@
 extern int hlpReportStatus(VBoxGuestFacilityStatus statusCurrent);
 extern void hlpReloadCursor(void);
-extern void hlpResizeRect(RECTL *paRects, unsigned nRects, unsigned uPrimary, unsigned uResized, int iNewWidth, int iNewHeight);
+extern void hlpResizeRect(RECTL *paRects, unsigned nRects, unsigned uPrimary, unsigned uResized, int iNewWidth, int iNewHeight, int iNewPosX, int iNewPosY);
 extern int hlpShowBalloonTip(HINSTANCE hInst, HWND hWnd, UINT uID, const char *pszMsg, const char *pszTitle, UINT uTimeout, DWORD dwInfoFlags);
 
Index: trunk/src/VBox/Additions/WINNT/VBoxTray/VBoxSeamless.cpp
===================================================================
--- trunk/src/VBox/Additions/WINNT/VBoxTray/VBoxSeamless.cpp	(revision 48058)
+++ trunk/src/VBox/Additions/WINNT/VBoxTray/VBoxSeamless.cpp	(revision 48070)
@@ -116,10 +116,10 @@
 }
 
-void VBoxSeamlessInstallHook()
+static void VBoxSeamlessInstallHook()
 {
     if (gCtx.pfnVBoxHookInstallWindowTracker)
     {
         /* Check current visible region state */
-        VBoxSeamlessCheckWindows();
+        VBoxSeamlessCheckWindows(true);
 
         HMODULE hMod = (HMODULE)RTLdrGetNativeHandle(gCtx.hModHook);
@@ -129,5 +129,5 @@
 }
 
-void VBoxSeamlessRemoveHook()
+static void VBoxSeamlessRemoveHook()
 {
     if (gCtx.pfnVBoxHookRemoveWindowTracker)
@@ -139,4 +139,25 @@
         gCtx.lpEscapeData = NULL;
     }
+}
+
+extern HANDLE ghSeamlessKmNotifyEvent;
+
+static VBOXDISPIF_SEAMLESS gVBoxDispIfSeamless;
+
+
+void VBoxSeamlessEnable()
+{
+    Assert(ghSeamlessKmNotifyEvent);
+
+    VBoxDispIfSeamlesCreate(&gCtx.pEnv->dispIf, &gVBoxDispIfSeamless, ghSeamlessKmNotifyEvent);
+
+    VBoxSeamlessInstallHook();
+}
+
+void VBoxSeamlessDisable()
+{
+    VBoxSeamlessRemoveHook();
+
+    VBoxDispIfSeamlesTerm(&gVBoxDispIfSeamless);
 }
 
@@ -245,6 +266,9 @@
 }
 
-void VBoxSeamlessCheckWindows()
-{
+void VBoxSeamlessCheckWindows(bool fForce)
+{
+    if (!VBoxDispIfSeamlesIsValid(&gVBoxDispIfSeamless))
+        return;
+
     VBOX_ENUM_PARAM param;
 
@@ -280,10 +304,11 @@
 #endif
                     LPRGNDATA lpCtxRgnData = VBOXDISPIFESCAPE_DATA(gCtx.lpEscapeData, RGNDATA);
-                    if (    !gCtx.lpEscapeData
+                    if (fForce
+                        ||  !gCtx.lpEscapeData
                         ||  (lpCtxRgnData->rdh.dwSize + lpCtxRgnData->rdh.nRgnSize != cbSize)
                         ||  memcmp(lpCtxRgnData, lpRgnData, cbSize))
                     {
                         /* send to display driver */
-                        VBoxDispIfEscape(&gCtx.pEnv->dispIf, lpEscapeData, cbSize);
+                        VBoxDispIfSeamlesSubmit(&gVBoxDispIfSeamless, lpEscapeData, cbSize);
 
                         if (gCtx.lpEscapeData)
Index: trunk/src/VBox/Additions/WINNT/VBoxTray/VBoxSeamless.h
===================================================================
--- trunk/src/VBox/Additions/WINNT/VBoxTray/VBoxSeamless.h	(revision 48058)
+++ trunk/src/VBox/Additions/WINNT/VBoxTray/VBoxSeamless.h	(revision 48070)
@@ -24,7 +24,7 @@
 
 
-void VBoxSeamlessInstallHook();
-void VBoxSeamlessRemoveHook();
-void VBoxSeamlessCheckWindows();
+void VBoxSeamlessEnable();
+void VBoxSeamlessDisable();
+void VBoxSeamlessCheckWindows(bool fForce);
 
 void VBoxSeamlessSetSupported(BOOL fSupported);
Index: trunk/src/VBox/Additions/WINNT/VBoxTray/VBoxTray.cpp
===================================================================
--- trunk/src/VBox/Additions/WINNT/VBoxTray/VBoxTray.cpp	(revision 48058)
+++ trunk/src/VBox/Additions/WINNT/VBoxTray/VBoxTray.cpp	(revision 48070)
@@ -46,15 +46,4 @@
 #include <Wtsapi32.h>
 
-#ifdef DEBUG_misha
-#define WARN(_m) do { \
-            Assert(0); \
-            Log(_m); \
-        } while (0)
-#else
-#define WARN(_m) do { \
-            Log(_m); \
-        } while (0)
-#endif
-
 /*
  * St (session [state] tracking) functionality API
@@ -136,4 +125,5 @@
 HANDLE                ghStopSem;
 HANDLE                ghSeamlessWtNotifyEvent = 0;
+HANDLE                ghSeamlessKmNotifyEvent = 0;
 SERVICE_STATUS        gVBoxServiceStatus;
 SERVICE_STATUS_HANDLE gVBoxServiceStatusHandle;
@@ -629,4 +619,11 @@
                 Log(("VBoxTray: CreateEvent for Seamless failed, last error = %08X\n", dwErr));
             }
+
+            ghSeamlessKmNotifyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
+            if (ghSeamlessKmNotifyEvent == NULL)
+            {
+                dwErr = GetLastError();
+                Log(("VBoxTray: CreateEvent for Seamless failed, last error = %08X\n", dwErr));
+            }
         }
     }
@@ -640,4 +637,10 @@
         CloseHandle(ghSeamlessWtNotifyEvent);
         ghSeamlessWtNotifyEvent = NULL;
+    }
+
+    if (ghSeamlessKmNotifyEvent)
+    {
+        CloseHandle(ghSeamlessKmNotifyEvent);
+        ghSeamlessKmNotifyEvent = NULL;
     }
 }
@@ -725,5 +728,5 @@
                  */
 
-                HANDLE hWaitEvent[3] = {0};
+                HANDLE hWaitEvent[4] = {0};
                 DWORD dwEventCount = 0;
 
@@ -734,4 +737,9 @@
                 {
                     hWaitEvent[dwEventCount++] = ghSeamlessWtNotifyEvent;
+                }
+
+                if (0 != ghSeamlessKmNotifyEvent)
+                {
+                    hWaitEvent[dwEventCount++] = ghSeamlessKmNotifyEvent;
                 }
 
@@ -768,5 +776,13 @@
 
                                     /* seamless window notification */
-                                    VBoxSeamlessCheckWindows();
+                                    VBoxSeamlessCheckWindows(false);
+                                    fHandled = TRUE;
+                                }
+                                else if (hWaitEvent[waitResult] == ghSeamlessKmNotifyEvent)
+                                {
+                                    Log(("VBoxTray: Event 'Km Seamless' triggered\n"));
+
+                                    /* seamless window notification */
+                                    VBoxSeamlessCheckWindows(true);
                                     fHandled = TRUE;
                                 }
@@ -988,5 +1004,5 @@
         case WM_VBOX_SEAMLESS_UPDATE:
             if (VBoxCapsEntryIsEnabled(VBOXCAPS_ENTRY_IDX_SEAMLESS))
-                VBoxSeamlessCheckWindows();
+                VBoxSeamlessCheckWindows(true);
             return 0;
 
@@ -1297,5 +1313,5 @@
     if (GetVersionEx(&info))
     {
-        WARN(("VBoxTray: Windows version %ld.%ld\n", info.dwMajorVersion, info.dwMinorVersion));
+        LogRel(("VBoxTray: Windows version %ld.%ld\n", info.dwMajorVersion, info.dwMinorVersion));
         gMajorVersion = info.dwMajorVersion;
     }
@@ -1507,5 +1523,5 @@
         Assert(pCap->enmAcState == VBOXCAPS_ENTRY_ACSTATE_ACQUIRED);
         Assert(pCap->enmFuncState == VBOXCAPS_ENTRY_FUNCSTATE_STARTED);
-        VBoxSeamlessInstallHook();
+        VBoxSeamlessEnable();
     }
     else
@@ -1513,5 +1529,5 @@
         Log(("VBoxTray: vboxCapsOnEnableSeamles: DISABLED\n"));
         Assert(pCap->enmAcState != VBOXCAPS_ENTRY_ACSTATE_ACQUIRED || pCap->enmFuncState != VBOXCAPS_ENTRY_FUNCSTATE_STARTED);
-        VBoxSeamlessRemoveHook();
+        VBoxSeamlessDisable();
     }
 }
Index: trunk/src/VBox/Additions/WINNT/VBoxTray/VBoxTray.h
===================================================================
--- trunk/src/VBox/Additions/WINNT/VBoxTray/VBoxTray.h	(revision 48058)
+++ trunk/src/VBox/Additions/WINNT/VBoxTray/VBoxTray.h	(revision 48070)
@@ -54,4 +54,15 @@
 
 #include "VBoxDispIf.h"
+
+#ifdef DEBUG_misha
+#define WARN(_m) do { \
+            Assert(0); \
+            Log(_m); \
+        } while (0)
+#else
+#define WARN(_m) do { \
+            Log(_m); \
+        } while (0)
+#endif
 
 /*
Index: trunk/src/VBox/Additions/WINNT/include/VBoxDisplay.h
===================================================================
--- trunk/src/VBox/Additions/WINNT/include/VBoxDisplay.h	(revision 48058)
+++ trunk/src/VBox/Additions/WINNT/include/VBoxDisplay.h	(revision 48070)
@@ -38,4 +38,5 @@
 # define VBOXESC_ADJUSTVIDEOMODES           0xABCD9011
 # define VBOXESC_SETCTXHOSTID               0xABCD9012
+# define VBOXESC_CONFIGURETARGETS           0xABCD9013
 #endif /* #ifdef VBOX_WITH_WDDM */
 
