diff --git a/ntoskrnl/cache/section/data.c b/ntoskrnl/cache/section/data.c
index 3b4aafac89f..bbb299e735e 100644
--- a/ntoskrnl/cache/section/data.c
+++ b/ntoskrnl/cache/section/data.c
@@ -98,7 +98,7 @@ NTAPI
 _MmLockSectionSegment(PMM_SECTION_SEGMENT Segment, const char *file, int line)
 {
     //DPRINT("MmLockSectionSegment(%p,%s:%d)\n", Segment, file, line);
-    ExAcquireFastMutex(&Segment->Lock);
+    ExAcquirePushLockExclusive(&Segment->Lock);
     Segment->Locked = TRUE;
 }
 
@@ -108,7 +108,7 @@ _MmUnlockSectionSegment(PMM_SECTION_SEGMENT Segment, const char *file, int line)
 {
     ASSERT(Segment->Locked);
     Segment->Locked = FALSE;
-    ExReleaseFastMutex(&Segment->Lock);
+    ExReleasePushLock(&Segment->Lock);
     //DPRINT("MmUnlockSectionSegment(%p,%s:%d)\n", Segment, file, line);
 }
 
diff --git a/ntoskrnl/cc/cacheman.c b/ntoskrnl/cc/cacheman.c
index 238fecb0f5a..1cc0929c70e 100644
--- a/ntoskrnl/cc/cacheman.c
+++ b/ntoskrnl/cc/cacheman.c
@@ -114,7 +114,11 @@ VOID
 NTAPI
 CcShutdownSystem(VOID)
 {
-    /* NOTHING TO DO */
+    ULONG Dummy;
+    /* Flush everything */
+    CcRosFlushDirtyPages(MAXULONG, &Dummy, TRUE, FALSE);
+    /* HACK: One last round for the Mm Writer thread */
+    MmShutdownBalancer();
 }
 
 /*
diff --git a/ntoskrnl/cc/copy.c b/ntoskrnl/cc/copy.c
index 09af125540c..af6d596cea1 100644
--- a/ntoskrnl/cc/copy.c
+++ b/ntoskrnl/cc/copy.c
@@ -796,8 +796,8 @@ CcZeroData (
     CCTRACE(CC_API_DEBUG, "FileObject=%p StartOffset=%I64u EndOffset=%I64u Wait=%d\n",
         FileObject, StartOffset->QuadPart, EndOffset->QuadPart, Wait);
 
-    DPRINT("CcZeroData(FileObject 0x%p, StartOffset %I64x, EndOffset %I64x, "
-           "Wait %u)\n", FileObject, StartOffset->QuadPart, EndOffset->QuadPart,
+    DPRINT("CcZeroData(FileObject %wZ (0x%p), StartOffset %I64x, EndOffset %I64x, "
+           "Wait %u)\n", &FileObject->FileName, FileObject, StartOffset->QuadPart, EndOffset->QuadPart,
            Wait);
 
     Length = EndOffset->QuadPart - StartOffset->QuadPart;
@@ -813,6 +813,9 @@ CcZeroData (
         ULONG CurrentLength;
         PPFN_NUMBER PfnArray;
 
+        DPRINT("Non cached zeroing: FileObject %wZ (0x%p), StartOffset %I64x, EndOffset %I64x, Wait %u\n",
+               &FileObject->FileName, FileObject, StartOffset->QuadPart, EndOffset->QuadPart, Wait);
+
         /* Setup our Mdl */
         Mdl = IoAllocateMdl(NULL, min(Length, MAX_ZERO_LENGTH), FALSE, FALSE, NULL);
         if (!Mdl)
diff --git a/ntoskrnl/include/internal/ex.h b/ntoskrnl/include/internal/ex.h
index a8273001523..378fb8ec3a6 100644
--- a/ntoskrnl/include/internal/ex.h
+++ b/ntoskrnl/include/internal/ex.h
@@ -1519,11 +1519,19 @@ XIPInit(
     IN PLOADER_PARAMETER_BLOCK LoaderBlock
 );
 
-#define InterlockedDecrementUL(Addend) \
-   (ULONG)InterlockedDecrement((PLONG)(Addend))
+FORCEINLINE
+ULONG
+InterlockedDecrementUL(volatile ULONG* Addend)
+{
+    return (ULONG)InterlockedDecrement((volatile LONG*)Addend);
+}
 
-#define InterlockedIncrementUL(Addend) \
-   (ULONG)InterlockedIncrement((PLONG)(Addend))
+FORCEINLINE
+ULONG
+InterlockedIncrementUL(volatile ULONG* Addend)
+{
+    return (ULONG)InterlockedIncrement((volatile LONG*)Addend);
+}
 
 #define InterlockedExchangeUL(Target, Value) \
    (ULONG)InterlockedExchange((PLONG)(Target), (LONG)(Value))
diff --git a/ntoskrnl/include/internal/mm.h b/ntoskrnl/include/internal/mm.h
index 5c28d27806b..6ed24e52e5f 100644
--- a/ntoskrnl/include/internal/mm.h
+++ b/ntoskrnl/include/internal/mm.h
@@ -196,7 +196,7 @@ typedef struct _MM_SECTION_SEGMENT
     LONG64 RefCount;
     PFILE_OBJECT FileObject;
 
-    FAST_MUTEX Lock;		/* lock which protects the page directory */
+    EX_PUSH_LOCK Lock;		/* lock which protects the page directory */
     LARGE_INTEGER RawLength;		/* length of the segment which is part of the mapped file */
     LARGE_INTEGER Length;			/* absolute length of the segment */
     PLONG64 ReferenceCount;
@@ -432,8 +432,7 @@ typedef struct _MMPFN
 
     // HACK until WS lists are supported
     MMWSLE Wsle;
-    struct _MMPFN* NextLRU;
-    struct _MMPFN* PreviousLRU;
+    LIST_ENTRY LruEntry;
 } MMPFN, *PMMPFN;
 
 extern PMMPFN MmPfnDatabase;
@@ -455,8 +454,6 @@ extern MMPFNLIST MmModifiedNoWritePageListHead;
 typedef struct _MM_MEMORY_CONSUMER
 {
     ULONG PagesUsed;
-    ULONG PagesTarget;
-    NTSTATUS (*Trim)(ULONG Target, ULONG Priority, PULONG NrFreed);
 } MM_MEMORY_CONSUMER, *PMM_MEMORY_CONSUMER;
 
 typedef struct _MM_REGION
@@ -868,14 +865,6 @@ MmDeleteKernelStack(PVOID Stack,
 
 /* balance.c *****************************************************************/
 
-CODE_SEG("INIT")
-VOID
-NTAPI
-MmInitializeMemoryConsumer(
-    ULONG Consumer,
-    NTSTATUS (*Trim)(ULONG Target, ULONG Priority, PULONG NrFreed)
-);
-
 CODE_SEG("INIT")
 VOID
 NTAPI
@@ -905,9 +894,14 @@ NTAPI
 MiInitBalancerThread(VOID);
 
 VOID
-NTAPI
 MmRebalanceMemoryConsumers(VOID);
 
+PFN_NUMBER
+MmPopStandbyPage(VOID);
+
+VOID
+MmShutdownBalancer(VOID);
+
 /* rmap.c **************************************************************/
 #define RMAP_SEGMENT_MASK ~((ULONG_PTR)0xff)
 #define RMAP_IS_SEGMENT(x) (((ULONG_PTR)(x) & RMAP_SEGMENT_MASK) == RMAP_SEGMENT_MASK)
@@ -947,13 +941,16 @@ MmDeleteRmap(
     PVOID Address
 );
 
+_IRQL_requires_max_(DISPATCH_LEVEL)
+VOID
+MmFreeRmap(_In_ __drv_freesMem(Mem) PMM_RMAP_ENTRY Rmap);
+
 CODE_SEG("INIT")
 VOID
 NTAPI
 MmInitializeRmapList(VOID);
 
 NTSTATUS
-NTAPI
 MmPageOutPhysicalAddress(PFN_NUMBER Page);
 
 PMM_SECTION_SEGMENT
@@ -1045,13 +1042,41 @@ MiGetPfnEntryIndex(IN PMMPFN Pfn1)
     return Pfn1 - MmPfnDatabase;
 }
 
+_IRQL_requires_max_(DISPATCH_LEVEL)
 PFN_NUMBER
-NTAPI
-MmGetLRUNextUserPage(PFN_NUMBER PreviousPage, BOOLEAN MoveToLast);
+MmGetLRUFirstUserPage(VOID);
 
+_IRQL_requires_max_(DISPATCH_LEVEL)
+VOID
+MmInsertLRULastUserPage(PFN_NUMBER Page);
+
+_IRQL_requires_max_(DISPATCH_LEVEL)
+VOID
+MmRemoveLRUUserPage(PFN_NUMBER Page);
+
+_IRQL_requires_max_(DISPATCH_LEVEL)
 PFN_NUMBER
-NTAPI
-MmGetLRUFirstUserPage(VOID);
+MmGetLRUFirstModifiedPage(VOID);
+
+_IRQL_requires_max_(DISPATCH_LEVEL)
+VOID
+MmInsertLRULastModifiedPage(PFN_NUMBER Page);
+
+_IRQL_requires_max_(DISPATCH_LEVEL)
+VOID
+MmRemoveLRUModifiedPage(PFN_NUMBER Page);
+
+_IRQL_requires_max_(DISPATCH_LEVEL)
+PFN_NUMBER
+MmGetLRUFirstStandbyPage(VOID);
+
+_IRQL_requires_max_(DISPATCH_LEVEL)
+VOID
+MmInsertLRULastStandbyPage(PFN_NUMBER Page);
+
+_IRQL_requires_max_(DISPATCH_LEVEL)
+VOID
+MmRemoveLRUStandbyPage(PFN_NUMBER Page);
 
 VOID
 NTAPI
@@ -1331,18 +1356,11 @@ MmFindRegion(
 #define DIRTY_SSE(E)             ((E) | 2)
 #define CLEAN_SSE(E)             ((E) & ~2)
 #define IS_DIRTY_SSE(E)          ((E) & 2)
-#define WRITE_SSE(E)             ((E) | 4)
-#define IS_WRITE_SSE(E)          ((E) & 4)
-#ifdef _WIN64
-#define PAGE_FROM_SSE(E)         ((E) & 0xFFFFFFF000ULL)
-#else
-#define PAGE_FROM_SSE(E)         ((E) & 0xFFFFF000)
-#endif
-#define SHARE_COUNT_FROM_SSE(E)  (((E) & 0x00000FFC) >> 3)
-#define MAX_SHARE_COUNT          0x1FF
-#define MAKE_SSE(P, C)           ((ULONG_PTR)((P) | ((C) << 3)))
-#define BUMPREF_SSE(E)           (PAGE_FROM_SSE(E) | ((SHARE_COUNT_FROM_SSE(E) + 1) << 3) | ((E) & 0x7))
-#define DECREF_SSE(E)            (PAGE_FROM_SSE(E) | ((SHARE_COUNT_FROM_SSE(E) - 1) << 3) | ((E) & 0x7))
+#define SHARE_COUNT_FROM_SSE(E)  (((E) & 0x00000FFC) >> 2)
+#define MAX_SHARE_COUNT          0x3FF
+#define MAKE_SSE(P, C)           ((ULONG_PTR)((P) | ((C) << 2)))
+#define BUMPREF_SSE(E)           ((PFN_FROM_SSE(E) << PAGE_SHIFT) | ((SHARE_COUNT_FROM_SSE(E) + 1) << 2) | ((E) & 0x3))
+#define DECREF_SSE(E)            ((PFN_FROM_SSE(E) << PAGE_SHIFT) | ((SHARE_COUNT_FROM_SSE(E) - 1) << 2) | ((E) & 0x3))
 
 VOID
 NTAPI
@@ -1495,21 +1513,17 @@ MmPurgeSegment(
     _In_ ULONG Length);
 
 BOOLEAN
-NTAPI
 MmCheckDirtySegment(
     PMM_SECTION_SEGMENT Segment,
     PLARGE_INTEGER Offset,
-    BOOLEAN ForceDirty,
     BOOLEAN PageOut);
 
 BOOLEAN
 NTAPI
-MmUnsharePageEntrySectionSegment(PMEMORY_AREA MemoryArea,
-                                 PMM_SECTION_SEGMENT Segment,
+MmUnsharePageEntrySectionSegment(PMM_SECTION_SEGMENT Segment,
                                  PLARGE_INTEGER Offset,
                                  BOOLEAN Dirty,
-                                 BOOLEAN PageOut,
-                                 ULONG_PTR *InEntry);
+                                 BOOLEAN PageOut);
 
 _When_(OldIrql == MM_NOIRQL, _IRQL_requires_max_(DISPATCH_LEVEL))
 _When_(OldIrql == MM_NOIRQL, _Requires_lock_not_held_(MmPfnLock))
diff --git a/ntoskrnl/ke/ipi.c b/ntoskrnl/ke/ipi.c
index 841087d1daa..f1d2f1958ea 100644
--- a/ntoskrnl/ke/ipi.c
+++ b/ntoskrnl/ke/ipi.c
@@ -170,7 +170,7 @@ KiIpiServiceRoutine(IN PKTRAP_FRAME TrapFrame,
 #if defined(_M_ARM) || defined(_M_AMD64)
         DbgBreakPoint();
 #else
-        (void)InterlockedDecrementUL(&Prcb->SignalDone->CurrentPacket[1]);
+        (void)InterlockedDecrementUL((ULONG*)&Prcb->SignalDone->CurrentPacket[1]);
         if (InterlockedCompareExchangeUL(&Prcb->SignalDone->CurrentPacket[2], 0, 0))
         {
             while (0 != InterlockedCompareExchangeUL(&Prcb->SignalDone->CurrentPacket[1], 0, 0));
diff --git a/ntoskrnl/mm/ARM3/miarm.h b/ntoskrnl/mm/ARM3/miarm.h
index b5fd1de3409..4ca73b19fa1 100644
--- a/ntoskrnl/mm/ARM3/miarm.h
+++ b/ntoskrnl/mm/ARM3/miarm.h
@@ -2408,6 +2408,10 @@ NTAPI
 MiWriteProtectSystemImage(
     _In_ PVOID ImageBase);
 
+VOID
+MiFillSystemPageDirectory(_In_ PVOID Base,
+                          _In_ SIZE_T NumberOfBytes);
+
 //
 // MiRemoveZeroPage will use inline code to zero out the page manually if only
 // free pages are available. In some scenarios, we don't/can't run that piece of
@@ -2436,6 +2440,9 @@ MiSynchronizeSystemPde(PMMPDE PointerPde)
 
     /* Copy the PDE from the double-mapped system page directory */
     SystemPde = MmSystemPagePtes[Index];
+
+    ASSERT((PointerPde->u.Long == 0) || (PointerPde->u.Long == SystemPde.u.Long));
+
     *PointerPde = SystemPde;
 
     /* Make sure we re-read the PDE and PTE */
diff --git a/ntoskrnl/mm/ARM3/pfnlist.c b/ntoskrnl/mm/ARM3/pfnlist.c
index 5712f22557a..f1cf7fb838a 100644
--- a/ntoskrnl/mm/ARM3/pfnlist.c
+++ b/ntoskrnl/mm/ARM3/pfnlist.c
@@ -64,7 +64,6 @@ ULONG MI_PFN_CURRENT_USAGE;
 CHAR MI_PFN_CURRENT_PROCESS_NAME[16] = "None yet";
 
 /* FUNCTIONS ******************************************************************/
-static
 VOID
 MiIncrementAvailablePages(
     VOID)
@@ -85,7 +84,6 @@ MiIncrementAvailablePages(
     }
 }
 
-static
 VOID
 MiDecrementAvailablePages(
     VOID)
@@ -110,7 +108,7 @@ MiDecrementAvailablePages(
     {
         /* FIXME: Should wake up the MPW and working set manager, if we had one */
 
-        DPRINT1("Running low on pages: %lu remaining\n", MmAvailablePages);
+        DPRINT("Running low on pages: %lu remaining\n", MmAvailablePages);
 
         /* Call RosMm and see if it can release any pages for us */
         MmRebalanceMemoryConsumers();
@@ -502,11 +500,13 @@ MiRemoveAnyPage(IN ULONG Color)
                 ASSERT_LIST_INVARIANT(&MmZeroedPageListHead);
                 PageIndex = MmZeroedPageListHead.Flink;
                 Color = PageIndex & MmSecondaryColorMask;
-                ASSERT(PageIndex != LIST_HEAD);
                 if (PageIndex == LIST_HEAD)
                 {
                     /* FIXME: Should check the standby list */
                     ASSERT(MmZeroedPageListHead.Total == 0);
+                    /* Get one from the Ros Mm instead */
+                    PageIndex = MmPopStandbyPage();
+                    Color = PageIndex & MmSecondaryColorMask;
                 }
             }
         }
@@ -562,11 +562,13 @@ MiRemoveZeroPage(IN ULONG Color)
                 ASSERT_LIST_INVARIANT(&MmFreePageListHead);
                 PageIndex = MmFreePageListHead.Flink;
                 Color = PageIndex & MmSecondaryColorMask;
-                ASSERT(PageIndex != LIST_HEAD);
                 if (PageIndex == LIST_HEAD)
                 {
                     /* FIXME: Should check the standby list */
                     ASSERT(MmZeroedPageListHead.Total == 0);
+                    /* Get one from the Ros Mm instead */
+                    PageIndex = MmPopStandbyPage();
+                    Color = PageIndex & MmSecondaryColorMask;
                 }
             }
         }
diff --git a/ntoskrnl/mm/ARM3/section.c b/ntoskrnl/mm/ARM3/section.c
index 4a65209d38b..3ad2d314138 100644
--- a/ntoskrnl/mm/ARM3/section.c
+++ b/ntoskrnl/mm/ARM3/section.c
@@ -476,9 +476,8 @@ MiAddMappedPtes(IN PMMPTE FirstPte,
 }
 
 VOID
-NTAPI
-MiFillSystemPageDirectory(IN PVOID Base,
-                          IN SIZE_T NumberOfBytes)
+MiFillSystemPageDirectory(_In_ PVOID Base,
+                          _In_ SIZE_T NumberOfBytes)
 {
     PMMPDE PointerPde, LastPde, SystemMapPde;
     MMPDE TempPde;
diff --git a/ntoskrnl/mm/balance.c b/ntoskrnl/mm/balance.c
index 4558deeff18..e60f087d853 100644
--- a/ntoskrnl/mm/balance.c
+++ b/ntoskrnl/mm/balance.c
@@ -14,6 +14,8 @@
 #define NDEBUG
 #include <debug.h>
 
+#include "../cache/section/newmm.h"
+
 #include "ARM3/miarm.h"
 
 
@@ -28,38 +30,242 @@ MM_ALLOCATION_REQUEST, *PMM_ALLOCATION_REQUEST;
 /* GLOBALS ******************************************************************/
 
 MM_MEMORY_CONSUMER MiMemoryConsumers[MC_MAXIMUM];
-static ULONG MiMinimumAvailablePages;
-static ULONG MiMinimumPagesPerRun;
-static CLIENT_ID MiBalancerThreadId;
-static HANDLE MiBalancerThreadHandle = NULL;
-static KEVENT MiBalancerEvent;
-static KTIMER MiBalancerTimer;
+static KEVENT MiWritePageEvent;
+static KTIMER MiWritePageTimer;
+static KEVENT MiPageoutEvent;
+static HANDLE MiWriterThread;
+static BOOLEAN MiInShutdown;
+
+/* Linked list of used PFNs */
+static LIST_ENTRY UserLRUPfnListHead;
+
+/* Linked list of Modified PFNs */
+static LIST_ENTRY ModifiedLRUPfnListHead;
+PFN_NUMBER MmModifiedPageCount;
+
+/* Linked list of Standby PFNs */
+static LIST_ENTRY StandbyLRUPfnListHead;
+PFN_NUMBER MmStandbyPageCount;
+
+/* List of RMAPs that we have to free from popping standby pages. */
+static PMM_RMAP_ENTRY RmapsToFree;
+
+/* HELPER FUNCTIONS ******************************************************/
+_IRQL_requires_max_(DISPATCH_LEVEL)
+static
+PFN_NUMBER
+MiGetFirstLRUPage(
+    _Inout_ PLIST_ENTRY ListHead)
+{
+    PFN_NUMBER Page = 0;
+    KIRQL OldIrql = MiAcquirePfnLock();
 
-static LONG PageOutThreadActive;
+    if (!IsListEmpty(ListHead))
+    {
+        PMMPFN Pfn = CONTAINING_RECORD(ListHead->Flink, MMPFN, LruEntry);
+        Page = MiGetPfnEntryIndex(Pfn);
 
-/* FUNCTIONS ****************************************************************/
+        ASSERT(MI_IS_ROS_PFN(Pfn));
+    }
 
-CODE_SEG("INIT")
+    MiReleasePfnLock(OldIrql);
+
+    return Page;
+}
+
+_IRQL_requires_max_(DISPATCH_LEVEL)
+static
 VOID
-NTAPI
-MmInitializeBalancer(ULONG NrAvailablePages, ULONG NrSystemPages)
+MiInsertLastLRUPage(
+    _Inout_ PMMPFN Pfn,
+    _Inout_ PLIST_ENTRY ListHead)
 {
-    memset(MiMemoryConsumers, 0, sizeof(MiMemoryConsumers));
+    KIRQL OldIrql = MiAcquirePfnLock();
+
+    ASSERT(MI_IS_ROS_PFN(Pfn));
+
+    ASSERT(Pfn->LruEntry.Flink == NULL);
+
+    InsertTailList(ListHead, &Pfn->LruEntry);
+
+    /* HACK for this special case */
+    if (ListHead == &UserLRUPfnListHead)
+        Pfn->u4.MustBeCached = 1;
+
+    MiReleasePfnLock(OldIrql);
+}
+
+
+_IRQL_requires_max_(DISPATCH_LEVEL)
+static
+VOID
+MiRemoveLRUPage(
+    _Inout_ PMMPFN Pfn,
+    _Inout_ PLIST_ENTRY ListHead)
+{
+    KIRQL OldIrql = MiAcquirePfnLock();
+
+    ASSERT(MI_IS_ROS_PFN(Pfn));
+
+    RemoveEntryList(&Pfn->LruEntry);
+    RtlZeroMemory(&Pfn->LruEntry, sizeof(Pfn->LruEntry));
+
+    /* HACK for this special case */
+    if (ListHead == &UserLRUPfnListHead)
+    {
+        ASSERT(Pfn->u4.MustBeCached);
+        Pfn->u4.MustBeCached = 0;
+    }
+    else
+    {
+        ASSERT(!Pfn->u4.MustBeCached);
+    }
+
+    MiReleasePfnLock(OldIrql);
+}
+
+/* FUNCTIONS *************************************************************/
+
+_IRQL_requires_max_(DISPATCH_LEVEL)
+PFN_NUMBER
+MmGetLRUFirstUserPage(VOID)
+{
+    return MiGetFirstLRUPage(&UserLRUPfnListHead);
+}
+
+_IRQL_requires_max_(DISPATCH_LEVEL)
+VOID
+MmInsertLRULastUserPage(PFN_NUMBER Page)
+{
+    MiInsertLastLRUPage(MiGetPfnEntry(Page), &UserLRUPfnListHead);
+}
+
+_IRQL_requires_max_(DISPATCH_LEVEL)
+VOID
+MmRemoveLRUUserPage(PFN_NUMBER Page)
+{
+    MiRemoveLRUPage(MiGetPfnEntry(Page), &UserLRUPfnListHead);
+}
+
+_IRQL_requires_max_(DISPATCH_LEVEL)
+PFN_NUMBER
+MmGetLRUNextUserPage(PFN_NUMBER Page)
+{
+    KIRQL OldIrql = MiAcquirePfnLock();
+    PMMPFN Pfn = MiGetPfnEntry(Page);
+    PLIST_ENTRY Entry = NULL;
+
+    Page = 0;
+
+    if (Pfn && MI_IS_ROS_PFN(Pfn) && (Pfn->u4.MustBeCached == 1))
+        Entry = Pfn->LruEntry.Flink;
+
+    if (!Entry)
+        Entry = UserLRUPfnListHead.Flink;
+
+    if (Entry != &UserLRUPfnListHead)
+    {
+        Pfn = CONTAINING_RECORD(Entry, MMPFN, LruEntry);
+        Page = MiGetPfnEntryIndex(Pfn);
+    }
+
+    MiReleasePfnLock(OldIrql);
+
+    return Page;
+}
+
+_IRQL_requires_max_(DISPATCH_LEVEL)
+PFN_NUMBER
+MmGetLRUFirstModifiedPage(VOID)
+{
+    return MiGetFirstLRUPage(&ModifiedLRUPfnListHead);
+}
+
+_IRQL_requires_max_(DISPATCH_LEVEL)
+VOID
+MmInsertLRULastModifiedPage(PFN_NUMBER Page)
+{
+    MiInsertLastLRUPage(MiGetPfnEntry(Page), &ModifiedLRUPfnListHead);
+
+    /* Keep modified page count low */
+    if (InterlockedIncrementUL(&MmModifiedPageCount) > 200)
+    {
+        KeSetEvent(&MiWritePageEvent, IO_NO_INCREMENT, FALSE);
+    }
+}
 
-    /* Set up targets. */
-    MiMinimumAvailablePages = 256;
-    MiMinimumPagesPerRun = 256;
-    MiMemoryConsumers[MC_USER].PagesTarget = NrAvailablePages / 2;
+_IRQL_requires_max_(DISPATCH_LEVEL)
+VOID
+MmRemoveLRUModifiedPage(PFN_NUMBER Page)
+{
+    MiRemoveLRUPage(MiGetPfnEntry(Page), &ModifiedLRUPfnListHead);
+    InterlockedDecrementUL(&MmModifiedPageCount);
+}
+
+_IRQL_requires_max_(DISPATCH_LEVEL)
+PFN_NUMBER
+MmGetLRUFirstStandbyPage(VOID)
+{
+    return MiGetFirstLRUPage(&StandbyLRUPfnListHead);
+}
+
+extern
+VOID
+MiIncrementAvailablePages(
+    VOID);
+
+_IRQL_requires_max_(DISPATCH_LEVEL)
+VOID
+MmInsertLRULastStandbyPage(PFN_NUMBER Page)
+{
+    KIRQL OldIrql = MiAcquirePfnLock();
+    PMMPFN Pfn = MiGetPfnEntry(Page);
+
+    ASSERT(Pfn != NULL);
+
+    InsertTailList(&StandbyLRUPfnListHead, &Pfn->LruEntry);
+
+    /* This one is now available */
+    MiIncrementAvailablePages();
+    MmStandbyPageCount++;
+
+    MiReleasePfnLock(OldIrql);
+}
+
+extern
+VOID
+MiDecrementAvailablePages(
+    VOID);
+
+_IRQL_requires_max_(DISPATCH_LEVEL)
+VOID
+MmRemoveLRUStandbyPage(PFN_NUMBER Page)
+{
+    KIRQL OldIrql = MiAcquirePfnLock();
+    PMMPFN Pfn = MiGetPfnEntry(Page);
+
+    ASSERT(Pfn != NULL);
+
+    RemoveEntryList(&Pfn->LruEntry);
+    RtlZeroMemory(&Pfn->LruEntry, sizeof(Pfn->LruEntry));
+
+    /* This one is not available anymore */
+    MiDecrementAvailablePages();
+    MmStandbyPageCount--;
+
+    MiReleasePfnLock(OldIrql);
 }
 
 CODE_SEG("INIT")
 VOID
 NTAPI
-MmInitializeMemoryConsumer(
-    ULONG Consumer,
-    NTSTATUS (*Trim)(ULONG Target, ULONG Priority, PULONG NrFreed))
+MmInitializeBalancer(ULONG NrAvailablePages, ULONG NrSystemPages)
 {
-    MiMemoryConsumers[Consumer].Trim = Trim;
+    memset(MiMemoryConsumers, 0, sizeof(MiMemoryConsumers));
+
+    InitializeListHead(&UserLRUPfnListHead);
+    InitializeListHead(&ModifiedLRUPfnListHead);
+    InitializeListHead(&StandbyLRUPfnListHead);
 }
 
 VOID
@@ -91,51 +297,10 @@ MmReleasePageMemoryConsumer(ULONG Consumer, PFN_NUMBER Page)
     return(STATUS_SUCCESS);
 }
 
-ULONG
-NTAPI
-MiTrimMemoryConsumer(ULONG Consumer, ULONG InitialTarget)
-{
-    ULONG Target = InitialTarget;
-    ULONG NrFreedPages = 0;
-    NTSTATUS Status;
-
-    /* Make sure we can trim this consumer */
-    if (!MiMemoryConsumers[Consumer].Trim)
-    {
-        /* Return the unmodified initial target */
-        return InitialTarget;
-    }
-
-    if (MmAvailablePages < MiMinimumAvailablePages)
-    {
-        /* Global page limit exceeded */
-        Target = (ULONG)max(Target, MiMinimumAvailablePages - MmAvailablePages);
-    }
-    else if (MiMemoryConsumers[Consumer].PagesUsed > MiMemoryConsumers[Consumer].PagesTarget)
-    {
-        /* Consumer page limit exceeded */
-        Target = max(Target, MiMemoryConsumers[Consumer].PagesUsed - MiMemoryConsumers[Consumer].PagesTarget);
-    }
-
-    if (Target)
-    {
-        /* Now swap the pages out */
-        Status = MiMemoryConsumers[Consumer].Trim(Target, MmAvailablePages < MiMinimumAvailablePages, &NrFreedPages);
-
-        DPRINT("Trimming consumer %lu: Freed %lu pages with a target of %lu pages\n", Consumer, NrFreedPages, Target);
-
-        if (!NT_SUCCESS(Status))
-        {
-            KeBugCheck(MEMORY_MANAGEMENT);
-        }
-    }
-
-    /* Return the page count needed to be freed to meet the initial target */
-    return (InitialTarget > NrFreedPages) ? (InitialTarget - NrFreedPages) : 0;
-}
-
-NTSTATUS
-MmTrimUserMemory(ULONG Target, ULONG Priority, PULONG NrFreedPages)
+#if 0
+static
+BOOLEAN
+MmPruneUserPage(PFN_NUMBER Page)
 {
     PFN_NUMBER CurrentPage;
     NTSTATUS Status;
@@ -264,15 +429,83 @@ MmTrimUserMemory(ULONG Target, ULONG Priority, PULONG NrFreedPages)
 
     return STATUS_SUCCESS;
 }
+#endif
 
 VOID
-NTAPI
 MmRebalanceMemoryConsumers(VOID)
 {
-    // if (InterlockedCompareExchange(&PageOutThreadActive, 0, 1) == 0)
+    /* We're in a low memory situation. Try to give pages back. */
+    KeSetEvent(&MiWritePageEvent, IO_NO_INCREMENT, FALSE);
+    KeSetEvent(&MiPageoutEvent, IO_NO_INCREMENT, FALSE);
+}
+
+PFN_NUMBER
+MmPopStandbyPage(VOID)
+{
+    /* We must be under PFN lock */
+    MI_ASSERT_PFN_LOCK_HELD();
+
+    PLIST_ENTRY ListEntry = StandbyLRUPfnListHead.Flink;
+    while (ListEntry != &StandbyLRUPfnListHead)
     {
-        KeSetEvent(&MiBalancerEvent, IO_NO_INCREMENT, FALSE);
+        PMMPFN Pfn = CONTAINING_RECORD(ListEntry, MMPFN, LruEntry);
+
+        PMM_RMAP_ENTRY Rmap = Pfn->RmapListHead;
+
+        /* The only mapping must be on a segment */
+        NT_ASSERT(Rmap != NULL);
+        NT_ASSERT(Rmap->Next == NULL);
+        NT_ASSERT(RMAP_IS_SEGMENT(Rmap->Address));
+
+        PCACHE_SECTION_PAGE_TABLE PageTable = (PCACHE_SECTION_PAGE_TABLE)Rmap->Process;
+
+        /* See if we can really free it */
+        if (ExTryToAcquirePushLockExclusive(&PageTable->Segment->Lock))
+        {
+            /* Nice, we will be able to remove it */
+            PFN_NUMBER Page = MiGetPfnEntryIndex(Pfn);
+            ULONG Offset = (ULONG_PTR)Rmap->Address & ~RMAP_SEGMENT_MASK;
+            ULONG_PTR Entry = PageTable->PageEntries[Offset];
+
+            NT_ASSERT(Entry != 0);
+            NT_ASSERT(PFN_FROM_SSE(Entry) == Page);
+            NT_ASSERT(SHARE_COUNT_FROM_SSE(Entry) == 0);
+            NT_ASSERT(!IS_DIRTY_SSE(Entry));
+            NT_ASSERT(!IS_SWAP_FROM_SSE(Entry));
+
+            /* Restore value */
+            SWAPENTRY SwapEntry = Pfn->u1.SwapEntry;
+            if (SwapEntry)
+                PageTable->PageEntries[Offset] = MAKE_SWAP_SSE(SwapEntry);
+            else
+                PageTable->PageEntries[Offset] = 0;
+
+            ExReleasePushLockExclusive(&PageTable->Segment->Lock);
+
+            /* Dereferencing it will bump the number of free pages, but this one was already free */
+            MmAvailablePages--;
+
+            /* Unlink it */
+            RemoveEntryList(&Pfn->LruEntry);
+            RtlZeroMemory(&Pfn->LruEntry, sizeof(Pfn->LruEntry));
+            Pfn->RmapListHead = NULL;
+
+            /* Defer freeing this. We can't do it right now because we're holding the PFN lock */
+            Rmap->Next = RmapsToFree;
+            RmapsToFree = Rmap;
+
+            /* Make that a pristine PFN entry */
+            ASSERT(Pfn->u3.ReferenceCount == 1);
+            MmDereferencePage(Page);
+
+            return Page;
+        }
+
+        ListEntry = ListEntry->Flink;
     }
+
+    /* If we get here, we're un trouble */
+    KeBugCheck(NO_PAGES_AVAILABLE);
 }
 
 NTSTATUS
@@ -298,16 +531,48 @@ MmRequestPageMemoryConsumer(ULONG Consumer, BOOLEAN CanWait,
     return(STATUS_SUCCESS);
 }
 
+static
+VOID
+MiPurgeStaleRmaps(VOID)
+{
+    while (TRUE)
+    {
+        PMM_RMAP_ENTRY ToFree;
+        PCACHE_SECTION_PAGE_TABLE PageTable;
+        KIRQL OldIrql = MiAcquirePfnLock();
+
+        ToFree = RmapsToFree;
+        if (ToFree)
+        {
+            RmapsToFree = ToFree->Next;
+        }
+        MiReleasePfnLock(OldIrql);
 
-VOID NTAPI
-MiBalancerThread(PVOID Unused)
+        if (ToFree == NULL)
+        {
+            break;
+        }
+
+        /* Each page map references the segment. Free it here. */
+        PageTable = (PCACHE_SECTION_PAGE_TABLE)ToFree->Process;
+        MmDereferenceSegment(PageTable->Segment);
+
+        MmFreeRmap(ToFree);
+    }
+}
+
+static
+VOID
+NTAPI
+MiPageWriterThread(PVOID Unused)
 {
     PVOID WaitObjects[2];
     NTSTATUS Status;
-    ULONG i;
 
-    WaitObjects[0] = &MiBalancerEvent;
-    WaitObjects[1] = &MiBalancerTimer;
+    UNREFERENCED_PARAMETER(Unused);
+
+    WaitObjects[0] = &MiWritePageEvent;
+    WaitObjects[1] = &MiWritePageTimer;
 
     while (1)
     {
@@ -322,30 +587,59 @@ MiBalancerThread(PVOID Unused)
 
         if (Status == STATUS_WAIT_0 || Status == STATUS_WAIT_1)
         {
-            ULONG InitialTarget = 0;
+            PFN_NUMBER Page, PageCount = MmModifiedPageCount;
 
-            do
-            {
-                ULONG OldTarget = InitialTarget;
+            DPRINT("Balancer running. %d available pages\n", MmAvailablePages);
 
-                /* Trim each consumer */
-                for (i = 0; i < MC_MAXIMUM; i++)
+            /*
+             * Now write modified pages back to disk.
+             * Make sure we don't loop forever because of one failed write.
+             */
+            while ((PageCount != 0) && (Page = MmGetLRUFirstModifiedPage()))
+            {
+                /* Is it part of file map ? */
+                LARGE_INTEGER SegmentOffset;
+                PMM_SECTION_SEGMENT Segment = MmGetSectionAssociation(Page, &SegmentOffset);
+                if (Segment)
                 {
-                    InitialTarget = MiTrimMemoryConsumer(i, InitialTarget);
-                }
+                    /* We're likely modifying FO's ValidDataLength. Lock it */
+                    FsRtlAcquireFileExclusive(Segment->FileObject);
 
-                /* No pages left to swap! */
-                if (InitialTarget != 0 &&
-                        InitialTarget == OldTarget)
-                {
-                    /* Game over */
-                    KeBugCheck(NO_PAGES_AVAILABLE);
+                    /* It is. Flush it to disk. */
+                    MmLockSectionSegment(Segment);
+
+                    ULONG_PTR Entry = MmGetPageEntrySectionSegment(Segment, &SegmentOffset);
+
+                    /* Now that we own the segment, make sure that it's still in modified state. */
+                    if (!IS_SWAP_FROM_SSE(Entry) && (PFN_FROM_SSE(Entry) == Page)
+                        && IS_DIRTY_SSE(Entry) && (SHARE_COUNT_FROM_SSE(Entry) == 0))
+                    {
+                        /* This will write the data to disk and put the page in standby list */
+                        DPRINT("Flushing page 0x%lx to disk\n", Page);
+                        MmCheckDirtySegment(Segment, &SegmentOffset, TRUE);
+                    }
+
+                    MmUnlockSectionSegment(Segment);
+
+                    FsRtlReleaseFile(Segment->FileObject);
+
+                    MmDereferenceSegment(Segment);
                 }
+
+                PageCount--;
+            }
+
+            /* Handle shutdown */
+            if (MiInShutdown)
+            {
+                return;
             }
-            while (InitialTarget != 0);
 
-            if (Status == STATUS_WAIT_0)
-                InterlockedDecrement(&PageOutThreadActive);
+            if (Status == STATUS_WAIT_1)
+            {
+                /* We're not in a hurry. Take this as an occasion to free those */
+                MiPurgeStaleRmaps();
+            }
         }
         else
         {
@@ -355,6 +649,33 @@ MiBalancerThread(PVOID Unused)
     }
 }
 
+static
+VOID
+NTAPI
+MiPageoutThread(PVOID Unused)
+{
+    UNREFERENCED_PARAMETER(Unused);
+
+    while (TRUE)
+    {
+        /* Wake up when in dire need of free pages */
+        KeWaitForSingleObject(&MiPageoutEvent, WrPageOut, KernelMode, FALSE, NULL);
+
+        PFN_NUMBER Page = 0;
+
+        /* Keep the number of standby pages at an acceptable level */
+        while ((MmAvailablePages < MmMinimumFreePages) &&
+            (MmStandbyPageCount < MmMinimumFreePages) &&
+            (Page = MmGetLRUNextUserPage(Page)))
+        {
+            DPRINT1("Running low on page despite our best efforts. Pruning page 0x%lx from working sets.\n", Page);
+
+            MmPageOutPhysicalAddress(Page);
+        }
+    }
+}
+
+
 CODE_SEG("INIT")
 VOID
 NTAPI
@@ -363,22 +684,26 @@ MiInitBalancerThread(VOID)
     KPRIORITY Priority;
     NTSTATUS Status;
     LARGE_INTEGER Timeout;
+    HANDLE ThreadHandle;
+
+    KeInitializeEvent(&MiWritePageEvent, SynchronizationEvent, FALSE);
+    KeInitializeEvent(&MiPageoutEvent, SynchronizationEvent, FALSE);
 
-    KeInitializeEvent(&MiBalancerEvent, SynchronizationEvent, FALSE);
-    KeInitializeTimerEx(&MiBalancerTimer, SynchronizationTimer);
+    KeInitializeTimerEx(&MiWritePageTimer, SynchronizationTimer);
 
     Timeout.QuadPart = -20000000; /* 2 sec */
-    KeSetTimerEx(&MiBalancerTimer,
+    KeSetTimerEx(&MiWritePageTimer,
                  Timeout,
                  2000,         /* 2 sec */
                  NULL);
 
-    Status = PsCreateSystemThread(&MiBalancerThreadHandle,
+    /* Modified page writer */
+    Status = PsCreateSystemThread(&ThreadHandle,
                                   THREAD_ALL_ACCESS,
                                   NULL,
                                   NULL,
-                                  &MiBalancerThreadId,
-                                  MiBalancerThread,
+                                  NULL,
+                                  MiPageWriterThread,
                                   NULL);
     if (!NT_SUCCESS(Status))
     {
@@ -386,11 +711,45 @@ MiInitBalancerThread(VOID)
     }
 
     Priority = LOW_REALTIME_PRIORITY + 1;
-    NtSetInformationThread(MiBalancerThreadHandle,
+    NtSetInformationThread(ThreadHandle,
                            ThreadPriority,
                            &Priority,
                            sizeof(Priority));
+    MiWriterThread = ThreadHandle;
 
+    /* Working set manager (sort of) */
+    Status = PsCreateSystemThread(&ThreadHandle,
+                                  THREAD_ALL_ACCESS,
+                                  NULL,
+                                  NULL,
+                                  NULL,
+                                  MiPageoutThread,
+                                  NULL);
+    if (!NT_SUCCESS(Status))
+    {
+        KeBugCheck(MEMORY_MANAGEMENT);
+    }
+
+    /* This one is important */
+    Priority = LOW_REALTIME_PRIORITY + 1;
+    NtSetInformationThread(ThreadHandle,
+                           ThreadPriority,
+                           &Priority,
+                           sizeof(Priority));
+    ObCloseHandle(ThreadHandle, KernelMode);
+}
+
+VOID
+MmShutdownBalancer(VOID)
+{
+    /* Wake up the writer thread. Tell it to finish */
+    MiInShutdown = TRUE;
+    KeSetEvent(&MiWritePageEvent, IO_NO_INCREMENT, FALSE);
+    NtWaitForSingleObject(MiWriterThread, FALSE, NULL);
+    ObCloseHandle(MiWriterThread, KernelMode);
+
+    /* Ensure we're freeing this and that all segments are properly unreferenced */
+    MiPurgeStaleRmaps();
 }
 
 
diff --git a/ntoskrnl/mm/freelist.c b/ntoskrnl/mm/freelist.c
index e3b2f30f9fa..2854ba49e1e 100644
--- a/ntoskrnl/mm/freelist.c
+++ b/ntoskrnl/mm/freelist.c
@@ -35,128 +35,7 @@ SIZE_T MmPagedPoolCommit;
 SIZE_T MmPeakCommitment;
 SIZE_T MmtotalCommitLimitMaximum;
 
-PMMPFN FirstUserLRUPfn;
-PMMPFN LastUserLRUPfn;
-
-/* FUNCTIONS *************************************************************/
-
-PFN_NUMBER
-NTAPI
-MmGetLRUFirstUserPage(VOID)
-{
-    PFN_NUMBER Page;
-    KIRQL OldIrql;
-
-    /* Find the first user page */
-    OldIrql = MiAcquirePfnLock();
-
-    if (FirstUserLRUPfn == NULL)
-    {
-        MiReleasePfnLock(OldIrql);
-        return 0;
-    }
-
-    Page = MiGetPfnEntryIndex(FirstUserLRUPfn);
-    MmReferencePage(Page);
-
-    MiReleasePfnLock(OldIrql);
-
-    return Page;
-}
-
-static
-VOID
-MmInsertLRULastUserPage(PFN_NUMBER Page)
-{
-    MI_ASSERT_PFN_LOCK_HELD();
-
-    PMMPFN Pfn = MiGetPfnEntry(Page);
-
-    if (FirstUserLRUPfn == NULL)
-        FirstUserLRUPfn = Pfn;
-
-    Pfn->PreviousLRU = LastUserLRUPfn;
-
-    if (LastUserLRUPfn != NULL)
-        LastUserLRUPfn->NextLRU = Pfn;
-    LastUserLRUPfn = Pfn;
-}
-
-static
-VOID
-MmRemoveLRUUserPage(PFN_NUMBER Page)
-{
-    MI_ASSERT_PFN_LOCK_HELD();
-
-    /* Unset the page as a user page */
-    ASSERT(Page != 0);
-
-    PMMPFN Pfn = MiGetPfnEntry(Page);
-
-    ASSERT_IS_ROS_PFN(Pfn);
-
-    if (Pfn->PreviousLRU)
-    {
-        ASSERT(Pfn->PreviousLRU->NextLRU == Pfn);
-        Pfn->PreviousLRU->NextLRU = Pfn->NextLRU;
-    }
-    else
-    {
-        ASSERT(FirstUserLRUPfn == Pfn);
-        FirstUserLRUPfn = Pfn->NextLRU;
-    }
-
-    if (Pfn->NextLRU)
-    {
-        ASSERT(Pfn->NextLRU->PreviousLRU == Pfn);
-        Pfn->NextLRU->PreviousLRU = Pfn->PreviousLRU;
-    }
-    else
-    {
-        ASSERT(Pfn == LastUserLRUPfn);
-        LastUserLRUPfn = Pfn->PreviousLRU;
-    }
-
-    Pfn->PreviousLRU = Pfn->NextLRU = NULL;
-}
-
-PFN_NUMBER
-NTAPI
-MmGetLRUNextUserPage(PFN_NUMBER PreviousPage, BOOLEAN MoveToLast)
-{
-    PFN_NUMBER Page = 0;
-    KIRQL OldIrql;
-
-    /* Find the next user page */
-    OldIrql = MiAcquirePfnLock();
-
-    PMMPFN PreviousPfn = MiGetPfnEntry(PreviousPage);
-    PMMPFN NextPfn = PreviousPfn->NextLRU;
-
-    /*
-     * Move this one at the end of the list.
-     * It may be freed by MmDereferencePage below.
-     * If it's not, then it means it is still hanging in some process address space.
-     * This avoids paging-out e.g. ntdll early just because it's mapped first time.
-     */
-    if ((MoveToLast) && (MmGetReferenceCountPage(PreviousPage) > 1))
-    {
-        MmRemoveLRUUserPage(PreviousPage);
-        MmInsertLRULastUserPage(PreviousPage);
-    }
-
-    if (NextPfn)
-    {
-        Page = MiGetPfnEntryIndex(NextPfn);
-        MmReferencePage(Page);
-    }
-
-    MmDereferencePage(PreviousPage);
-
-    MiReleasePfnLock(OldIrql);
-
-    return Page;
-}
+/* FUNCTIONS **************************************************************/
 
 BOOLEAN
 NTAPI
@@ -577,19 +456,15 @@ MmDereferencePage(PFN_NUMBER Pfn)
     Pfn1->u3.e2.ReferenceCount--;
     if (Pfn1->u3.e2.ReferenceCount == 0)
     {
-        /* Apply LRU hack */
-        if (Pfn1->u4.MustBeCached)
-        {
-            MmRemoveLRUUserPage(Pfn);
-            Pfn1->u4.MustBeCached = 0;
-        }
-
         /* Mark the page temporarily as valid, we're going to make it free soon */
         Pfn1->u3.e1.PageLocation = ActiveAndValid;
 
         /* It's not a ROS PFN anymore */
         Pfn1->u4.AweAllocation = FALSE;
 
+        /* This should not be in any list */
+        ASSERT(Pfn1->LruEntry.Flink == NULL);
+
         /* Bring it back into the free list */
         DPRINT("Legacy free: %lx\n", Pfn);
         MiInsertPageInFreeList(Pfn);
@@ -638,15 +513,6 @@ MmAllocPage(ULONG Type)
     Pfn1->u1.SwapEntry = 0;
     Pfn1->RmapListHead = NULL;
 
-    Pfn1->NextLRU = NULL;
-    Pfn1->PreviousLRU = NULL;
-
-    if (Type == MC_USER)
-    {
-        Pfn1->u4.MustBeCached = 1; /* HACK again */
-        MmInsertLRULastUserPage(PfnOffset);
-    }
-
     MiReleasePfnLock(OldIrql);
     return PfnOffset;
 }
diff --git a/ntoskrnl/mm/i386/page.c b/ntoskrnl/mm/i386/page.c
index a9ba2eb1179..990361acc0c 100644
--- a/ntoskrnl/mm/i386/page.c
+++ b/ntoskrnl/mm/i386/page.c
@@ -109,11 +109,6 @@ ULONG MmProtectToValue[32] =
 
 /* FUNCTIONS ***************************************************************/
 
-NTSTATUS
-NTAPI
-MiFillSystemPageDirectory(IN PVOID Base,
-                          IN SIZE_T NumberOfBytes);
-
 static
 BOOLEAN
 MiIsPageTablePresent(PVOID Address)
@@ -191,29 +186,51 @@ MmGetPfnForProcess(PEPROCESS Process,
     PMMPTE PointerPte;
     PFN_NUMBER Page;
 
-    /* Must be called for user mode only */
-    ASSERT(Process != NULL);
-    ASSERT(Address < MmSystemRangeStart);
+    if (Process == NULL)
+    {
+        if (Address < MmSystemRangeStart)
+        {
+            DPRINT1("NULL process given for user-mode mapping at %p\n", Address);
+            KeBugCheck(MEMORY_MANAGEMENT);
+        }
+#if (_MI_PAGING_LEVELS == 2)
+        if (!MiSynchronizeSystemPde(MiAddressToPde(Address)))
+#else
+        if (!MiIsPdeForAddressValid(Address))
+#endif
+        {
+            return 0;
+        }
+    }
+    else
+    {
+        if (Address >= MmSystemRangeStart)
+        {
+            DPRINT1("Kernel space address %p given for process %p\n", Address, Process);
+            KeBugCheck(MEMORY_MANAGEMENT);
+        }
+        /* This must be our process */
+        ASSERT(Process == PsGetCurrentProcess());
 
-    /* And for our process */
-    ASSERT(Process == PsGetCurrentProcess());
+        /* Lock for reading */
+        MiLockProcessWorkingSetShared(Process, PsGetCurrentThread());
 
-    /* Lock for reading */
-    MiLockProcessWorkingSetShared(Process, PsGetCurrentThread());
+        if (!MiIsPageTablePresent(Address))
+        {
+            MiUnlockProcessWorkingSetShared(Process, PsGetCurrentThread());
+            return 0;
+        }
 
-    if (!MiIsPageTablePresent(Address))
-    {
-        MiUnlockProcessWorkingSetShared(Process, PsGetCurrentThread());
-        return 0;
+        /* Make sure we can read the PTE */
+        MiMakePdeExistAndMakeValid(MiAddressToPde(Address), Process, MM_NOIRQL);
     }
 
-    /* Make sure we can read the PTE */
-    MiMakePdeExistAndMakeValid(MiAddressToPde(Address), Process, MM_NOIRQL);
-
     PointerPte = MiAddressToPte(Address);
     Page = PointerPte->u.Hard.Valid ? PFN_FROM_PTE(PointerPte) : 0;
 
-    MiUnlockProcessWorkingSetShared(Process, PsGetCurrentThread());
+    if (Process)
+        MiUnlockProcessWorkingSetShared(Process, PsGetCurrentThread());
+
     return Page;
 }
 
@@ -815,14 +832,28 @@ MmSetDirtyBit(PEPROCESS Process, PVOID Address, BOOLEAN Bit)
     DPRINT("MmSetDirtyBit(Process %p  Address %p  Bit %x)\n",
            Process, Address, Bit);
 
-    ASSERT(Process != NULL);
-    ASSERT(Address < MmSystemRangeStart);
+    if (Address < MmSystemRangeStart)
+    {
+        ASSERT(Address < MmSystemRangeStart);
 
-    ASSERT(Process == PsGetCurrentProcess());
+        ASSERT(Process == PsGetCurrentProcess());
 
-    MiLockProcessWorkingSetUnsafe(Process, PsGetCurrentThread());
+        MiLockProcessWorkingSetUnsafe(Process, PsGetCurrentThread());
+
+        ASSERT(MiIsPageTablePresent(Address));
+
+        MiMakePdeExistAndMakeValid(MiAddressToPde(Address), Process, MM_NOIRQL);
+    }
+    else
+    {
+        ASSERT(Process == NULL);
+#if _MI_PAGING_LEVELS == 2
+        NT_VERIFY(MiSynchronizeSystemPde(MiAddressToPde(Address)));
+#else
+        ASSERT(MiIsPdeForAddressValid(Address));
+#endif
+    }
 
-    MiMakePdeExistAndMakeValid(MiAddressToPde(Address), Process, MM_NOIRQL);
 
     PointerPte = MiAddressToPte(Address);
     // We shouldnl't set dirty bit on non-mapped adresses
@@ -837,7 +868,8 @@ MmSetDirtyBit(PEPROCESS Process, PVOID Address, BOOLEAN Bit)
     if (!Bit)
         KeInvalidateTlbEntry(Address);
 
-    MiUnlockProcessWorkingSetUnsafe(Process, PsGetCurrentThread());
+    if (Address < MmSystemRangeStart)
+        MiUnlockProcessWorkingSetUnsafe(Process, PsGetCurrentThread());
 }
 
 CODE_SEG("INIT")
diff --git a/ntoskrnl/mm/mminit.c b/ntoskrnl/mm/mminit.c
index 3e58ad9bbc8..81515346456 100644
--- a/ntoskrnl/mm/mminit.c
+++ b/ntoskrnl/mm/mminit.c
@@ -233,7 +233,6 @@ MmInitSystem(IN ULONG Phase,
     MiDbgDumpAddressSpace();
 
     MmInitGlobalKernelPageDirectory();
-    MmInitializeMemoryConsumer(MC_USER, MmTrimUserMemory);
     MmInitializeRmapList();
     MmInitSectionImplementation();
     MmInitPagingFile();
diff --git a/ntoskrnl/mm/rmap.c b/ntoskrnl/mm/rmap.c
index e27e31de820..cb1f04c5b75 100644
--- a/ntoskrnl/mm/rmap.c
+++ b/ntoskrnl/mm/rmap.c
@@ -46,8 +46,14 @@ MmInitializeRmapList(VOID)
                                      50);
 }
 
+_IRQL_requires_max_(DISPATCH_LEVEL)
+VOID
+MmFreeRmap(_In_ __drv_freesMem(Mem) PMM_RMAP_ENTRY Rmap)
+{
+    ExFreeToNPagedLookasideList(&RmapLookasideList, Rmap);
+}
+
 NTSTATUS
-NTAPI
 MmPageOutPhysicalAddress(PFN_NUMBER Page)
 {
     PMM_RMAP_ENTRY entry;
@@ -56,11 +62,9 @@ MmPageOutPhysicalAddress(PFN_NUMBER Page)
     PVOID Address = NULL;
     PEPROCESS Process = NULL;
     NTSTATUS Status = STATUS_SUCCESS;
-    PMM_SECTION_SEGMENT Segment;
-    LARGE_INTEGER SegmentOffset;
     KIRQL OldIrql;
+    KAPC_STATE ApcState;
 
-GetEntry:
     OldIrql = MiAcquirePfnLock();
 
     entry = MmGetRmapListHeadPage(Page);
@@ -71,7 +75,8 @@ GetEntry:
     if (entry == NULL)
     {
         MiReleasePfnLock(OldIrql);
-        goto WriteSegment;
+        /* This page is not in any working set. Say we didn't do anything */
+        return STATUS_UNSUCCESSFUL;
     }
 
     Process = entry->Process;
@@ -82,23 +87,32 @@ GetEntry:
         KeBugCheck(MEMORY_MANAGEMENT);
     }
 
-    /* This is for user-mode address only */
-    ASSERT(Address < MmSystemRangeStart);
-
-    if (!ExAcquireRundownProtection(&Process->RundownProtect))
+    if (Process != NULL)
     {
-        MiReleasePfnLock(OldIrql);
-        return STATUS_PROCESS_IS_TERMINATING;
+        /* This is for user-mode address only */
+        if (Address >= MmSystemRangeStart)
+        {
+            DPRINT1("Got Kernel mode address to page out for process %p\n", Process);
+            KeBugCheck(MEMORY_MANAGEMENT);
+        }
+
+        if (!ExAcquireRundownProtection(&Process->RundownProtect))
+        {
+            MiReleasePfnLock(OldIrql);
+            return STATUS_PROCESS_IS_TERMINATING;
+        }
+
+        Status = ObReferenceObjectByPointer(Process, PROCESS_ALL_ACCESS, NULL, KernelMode);
     }
 
-    Status = ObReferenceObjectByPointer(Process, PROCESS_ALL_ACCESS, NULL, KernelMode);
     MiReleasePfnLock(OldIrql);
     if (!NT_SUCCESS(Status))
     {
-        ExReleaseRundownProtection(&Process->RundownProtect);
+        if (Process != NULL)
+            ExReleaseRundownProtection(&Process->RundownProtect);
         return Status;
     }
-    AddressSpace = &Process->Vm;
+    AddressSpace = Process ? &Process->Vm : MmGetKernelAddressSpace();
 
     MmLockAddressSpace(AddressSpace);
 
@@ -106,26 +120,31 @@ GetEntry:
     if (MemoryArea == NULL || MemoryArea->DeleteInProgress)
     {
         MmUnlockAddressSpace(AddressSpace);
-        ExReleaseRundownProtection(&Process->RundownProtect);
-        ObDereferenceObject(Process);
-        goto GetEntry;
+        if (Process)
+        {
+            ExReleaseRundownProtection(&Process->RundownProtect);
+            ObDereferenceObject(Process);
+        }
+        return STATUS_UNSUCCESSFUL;
     }
 
-
     /* Attach to it, if needed */
     ASSERT(PsGetCurrentProcess() == PsInitialSystemProcess);
-    if (Process != PsInitialSystemProcess)
-        KeAttachProcess(&Process->Pcb);
+    if ((Process != NULL) && (Process != PsInitialSystemProcess))
+        KeStackAttachProcess(&Process->Pcb, &ApcState);
 
     if (MmGetPfnForProcess(Process, Address) != Page)
     {
         /* This changed in the short window where we didn't have any locks */
-        if (Process != PsInitialSystemProcess)
-            KeDetachProcess();
+        if ((Process != NULL) && (Process != PsInitialSystemProcess))
+            KeUnstackDetachProcess(&ApcState);
         MmUnlockAddressSpace(AddressSpace);
-        ExReleaseRundownProtection(&Process->RundownProtect);
-        ObDereferenceObject(Process);
-        goto GetEntry;
+        if (Process != NULL)
+        {
+            ExReleaseRundownProtection(&Process->RundownProtect);
+            ObDereferenceObject(Process);
+        }
+        return STATUS_UNSUCCESSFUL;
     }
 
     if (MemoryArea->Type == MEMORY_AREA_SECTION_VIEW)
@@ -135,6 +154,7 @@ GetEntry:
         PFN_NUMBER MapPage;
         LARGE_INTEGER Offset;
         BOOLEAN Released;
+        PMM_SECTION_SEGMENT Segment;
 
         Offset.QuadPart = MemoryArea->SectionData.ViewOffset +
                  ((ULONG_PTR)Address - MA_GetStartingAddress(MemoryArea));
@@ -148,12 +168,17 @@ GetEntry:
         {
             /* The segment is being read or something. Give up */
             MmUnlockSectionSegment(Segment);
-            if (Process != PsInitialSystemProcess)
-                KeDetachProcess();
+            if ((Process != NULL) && (Process != PsInitialSystemProcess))
+                KeUnstackDetachProcess(&ApcState);
             MmUnlockAddressSpace(AddressSpace);
-            ExReleaseRundownProtection(&Process->RundownProtect);
-            ObDereferenceObject(Process);
-            return(STATUS_UNSUCCESSFUL);
+
+            if (Process != NULL)
+            {
+                ExReleaseRundownProtection(&Process->RundownProtect);
+                ObDereferenceObject(Process);
+            }
+
+            return STATUS_UNSUCCESSFUL;
         }
 
         /* Delete this virtual mapping in the process */
@@ -170,6 +195,9 @@ GetEntry:
             /* This page is private to the process */
             MmUnlockSectionSegment(Segment);
 
+            /* Only for user mode mappings */
+            ASSERT(Process != NULL);
+
             /* Check if we should write it back to the page file */
             SwapEntry = MmGetSavedSwapEntryPage(Page);
 
@@ -190,7 +218,7 @@ GetEntry:
 
                     MmUnlockAddressSpace(AddressSpace);
                     if (Process != PsInitialSystemProcess)
-                        KeDetachProcess();
+                        KeUnstackDetachProcess(&ApcState);
                     ExReleaseRundownProtection(&Process->RundownProtect);
                     ObDereferenceObject(Process);
 
@@ -230,7 +258,7 @@ GetEntry:
 
                     MmUnlockAddressSpace(AddressSpace);
                     if (Process != PsInitialSystemProcess)
-                        KeDetachProcess();
+                        KeUnstackDetachProcess(&ApcState);
                     ExReleaseRundownProtection(&Process->RundownProtect);
                     ObDereferenceObject(Process);
 
@@ -248,12 +276,13 @@ GetEntry:
             /* We can finally let this page go */
             MmUnlockAddressSpace(AddressSpace);
             if (Process != PsInitialSystemProcess)
-                KeDetachProcess();
+                KeUnstackDetachProcess(&ApcState);
 #if DBG
             OldIrql = MiAcquirePfnLock();
             ASSERT(MmGetRmapListHeadPage(Page) == NULL);
             MiReleasePfnLock(OldIrql);
 #endif
+            MmRemoveLRUUserPage(Page);
             MmReleasePageMemoryConsumer(MC_USER, Page);
 
             ExReleaseRundownProtection(&Process->RundownProtect);
@@ -263,17 +292,20 @@ GetEntry:
         }
 
         /* One less mapping referencing this segment */
-        Released = MmUnsharePageEntrySectionSegment(MemoryArea, Segment, &Offset, Dirty, TRUE, NULL);
+        Released = MmUnsharePageEntrySectionSegment(Segment, &Offset, Dirty, TRUE);
 
         MmUnlockSectionSegment(Segment);
-        if (Process != PsInitialSystemProcess)
-            KeDetachProcess();
+        if ((Process != NULL) && (Process != PsInitialSystemProcess))
+            KeUnstackDetachProcess(&ApcState);
         MmUnlockAddressSpace(AddressSpace);
 
-        ExReleaseRundownProtection(&Process->RundownProtect);
-        ObDereferenceObject(Process);
+        if (Process != NULL)
+        {
+            ExReleaseRundownProtection(&Process->RundownProtect);
+            ObDereferenceObject(Process);
+        }
 
-        if (Released) return STATUS_SUCCESS;
+        return Released ? STATUS_SUCCESS : STATUS_UNSUCCESSFUL;
     }
 #ifdef NEWCC
     else if (Type == MEMORY_AREA_CACHE)
@@ -288,26 +320,6 @@ GetEntry:
         KeBugCheck(MEMORY_MANAGEMENT);
     }
 
-WriteSegment:
-    /* Now write this page to file, if needed */
-    Segment = MmGetSectionAssociation(Page, &SegmentOffset);
-    if (Segment)
-    {
-        BOOLEAN Released;
-
-        MmLockSectionSegment(Segment);
-
-        Released = MmCheckDirtySegment(Segment, &SegmentOffset, FALSE, TRUE);
-
-        MmUnlockSectionSegment(Segment);
-        MmDereferenceSegment(Segment);
-
-        if (Released)
-        {
-            return STATUS_SUCCESS;
-        }
-    }
-
     /* If we are here, then we didn't release the page */
     return STATUS_UNSUCCESSFUL;
 }
@@ -317,8 +329,7 @@ NTAPI
 MmInsertRmap(PFN_NUMBER Page, PEPROCESS Process,
              PVOID Address)
 {
-    PMM_RMAP_ENTRY current_entry;
-    PMM_RMAP_ENTRY new_entry;
+    PMM_RMAP_ENTRY previous_entry, new_entry;
     ULONG PrevSize;
     KIRQL OldIrql;
 
@@ -332,6 +343,7 @@ MmInsertRmap(PFN_NUMBER Page, PEPROCESS Process,
     }
     new_entry->Address = Address;
     new_entry->Process = (PEPROCESS)Process;
+    new_entry->Next = NULL;
 #if DBG
     new_entry->Caller = _ReturnAddress();
 #endif
@@ -349,47 +361,40 @@ MmInsertRmap(PFN_NUMBER Page, PEPROCESS Process,
     }
 
     OldIrql = MiAcquirePfnLock();
-    current_entry = MmGetRmapListHeadPage(Page);
+    previous_entry = MmGetRmapListHeadPage(Page);
 
-    PMM_RMAP_ENTRY previous_entry = NULL;
-    /* Keep the list sorted */
-    while (current_entry && (current_entry->Address < Address))
+    /* Put it at the end of the list so this isn't paged out immediately. */
+    if (previous_entry != NULL)
     {
-        previous_entry = current_entry;
-        current_entry = current_entry->Next;
-    }
-
-    /* In case of clash in the address, sort by process */
-    if (current_entry && (current_entry->Address == Address))
-    {
-        while (current_entry && (current_entry->Process < Process))
+        while (previous_entry->Next != NULL)
         {
-            previous_entry = current_entry;
-            current_entry = current_entry->Next;
+            if ((previous_entry->Process == Process) && (previous_entry->Address == Address))
+            {
+                ASSERT(previous_entry->Process != Process);
+                ASSERT(previous_entry->Address != Address);
+                KeBugCheck(MEMORY_MANAGEMENT);
+            }
+            previous_entry = previous_entry->Next;
         }
-    }
 
-    if (current_entry && (current_entry->Address == Address) && (current_entry->Process == Process))
-    {
-#if DBG
-        DbgPrint("MmInsertRmap tries to add a second rmap entry for address %p\n", current_entry->Address);
-        DbgPrint("    current caller  %p\n", new_entry->Caller);
-        DbgPrint("    previous caller %p\n", current_entry->Caller);
-#endif
-        KeBugCheck(MEMORY_MANAGEMENT);
-    }
+        if ((previous_entry->Process == Process) && (previous_entry->Address == Address))
+        {
+            ASSERT(previous_entry->Process != Process);
+            ASSERT(previous_entry->Address != Address);
+            KeBugCheck(MEMORY_MANAGEMENT);
+        }
 
-    new_entry->Next = current_entry;
-    if (previous_entry)
         previous_entry->Next = new_entry;
+    }
     else
+    {
         MmSetRmapListHeadPage(Page, new_entry);
+    }
 
     MiReleasePfnLock(OldIrql);
 
-    if (!RMAP_IS_SEGMENT(Address))
+    if (!RMAP_IS_SEGMENT(Address) && (Process != NULL))
     {
-        ASSERT(Process != NULL);
         PrevSize = InterlockedExchangeAddUL(&Process->Vm.WorkingSetSize, PAGE_SIZE);
         if (PrevSize >= Process->Vm.PeakWorkingSetSize)
         {
@@ -426,9 +431,8 @@ MmDeleteRmap(PFN_NUMBER Page, PEPROCESS Process,
             MiReleasePfnLock(OldIrql);
 
             ExFreeToNPagedLookasideList(&RmapLookasideList, current_entry);
-            if (!RMAP_IS_SEGMENT(Address))
+            if (!RMAP_IS_SEGMENT(Address) && (Process != NULL))
             {
-                ASSERT(Process != NULL);
                 (void)InterlockedExchangeAddUL(&Process->Vm.WorkingSetSize, -PAGE_SIZE);
             }
             return;
@@ -501,6 +505,9 @@ MmDeleteSectionAssociation(PFN_NUMBER Page)
     current_entry = MmGetRmapListHeadPage(Page);
     while (current_entry != NULL)
     {
+        /* We should be out of any list */
+        ASSERT(MiGetPfnEntry(Page)->LruEntry.Flink == NULL);
+
         if (RMAP_IS_SEGMENT(current_entry->Address))
         {
             if (previous_entry == NULL)
diff --git a/ntoskrnl/mm/section.c b/ntoskrnl/mm/section.c
index 44b5710f6f4..1e65ea98069 100644
--- a/ntoskrnl/mm/section.c
+++ b/ntoskrnl/mm/section.c
@@ -71,7 +71,7 @@ NTAPI
 _MmLockSectionSegment(PMM_SECTION_SEGMENT Segment, const char *file, int line)
 {
     //DPRINT("MmLockSectionSegment(%p,%s:%d)\n", Segment, file, line);
-    ExAcquireFastMutex(&Segment->Lock);
+    ExAcquirePushLockExclusive(&Segment->Lock);
     Segment->Locked = TRUE;
 }
 
@@ -81,7 +81,7 @@ _MmUnlockSectionSegment(PMM_SECTION_SEGMENT Segment, const char *file, int line)
 {
     ASSERT(Segment->Locked);
     Segment->Locked = FALSE;
-    ExReleaseFastMutex(&Segment->Lock);
+    ExReleasePushLockExclusive(&Segment->Lock);
     //DPRINT("MmUnlockSectionSegment(%p,%s:%d)\n", Segment, file, line);
 }
 #endif
@@ -948,6 +948,10 @@ MmpFreePageFileSegment(PMM_SECTION_SEGMENT Segment)
                     MmSetSavedSwapEntryPage(Page, 0);
                     MmFreeSwapPage(SavedSwapEntry);
                 }
+                if (IS_DIRTY_SSE(Entry))
+                    MmRemoveLRUModifiedPage(Page);
+                else
+                    MmRemoveLRUStandbyPage(Page);
                 MmReleasePageMemoryConsumer(MC_USER, Page);
             }
         }
@@ -982,7 +986,16 @@ FreeSegmentPage(PMM_SECTION_SEGMENT Segment, PLARGE_INTEGER Offset)
 
     /* Write the page */
     if (IS_DIRTY_SSE(Entry))
+    {
+        DPRINT1("Writing page at offset 0x%I64x for file %wZ\n",
+                Offset->QuadPart, &Segment->FileObject->FileName);
         MiWritePage(Segment, Offset->QuadPart, Page);
+        MmRemoveLRUModifiedPage(Page);
+    }
+    else
+    {
+        MmRemoveLRUStandbyPage(Page);
+    }
 
     MmReleasePageMemoryConsumer(MC_USER, Page);
 }
@@ -1083,19 +1096,29 @@ MmSharePageEntrySectionSegment(PMM_SECTION_SEGMENT Segment,
     {
         KeBugCheck(MEMORY_MANAGEMENT);
     }
+
+    /* Move list, if needed */
+    if (SHARE_COUNT_FROM_SSE(Entry) == 0)
+    {
+        PFN_NUMBER Page = PFN_FROM_SSE(Entry);
+        if (IS_DIRTY_SSE(Entry))
+            MmRemoveLRUModifiedPage(Page);
+        else
+            MmRemoveLRUStandbyPage(Page);
+        MmInsertLRULastUserPage(Page);
+    }
+
     MmSetPageEntrySectionSegment(Segment, Offset, BUMPREF_SSE(Entry));
 }
 
 BOOLEAN
 NTAPI
-MmUnsharePageEntrySectionSegment(PMEMORY_AREA MemoryArea,
-                                 PMM_SECTION_SEGMENT Segment,
+MmUnsharePageEntrySectionSegment(PMM_SECTION_SEGMENT Segment,
                                  PLARGE_INTEGER Offset,
                                  BOOLEAN Dirty,
-                                 BOOLEAN PageOut,
-                                 ULONG_PTR *InEntry)
+                                 BOOLEAN PageOut)
 {
-    ULONG_PTR Entry = InEntry ? *InEntry : MmGetPageEntrySectionSegment(Segment, Offset);
+    ULONG_PTR Entry = MmGetPageEntrySectionSegment(Segment, Offset);
     PFN_NUMBER Page = PFN_FROM_SSE(Entry);
     BOOLEAN IsDataMap = BooleanFlagOn(*Segment->Flags, MM_DATAFILE_SEGMENT);
     SWAPENTRY SwapEntry;
@@ -1117,32 +1140,50 @@ MmUnsharePageEntrySectionSegment(PMEMORY_AREA MemoryArea,
     Entry = DECREF_SSE(Entry);
     if (Dirty) Entry = DIRTY_SSE(Entry);
 
-    /* If we are paging-out, pruning the page for real will be taken care of in MmCheckDirtySegment */
-    if ((SHARE_COUNT_FROM_SSE(Entry) > 0) || PageOut)
+    /* Check if we should keep it. */
+    if ((SHARE_COUNT_FROM_SSE(Entry) > 0) || PageOut || IsDataMap)
     {
-        /* Update the page mapping in the segment and we're done */
-        MmSetPageEntrySectionSegment(Segment, Offset, Entry);
-        return FALSE;
-    }
+        if (SHARE_COUNT_FROM_SSE(Entry) == 0)
+        {
+            /* If we're paging out, we already removed it from the list */
+            MmRemoveLRUUserPage(Page);
 
-    /* We are pruning the last mapping on this page. See if we can keep it a bit more. */
-    ASSERT(!PageOut);
+            if (IS_DIRTY_SSE(Entry))
+            {
+                MmInsertLRULastModifiedPage(Page);
+                /* If we're not in page out path, we're unmapping. Flush to disk */
+                if (!PageOut)
+                {
+                    MmCheckDirtySegment(Segment, Offset, FALSE);
+                }
+            }
+            else
+            {
+                MmInsertLRULastStandbyPage(Page);
+            }
+        }
 
-    if (IsDataMap)
-    {
-        /* We can always keep memory in for data maps */
+        /* Update the page mapping in the segment and we're done */
         MmSetPageEntrySectionSegment(Segment, Offset, Entry);
-        return FALSE;
+
+        /* Tell page-out code path we're not using it anymore */
+        return (SHARE_COUNT_FROM_SSE(Entry) == 0);
     }
 
+    /* Whatever happens, this is not in any working set anymore */
+    MmRemoveLRUUserPage(Page);
+
     if (!FlagOn(Segment->Image.Characteristics, IMAGE_SCN_MEM_SHARED))
     {
         ASSERT(Segment->WriteCopy);
         ASSERT(!IS_DIRTY_SSE(Entry));
         ASSERT(MmGetSavedSwapEntryPage(Page) == 0);
         /* So this must have been a read-only page. Keep it ! */
+        MmInsertLRULastStandbyPage(Page);
         MmSetPageEntrySectionSegment(Segment, Offset, Entry);
-        return FALSE;
+
+        /* Tell caller we're not using it anymore */
+        return TRUE;
     }
 
     /*
@@ -1152,8 +1193,11 @@ MmUnsharePageEntrySectionSegment(PMEMORY_AREA MemoryArea,
     SwapEntry = MmGetSavedSwapEntryPage(Page);
     if ((SwapEntry == 0) && !IS_DIRTY_SSE(Entry))
     {
+        MmInsertLRULastStandbyPage(Page);
         MmSetPageEntrySectionSegment(Segment, Offset, Entry);
-        return FALSE;
+
+        /* Tell caller we're not using it anymore */
+        return TRUE;
     }
 
     /* No more processes are referencing this shared dirty page. Ditch it. */
@@ -1162,8 +1206,11 @@ MmUnsharePageEntrySectionSegment(PMEMORY_AREA MemoryArea,
         MmSetSavedSwapEntryPage(Page, 0);
         MmFreeSwapPage(SwapEntry);
     }
+
     MmSetPageEntrySectionSegment(Segment, Offset, 0);
     MmReleasePageMemoryConsumer(MC_USER, Page);
+
+    /* Tell caller we're not using it anymore */
     return TRUE;
 }
 
@@ -1190,13 +1237,11 @@ MiCopyFromUserPage(PFN_NUMBER DestPage, const VOID *SrcAddress)
 
 static
 NTSTATUS
-NTAPI
 MmMakeSegmentResident(
     _In_ PMM_SECTION_SEGMENT Segment,
     _In_ LONGLONG Offset,
     _In_ ULONG Length,
-    _In_opt_ PLARGE_INTEGER ValidDataLength,
-    _In_ BOOLEAN SetDirty)
+    _In_opt_ PLARGE_INTEGER ValidDataLength)
 {
     /* Let's use a 64K granularity. */
     LONGLONG RangeStart, RangeEnd;
@@ -1263,9 +1308,6 @@ MmMakeSegmentResident(
 
             if (Entry != 0)
             {
-                /* Dirtify it if it's a resident page and we're asked to */
-                if (SetDirty && !IS_SWAP_FROM_SSE(Entry))
-                    MmSetPageEntrySectionSegment(Segment, &CurrentOffset, DIRTY_SSE(Entry));
                 continue;
             }
 
@@ -1337,7 +1379,7 @@ MmMakeSegmentResident(
             for (UINT i = 0; i < BYTES_TO_PAGES(ReadLength); i++)
             {
                 /* MmRequestPageMemoryConsumer succeeds or bugchecks */
-                (void)MmRequestPageMemoryConsumer(MC_USER, FALSE, &Pages[i]);
+                (void)MmRequestPageMemoryConsumer(MC_USER, TRUE, &Pages[i]);
             }
             Mdl->MdlFlags |= MDL_PAGES_LOCKED | MDL_IO_PAGE_READ;
 
@@ -1347,13 +1389,20 @@ MmMakeSegmentResident(
             /* Clamp to VDL */
             if (ValidDataLength && ((FileOffset.QuadPart + ReadLength) > ValidDataLength->QuadPart))
             {
-                if (FileOffset.QuadPart > ValidDataLength->QuadPart)
+                if (FileOffset.QuadPart >= ValidDataLength->QuadPart)
                 {
+                    DPRINT("Skipping read beyond VDL\n");
                     /* Great, nothing to read. */
                     goto AssignPagesToSegment;
                 }
 
-                Mdl->Size = (FileOffset.QuadPart + ReadLength) - ValidDataLength->QuadPart;
+                Mdl->ByteCount = ValidDataLength->QuadPart - FileOffset.QuadPart;
+
+                // Mdl->ByteCount = PAGE_ROUND_UP(Mdl->ByteCount);
+                ASSERT(Mdl->ByteCount > 0);
+                ASSERT(Mdl->ByteCount <= ReadLength);
+                ASSERT(Mdl->ByteCount <= ValidDataLength->QuadPart);
+                DPRINT("Clamping read of %wZ from %x to %x\n", &FileObject->FileName, ReadLength, Mdl->ByteCount);
             }
 
             KEVENT Event;
@@ -1367,6 +1416,7 @@ MmMakeSegmentResident(
             Status = IoPageRead(FileObject, Mdl, &FileOffset, &Event, &Iosb);
             if (Status == STATUS_PENDING)
             {
+                DPRINT1("Pending!\n");
                 KeWaitForSingleObject(&Event, WrPageIn, KernelMode, FALSE, NULL);
                 Status = Iosb.Status;
             }
@@ -1419,8 +1469,10 @@ AssignPagesToSegment:
 
                 ASSERT(MM_IS_WAIT_PTE(MmGetPageEntrySectionSegment(Segment, &CurrentOffset)));
 
-                if (SetDirty)
-                    Entry = DIRTY_SSE(Entry);
+                MmInsertLRULastStandbyPage(Pages[i]);
+
+                DPRINT("Read data from file %wZ, Offset %llx, page %lx\n",
+                       &Segment->FileObject->FileName, CurrentOffset.QuadPart, Pages[i]);
 
                 MmSetPageEntrySectionSegment(Segment, &CurrentOffset, Entry);
             }
@@ -1521,6 +1573,47 @@ MmAlterViewAttributes(PMMSUPPORT AddressSpace,
     MmUnlockSectionSegment(Segment);
 }
 
+VOID
+NTAPI
+MiCopyPfnPartial(
+    _In_ PFN_NUMBER DestPage,
+    _In_ PFN_NUMBER SrcPage,
+    _In_ ULONG Length)
+{
+    PMMPTE SysPtes;
+    MMPTE TempPte;
+    PVOID DestAddress;
+    const VOID* SrcAddress;
+
+    ASSERT(Length <= PAGE_SIZE);
+
+    /* Grab 2 system PTEs */
+    SysPtes = MiReserveSystemPtes(2, SystemPteSpace);
+    ASSERT(SysPtes);
+
+    /* Initialize the destination PTE */
+    TempPte = ValidKernelPte;
+    TempPte.u.Hard.PageFrameNumber = DestPage;
+
+    /* Make the system PTE valid with our PFN */
+    MI_WRITE_VALID_PTE(&SysPtes[0], TempPte);
+
+    /* Initialize the source PTE */
+    TempPte = ValidKernelPte;
+    TempPte.u.Hard.PageFrameNumber = SrcPage;
+
+    /* Make the system PTE valid with our PFN */
+    MI_WRITE_VALID_PTE(&SysPtes[1], TempPte);
+
+    /* Get the addresses and perform the copy */
+    DestAddress = MiPteToAddress(&SysPtes[0]);
+    SrcAddress = MiPteToAddress(&SysPtes[1]);
+    RtlCopyMemory(DestAddress, SrcAddress, Length);
+
+    /* Now get rid of it */
+    MiReleaseSystemPtes(SysPtes, 2, SystemPteSpace);
+}
+
 NTSTATUS
 NTAPI
 MmNotPresentFaultSectionView(PMMSUPPORT AddressSpace,
@@ -1665,9 +1758,12 @@ MmNotPresentFaultSectionView(PMMSUPPORT AddressSpace,
         MmSetSavedSwapEntryPage(Page, SwapEntry);
 
         /*
-         * Add the page to the process's working set
+         * Add the page to the process's working set. No COW for kernel.
          */
-        if (Process) MmInsertRmap(Page, Process, Address);
+        ASSERT(Process != NULL);
+        MmInsertRmap(Page, Process, Address);
+        MmInsertLRULastUserPage(Page);
+
         /*
          * Finish the operation
          */
@@ -1739,6 +1835,7 @@ MmNotPresentFaultSectionView(PMMSUPPORT AddressSpace,
             if (!Process) MI_SET_PROCESS2("Kernel Section");
             MmRequestPageMemoryConsumer(MC_USER, FALSE, &Page);
             MmSetPageEntrySectionSegment(Segment, &Offset, MAKE_SSE(Page << PAGE_SHIFT, 1));
+            MmInsertLRULastUserPage(Page);
             MmUnlockSectionSegment(Segment);
 
             Status = MmCreateVirtualMapping(Process, PAddress, Attributes, Page);
@@ -1748,13 +1845,15 @@ MmNotPresentFaultSectionView(PMMSUPPORT AddressSpace,
                 KeBugCheck(MEMORY_MANAGEMENT);
             }
             ASSERT(MmIsPagePresent(Process, PAddress));
-            if (Process)
-                MmInsertRmap(Page, Process, Address);
+            MmInsertRmap(Page, Process, Address);
 
             DPRINT("Address 0x%p\n", Address);
             return STATUS_SUCCESS;
         }
 
+        /*
+         * We need to load the page. Release all lock before goin into FS.
+         */
         MmUnlockSectionSegment(Segment);
         MmUnlockAddressSpace(AddressSpace);
 
@@ -1763,7 +1862,7 @@ MmNotPresentFaultSectionView(PMMSUPPORT AddressSpace,
 
         PFSRTL_COMMON_FCB_HEADER FcbHeader = Segment->FileObject->FsContext;
 
-        Status = MmMakeSegmentResident(Segment, Offset.QuadPart, PAGE_SIZE, &FcbHeader->ValidDataLength, FALSE);
+        Status = MmMakeSegmentResident(Segment, Offset.QuadPart, PAGE_SIZE, &FcbHeader->ValidDataLength);
 
         FsRtlReleaseFile(Segment->FileObject);
 
@@ -1779,7 +1878,8 @@ MmNotPresentFaultSectionView(PMMSUPPORT AddressSpace,
         /* Everything went fine. Restart the operation */
         return STATUS_MM_RESTART_OPERATION;
     }
-    else if (IS_SWAP_FROM_SSE(Entry))
+
+    if (IS_SWAP_FROM_SSE(Entry))
     {
         SWAPENTRY SwapEntry;
 
@@ -1846,45 +1946,41 @@ MmNotPresentFaultSectionView(PMMSUPPORT AddressSpace,
             DPRINT1("Unable to create virtual mapping\n");
             KeBugCheck(MEMORY_MANAGEMENT);
         }
-        if (Process)
-            MmInsertRmap(Page, Process, Address);
+        MmInsertRmap(Page, Process, Address);
 
         /*
          * Mark the offset within the section as having valid, in-memory
-         * data
+         * data, user data.
          */
         Entry = MAKE_SSE(Page << PAGE_SHIFT, 1);
         MmSetPageEntrySectionSegment(Segment, &Offset, Entry);
+        MmInsertLRULastUserPage(Page);
         MmUnlockSectionSegment(Segment);
 
         DPRINT("Address 0x%p\n", Address);
         return STATUS_SUCCESS;
     }
-    else
-    {
-        /* We already have a page on this section offset. Map it into the process address space. */
-        Page = PFN_FROM_SSE(Entry);
+    /* We already have a page on this section offset. Map it into the process address space. */
+    Page = PFN_FROM_SSE(Entry);
 
-        Status = MmCreateVirtualMapping(Process,
-                                        PAddress,
-                                        Attributes,
-                                        Page);
-        if (!NT_SUCCESS(Status))
-        {
-            DPRINT1("Unable to create virtual mapping\n");
-            KeBugCheck(MEMORY_MANAGEMENT);
-        }
+    Status = MmCreateVirtualMapping(Process,
+                                    PAddress,
+                                    Attributes,
+                                    Page);
+    if (!NT_SUCCESS(Status))
+    {
+        DPRINT1("Unable to create virtual mapping\n");
+        KeBugCheck(MEMORY_MANAGEMENT);
+    }
 
-        if (Process)
-            MmInsertRmap(Page, Process, Address);
+    MmInsertRmap(Page, Process, Address);
 
-        /* Take a reference on it */
-        MmSharePageEntrySectionSegment(Segment, &Offset);
-        MmUnlockSectionSegment(Segment);
+    /* Take a reference on it */
+    MmSharePageEntrySectionSegment(Segment, &Offset);
+    MmUnlockSectionSegment(Segment);
 
-        DPRINT("Address 0x%p\n", Address);
-        return STATUS_SUCCESS;
-    }
+    DPRINT("Address 0x%p\n", Address);
+    return STATUS_SUCCESS;
 }
 
 NTSTATUS
@@ -1932,6 +2028,7 @@ MmAccessFaultSectionView(PMMSUPPORT AddressSpace,
     if (MmGetPageProtect(Process, Address) & (PAGE_READWRITE | PAGE_EXECUTE_READWRITE))
     {
         DPRINT("Address 0x%p\n", Address);
+        MmSetDirtyPage(Process, Address);
         return STATUS_SUCCESS;
     }
 
@@ -1943,6 +2040,7 @@ MmAccessFaultSectionView(PMMSUPPORT AddressSpace,
     {
         /* Simply update page protection and we're done */
         MmSetPageProtect(Process, Address, Region->Protect);
+        MmSetDirtyPage(Process, Address);
         return STATUS_SUCCESS;
     }
 
@@ -1983,13 +2081,14 @@ MmAccessFaultSectionView(PMMSUPPORT AddressSpace,
         MmUnlockSectionSegment(Segment);
         /* This is a private page. We must only change the page protection. */
         MmSetPageProtect(Process, PAddress, NewProtect);
+        MmSetDirtyPage(Process, Address);
         return STATUS_SUCCESS;
     }
 
     /*
      * Allocate a page
      */
-    if (!NT_SUCCESS(MmRequestPageMemoryConsumer(MC_USER, TRUE, &NewPage)))
+    if (!NT_SUCCESS(MmRequestPageMemoryConsumer(MC_USER, FALSE, &NewPage)))
     {
         KeBugCheck(MEMORY_MANAGEMENT);
     }
@@ -2004,9 +2103,8 @@ MmAccessFaultSectionView(PMMSUPPORT AddressSpace,
      */
     DPRINT("Swapping page (Old %x New %x)\n", OldPage, NewPage);
     MmDeleteVirtualMapping(Process, PAddress, NULL, NULL);
-    if (Process)
-        MmDeleteRmap(OldPage, Process, PAddress);
-    MmUnsharePageEntrySectionSegment(MemoryArea, Segment, &Offset, FALSE, FALSE, NULL);
+    MmDeleteRmap(OldPage, Process, PAddress);
+    MmUnsharePageEntrySectionSegment(Segment, &Offset, FALSE, FALSE);
     MmUnlockSectionSegment(Segment);
 
     /*
@@ -2018,8 +2116,12 @@ MmAccessFaultSectionView(PMMSUPPORT AddressSpace,
         KeBugCheck(MEMORY_MANAGEMENT);
     }
 
-    if (Process)
-        MmInsertRmap(NewPage, Process, PAddress);
+    /* No Copy-On-Write for kernel file mappings */
+    ASSERT(Process != NULL);
+    MmInsertRmap(NewPage, Process, PAddress);
+    MmInsertLRULastUserPage(NewPage);
+
+    MmSetDirtyPage(Process, PAddress);
 
     DPRINT("Address 0x%p\n", Address);
     return STATUS_SUCCESS;
@@ -2228,7 +2330,7 @@ MmCreatePhysicalMemorySection(VOID)
     Segment->ReferenceCount = &Segment->RefCount;
     Segment->Flags = &Segment->SegFlags;
 
-    ExInitializeFastMutex(&Segment->Lock);
+    ExInitializePushLock(&Segment->Lock);
     Segment->Image.FileOffset = 0;
     Segment->Protection = PAGE_EXECUTE_READWRITE;
     Segment->RawLength = SectionSize;
@@ -2348,18 +2450,10 @@ MmCreateDataFileSection(PSECTION *SectionObject,
     }
     else
     {
-        LARGE_INTEGER FileSize;
-        Status = FsRtlGetFileSize(FileObject, &FileSize);
-        if (!NT_SUCCESS(Status))
-        {
-            ObDereferenceObject(Section);
-            return Status;
-        }
+        /* We can read the FCB header directly, since we locked the file */
+        PFSRTL_COMMON_FCB_HEADER FcbHeader = FileObject->FsContext;
+        LARGE_INTEGER FileSize = FcbHeader->FileSize;
 
-        /*
-         * FIXME: Revise this once a locking order for file size changes is
-         * decided
-         */
         if ((UMaximumSize != NULL) && (UMaximumSize->QuadPart != 0))
         {
             MaximumSize = *UMaximumSize;
@@ -2375,16 +2469,24 @@ MmCreateDataFileSection(PSECTION *SectionObject,
             }
         }
 
-        if (MaximumSize.QuadPart > FileSize.QuadPart)
+        /*
+         * Check if we must update File Information.
+         * Do not do this if we're not actually writing anything.
+         */
+        if ((SectionPageProtection == PAGE_READWRITE)
+            || (SectionPageProtection == PAGE_EXECUTE_READWRITE))
         {
-            Status = IoSetInformation(FileObject,
-                                      FileEndOfFileInformation,
-                                      sizeof(LARGE_INTEGER),
-                                      &MaximumSize);
-            if (!NT_SUCCESS(Status))
+            if (MaximumSize.QuadPart > FileSize.QuadPart)
             {
-                ObDereferenceObject(Section);
-                return STATUS_SECTION_NOT_EXTENDED;
+                Status = IoSetInformation(FileObject,
+                                          FileEndOfFileInformation,
+                                          sizeof(LARGE_INTEGER),
+                                          &MaximumSize);
+                if (!NT_SUCCESS(Status))
+                {
+                    ObDereferenceObject(Section);
+                    return STATUS_SECTION_NOT_EXTENDED;
+                }
             }
         }
     }
@@ -2465,7 +2567,7 @@ grab_segment:
 
         Segment->SectionCount = 1;
 
-        ExInitializeFastMutex(&Segment->Lock);
+        ExInitializePushLock(&Segment->Lock);
         Segment->FileObject = FileObject;
         ObReferenceObject(FileObject);
 
@@ -2586,10 +2688,11 @@ ExeFmtpReadFile(IN PVOID File,
     ULONG AdjustOffset;
     ULONG OffsetAdjustment;
     ULONG BufferSize;
-    ULONG UsedSize;
+    ULONG UsedSize = 0;
     PVOID Buffer;
     PFILE_OBJECT FileObject = File;
     IO_STATUS_BLOCK Iosb;
+    PMM_SECTION_SEGMENT DataFileSegment;
 
     ASSERT_IRQL_LESS(DISPATCH_LEVEL);
 
@@ -2613,18 +2716,91 @@ ExeFmtpReadFile(IN PVOID File,
     BufferSize = Length + OffsetAdjustment;
     BufferSize = PAGE_ROUND_UP(BufferSize);
 
-    /*
-     * It's ok to use paged pool, because this is a temporary buffer only used in
-     * the loading of executables. The assumption is that MmCreateSection is
-     * always called at low IRQLs and that these buffers don't survive a brief
-     * initialization phase
-     */
-    Buffer = ExAllocatePoolWithTag(PagedPool, BufferSize, 'rXmM');
+    /* Use Non-Paged pool because we might copy at high IRQL */
+    Buffer = ExAllocatePoolWithTag(NonPagedPool, BufferSize, 'rXmM');
     if (!Buffer)
     {
         return STATUS_INSUFFICIENT_RESOURCES;
     }
 
+    /* Set this now because Buffer will move */
+    *AllocBase = Buffer;
+
+    /* See if we can use the data mapping. */
+    DataFileSegment = MiGrabDataSection(FileObject->SectionObjectPointer);
+    if (DataFileSegment != NULL)
+    {
+        while (TRUE)
+        {
+            /* Page the data in. Lock the file, so that the VDL doesn't get updated behind us. */
+            FsRtlAcquireFileExclusive(DataFileSegment->FileObject);
+
+            PFSRTL_COMMON_FCB_HEADER FcbHeader = DataFileSegment->FileObject->FsContext;
+
+            Status = MmMakeSegmentResident(DataFileSegment, FileOffset.QuadPart, BufferSize, &FcbHeader->ValidDataLength);
+
+            FsRtlReleaseFile(DataFileSegment->FileObject);
+
+            if (!NT_SUCCESS(Status))
+            {
+                goto Exit;
+            }
+
+            /* Now we can copy the paged in data to our buffer */
+            MmLockSectionSegment(DataFileSegment);
+            while (BufferSize)
+            {
+                KIRQL OldIrql;
+                PVOID PageMap;
+                ULONG_PTR Entry;
+
+                while (TRUE)
+                {
+                    Entry = MmGetPageEntrySectionSegment(DataFileSegment, &FileOffset);
+
+                    if (!IS_SWAP_FROM_SSE(Entry))
+                        break;
+
+                    MmUnlockSectionSegment(DataFileSegment);
+                    KeDelayExecutionThread(KernelMode, FALSE, &TinyTime);
+                    MmLockSectionSegment(DataFileSegment);
+                }
+
+                if (Entry == 0)
+                {
+                    /* Geez. Already paged out. */
+                    break;
+                }
+
+                PageMap = MiMapPageInHyperSpace(PsGetCurrentProcess(), PFN_FROM_SSE(Entry), &OldIrql);
+                if (PageMap == NULL)
+                {
+                    MmUnlockSectionSegment(DataFileSegment);
+                    Status = STATUS_NO_MEMORY;
+                    goto Exit;
+                }
+
+                RtlCopyMemory(Buffer, PageMap, PAGE_SIZE);
+                MiUnmapPageInHyperSpace(PsGetCurrentProcess(), PageMap, OldIrql);
+
+                UsedSize += PAGE_SIZE;
+                Buffer = Add2Ptr(Buffer, PAGE_SIZE);
+                FileOffset.QuadPart += PAGE_SIZE;
+                BufferSize -= PAGE_SIZE;
+            }
+
+            MmUnlockSectionSegment(DataFileSegment);
+
+            /* Are we done yet */
+            if (BufferSize == 0)
+            {
+                Status = STATUS_SUCCESS;
+                goto Exit;
+            }
+        }
+    }
+
+    /* We couldn't get data from data segment. Get it from file directly */
     Status = MiSimpleRead(FileObject, &FileOffset, Buffer, BufferSize, TRUE, &Iosb);
 
     UsedSize = (ULONG)Iosb.Information;
@@ -2635,15 +2811,21 @@ ExeFmtpReadFile(IN PVOID File,
         ASSERT(!NT_SUCCESS(Status));
     }
 
+Exit:
+    if (DataFileSegment != NULL)
+    {
+        MmDereferenceSegment(DataFileSegment);
+    }
+
     if(NT_SUCCESS(Status))
     {
-        *Data = (PVOID)((ULONG_PTR)Buffer + OffsetAdjustment);
-        *AllocBase = Buffer;
+        *Data = Add2Ptr(*AllocBase, OffsetAdjustment);
         *ReadSize = UsedSize - OffsetAdjustment;
     }
     else
     {
-        ExFreePoolWithTag(Buffer, 'rXmM');
+        ExFreePoolWithTag(*AllocBase, 'rXmM');
+        *AllocBase = NULL;
     }
 
     return Status;
@@ -3125,7 +3307,7 @@ ExeFmtpCreateImageSection(PFILE_OBJECT FileObject,
     /* And finish their initialization */
     for ( i = 0; i < ImageSectionObject->NrSegments; ++ i )
     {
-        ExInitializeFastMutex(&ImageSectionObject->Segments[i].Lock);
+        ExInitializePushLock(&ImageSectionObject->Segments[i].Lock);
         ImageSectionObject->Segments[i].ReferenceCount = &ImageSectionObject->RefCount;
         ImageSectionObject->Segments[i].Flags = &ImageSectionObject->SegFlags;
         MiInitializeSectionPageTable(&ImageSectionObject->Segments[i]);
@@ -3241,9 +3423,6 @@ grab_image_section_object:
 
         MiReleasePfnLock(OldIrql);
 
-        /* Purge the cache */
-        CcFlushCache(FileObject->SectionObjectPointer, NULL, 0, NULL);
-
         StatusExeFmt = ExeFmtpCreateImageSection(FileObject, ImageSectionObject);
 
         if (!NT_SUCCESS(StatusExeFmt))
@@ -3458,6 +3637,9 @@ MmFreeSectionPage(PVOID Context, MEMORY_AREA* MemoryArea, PVOID Address,
     }
     else if (Page != 0)
     {
+        /* Delete from process working set */
+        MmDeleteRmap(Page, Process, Address);
+
         if (IS_SWAP_FROM_SSE(Entry) ||
                 Page != PFN_FROM_SSE(Entry))
         {
@@ -3472,18 +3654,13 @@ MmFreeSectionPage(PVOID Context, MEMORY_AREA* MemoryArea, PVOID Address,
                 MmFreeSwapPage(SavedSwapEntry);
                 MmSetSavedSwapEntryPage(Page, 0);
             }
-            MmDeleteRmap(Page, Process, Address);
+            MmRemoveLRUUserPage(Page);
             MmReleasePageMemoryConsumer(MC_USER, Page);
         }
         else
         {
-            if (Process)
-            {
-                MmDeleteRmap(Page, Process, Address);
-            }
-
             /* We don't dirtify for System Space Maps. We let Cc manage that */
-            MmUnsharePageEntrySectionSegment(MemoryArea, Segment, &Offset, Process ? Dirty : FALSE, FALSE, NULL);
+            MmUnsharePageEntrySectionSegment(Segment, &Offset, Process ? Dirty : FALSE, FALSE);
         }
     }
 }
@@ -3634,6 +3811,17 @@ MiRosUnmapViewOfSection(IN PEPROCESS Process,
     }
     else
     {
+        PFILE_OBJECT FileObject = MemoryArea->SectionData.Segment->FileObject;
+
+        /*
+         * This may be the last mapping for this file, meaning we'll flush it to disk.
+         * Forbid other operations on it, notably ones which modify ValidDataLength or file size.
+         */
+        if (FileObject != NULL)
+        {
+            FsRtlAcquireFileExclusive(FileObject);
+        }
+
         Status = MmUnmapViewOfSegment(AddressSpace, BaseAddress);
         if (!NT_SUCCESS(Status))
         {
@@ -3641,6 +3829,11 @@ MiRosUnmapViewOfSection(IN PEPROCESS Process,
                     BaseAddress, Process, Status);
             ASSERT(NT_SUCCESS(Status));
         }
+
+        if (FileObject != NULL)
+        {
+            FsRtlReleaseFile(FileObject);
+        }
     }
 
     /* Notify debugger */
@@ -4224,11 +4417,12 @@ MiPurgeImageSegment(PMM_SECTION_SEGMENT Segment)
             }
 
             /* Regular entry */
-            ASSERT(!IS_WRITE_SSE(Entry));
             ASSERT(MmGetSavedSwapEntryPage(PFN_FROM_SSE(Entry)) == 0);
+            ASSERT(IS_DIRTY_SSE(Entry) == 0);
 
             /* Properly remove using the used API */
             Offset.QuadPart = PageTable->FileOffset.QuadPart + (i << PAGE_SHIFT);
+            MmRemoveLRUStandbyPage(PFN_FROM_SSE(Entry));
             MmSetPageEntrySectionSegment(Segment, &Offset, 0);
             MmReleasePageMemoryConsumer(MC_USER, PFN_FROM_SSE(Entry));
         }
@@ -4775,15 +4969,6 @@ MmPurgeSegment(
             return FALSE;
         }
 
-        if (IS_WRITE_SSE(Entry))
-        {
-            /* We're trying to purge an entry which is being written. Restart this loop iteration */
-            MmUnlockSectionSegment(Segment);
-            KeDelayExecutionThread(KernelMode, FALSE, &TinyTime);
-            MmLockSectionSegment(Segment);
-            continue;
-        }
-
         if (SHARE_COUNT_FROM_SSE(Entry) > 0)
         {
             /* This page is currently in use. Bad luck */
@@ -4792,8 +4977,15 @@ MmPurgeSegment(
             return FALSE;
         }
 
+        /* Remove from lists */
+        if (IS_DIRTY_SSE(Entry))
+            MmRemoveLRUModifiedPage(PFN_FROM_SSE(Entry));
+        else
+            MmRemoveLRUStandbyPage(PFN_FROM_SSE(Entry));
+
         /* We can let this page go */
         MmSetPageEntrySectionSegment(Segment, &PurgeStart, 0);
+
         MmReleasePageMemoryConsumer(MC_USER, PFN_FROM_SSE(Entry));
 
         PurgeStart.QuadPart += PAGE_SIZE;
@@ -4818,7 +5010,7 @@ MmMakeDataSectionResident(
     /* There must be a segment for this call */
     ASSERT(Segment);
 
-    NTSTATUS Status = MmMakeSegmentResident(Segment, Offset, Length, ValidDataLength, FALSE);
+    NTSTATUS Status = MmMakeSegmentResident(Segment, Offset, Length, ValidDataLength);
 
     MmDereferenceSegment(Segment);
 
@@ -4892,7 +5084,7 @@ MmFlushSegment(
 
         if (IS_DIRTY_SSE(Entry))
         {
-            MmCheckDirtySegment(Segment, &FlushStart, FALSE, FALSE);
+            MmCheckDirtySegment(Segment, &FlushStart, FALSE);
 
             if (Iosb)
                 Iosb->Information += PAGE_SIZE;
@@ -4912,11 +5104,9 @@ MmFlushSegment(
 
 _Requires_exclusive_lock_held_(Segment->Lock)
 BOOLEAN
-NTAPI
 MmCheckDirtySegment(
     PMM_SECTION_SEGMENT Segment,
     PLARGE_INTEGER Offset,
-    BOOLEAN ForceDirty,
     BOOLEAN PageOut)
 {
     ULONG_PTR Entry;
@@ -4934,9 +5124,9 @@ MmCheckDirtySegment(
         return FALSE;
 
     Page = PFN_FROM_SSE(Entry);
-    if ((IS_DIRTY_SSE(Entry)) || ForceDirty)
+    if (IS_DIRTY_SSE(Entry))
     {
-        BOOLEAN DirtyAgain;
+        BOOLEAN Standby;
 
         /*
          * We got a dirty entry. This path is for the shared data,
@@ -4945,10 +5135,27 @@ MmCheckDirtySegment(
         ASSERT(FlagOn(*Segment->Flags, MM_DATAFILE_SEGMENT) ||
                FlagOn(Segment->Image.Characteristics, IMAGE_SCN_MEM_SHARED));
 
-        /* Insert the cleaned entry back. Mark it as write in progress, and clear the dirty bit. */
-        Entry = MAKE_SSE(PAGE_FROM_SSE(Entry), SHARE_COUNT_FROM_SSE(Entry) + 1);
-        Entry = WRITE_SSE(Entry);
-        MmSetPageEntrySectionSegment(Segment, Offset, Entry);
+        /* This will be clean after we write the dirty data */
+        Entry = CLEAN_SSE(Entry);
+
+        /* In case it's in the modified list,
+         * just remove it from there and don't let others use the page */
+        if (SHARE_COUNT_FROM_SSE(Entry) == 0)
+        {
+            MmRemoveLRUModifiedPage(Page);
+            MmSetPageEntrySectionSegment(Segment, Offset, MAKE_SWAP_SSE(MM_WAIT_ENTRY));
+            /* This will go to standby after us */
+            Standby = TRUE;
+        }
+        else
+        {
+            /* Insert the cleaned entry back. Get a ref so this doesn't go away without us noticing. */
+            Entry = BUMPREF_SSE(Entry);
+            MmSetPageEntrySectionSegment(Segment, Offset, Entry);
+
+            /* This page is still active. */
+            Standby = FALSE;
+        }
 
         MmUnlockSectionSegment(Segment);
 
@@ -4959,8 +5166,8 @@ MmCheckDirtySegment(
                 IoSetTopLevelIrp((PIRP)FSRTL_MOD_WRITE_TOP_LEVEL_IRP);
 
             /* Go ahead and write the page */
-            DPRINT("Writing page at offset %I64d for file %wZ, Pageout: %s\n",
-                    Offset->QuadPart, &Segment->FileObject->FileName, PageOut ? "TRUE" : "FALSE");
+            DPRINT("Writing page at offset 0x%I64x for file %wZ, Pageout: %s\n",
+                   Offset->QuadPart, &Segment->FileObject->FileName, PageOut ? "TRUE" : "FALSE");
             Status = MiWritePage(Segment, Offset->QuadPart, Page);
 
             if (PageOut)
@@ -5001,48 +5208,28 @@ MmCheckDirtySegment(
 
         MmLockSectionSegment(Segment);
 
-        /* Get the entry again */
-        Entry = MmGetPageEntrySectionSegment(Segment, Offset);
-        ASSERT(PFN_FROM_SSE(Entry) == Page);
-
-        if (!NT_SUCCESS(Status))
+        if (Standby)
         {
-            /* Damn, this failed. Consider this page as still dirty */
-            DPRINT1("MiWritePage FAILED: Status 0x%08x!\n", Status);
-            DirtyAgain = TRUE;
+            /* Restore our entry. Check if we succeeded first */
+            if (!NT_SUCCESS(Status))
+            {
+                DPRINT1("Failed to write page at offset %llx, file %wZ, Status 0x%08x\n",
+                        Offset->QuadPart, &Segment->FileObject->FileName, Status);
+                /* Oh no. Then it's not clean at all */
+                Entry = DIRTY_SSE(Entry);
+                MmInsertLRULastModifiedPage(Page);
+            }
+            else
+            {
+                MmInsertLRULastStandbyPage(Page);
+            }
+            MmSetPageEntrySectionSegment(Segment, Offset, Entry);
         }
         else
         {
-            /* Check if someone dirtified this page while we were not looking */
-            DirtyAgain = IS_DIRTY_SSE(Entry);
-        }
-
-        /* Drop the reference we got, deleting the write altogether. */
-        Entry = MAKE_SSE(Page << PAGE_SHIFT, SHARE_COUNT_FROM_SSE(Entry) - 1);
-        if (DirtyAgain)
-        {
-            Entry = DIRTY_SSE(Entry);
-        }
-        MmSetPageEntrySectionSegment(Segment, Offset, Entry);
-    }
-
-    /* Were this page hanging there just for the sake of being present ? */
-    if (!IS_DIRTY_SSE(Entry) && (SHARE_COUNT_FROM_SSE(Entry) == 0) && PageOut)
-    {
-        ULONG_PTR NewEntry = 0;
-        /* Restore the swap entry here */
-        if (!FlagOn(*Segment->Flags, MM_DATAFILE_SEGMENT))
-        {
-            SWAPENTRY SwapEntry = MmGetSavedSwapEntryPage(Page);
-            if (SwapEntry)
-                NewEntry = MAKE_SWAP_SSE(SwapEntry);
+            /* Simply unshare it, dirtify again if we failed. */
+            MmUnsharePageEntrySectionSegment(Segment, Offset, !NT_SUCCESS(Status), PageOut);
         }
-
-        /* Yes. Release it */
-        MmSetPageEntrySectionSegment(Segment, Offset, NewEntry);
-        MmReleasePageMemoryConsumer(MC_USER, Page);
-        /* Tell the caller we released the page */
-        return TRUE;
     }
 
     return FALSE;
diff --git a/ntoskrnl/mm/shutdown.c b/ntoskrnl/mm/shutdown.c
index 1d08a4f4166..5d9d4cad3c2 100644
--- a/ntoskrnl/mm/shutdown.c
+++ b/ntoskrnl/mm/shutdown.c
@@ -22,7 +22,6 @@ MiShutdownSystem(VOID)
 {
     ULONG i;
     PFN_NUMBER Page;
-    BOOLEAN Dirty;
 
     /* Loop through all the paging files */
     for (i = 0; i < MmNumberOfPagingFiles; i++)
@@ -36,41 +35,20 @@ MiShutdownSystem(VOID)
         ZwClose(MmPagingFile[i]->FileHandle);
     }
 
-    /* Loop through all the pages owned by the legacy Mm and page them out, if needed. */
-    /* We do it as long as there are dirty pages, since flushing can cause the FS to dirtify new ones. */
-    do
+    /* Loop through all the pages owned by the legacy Mm and flush them to disk. */
+    while ((Page = MmGetLRUFirstModifiedPage()))
     {
-        Dirty = FALSE;
+        LARGE_INTEGER SegmentOffset;
+        PMM_SECTION_SEGMENT Segment = MmGetSectionAssociation(Page, &SegmentOffset);
 
-        Page = MmGetLRUFirstUserPage();
-        while (Page)
+        if (Segment)
         {
-            LARGE_INTEGER SegmentOffset;
-            PMM_SECTION_SEGMENT Segment = MmGetSectionAssociation(Page, &SegmentOffset);
-
-            if (Segment)
-            {
-                if ((*Segment->Flags) & MM_DATAFILE_SEGMENT)
-                {
-                    MmLockSectionSegment(Segment);
-
-                    ULONG_PTR Entry = MmGetPageEntrySectionSegment(Segment, &SegmentOffset);
-
-                    if (!IS_SWAP_FROM_SSE(Entry) && IS_DIRTY_SSE(Entry))
-                    {
-                        Dirty = TRUE;
-                        MmCheckDirtySegment(Segment, &SegmentOffset, FALSE, TRUE);
-                    }
-
-                    MmUnlockSectionSegment(Segment);
-                }
-
-                MmDereferenceSegment(Segment);
-            }
-
-            Page = MmGetLRUNextUserPage(Page, FALSE);
+            MmLockSectionSegment(Segment);
+            MmCheckDirtySegment(Segment, &SegmentOffset, TRUE);
+            MmUnlockSectionSegment(Segment);
+            MmDereferenceSegment(Segment);
         }
-    } while (Dirty);
+    }
 }
 
 VOID
diff --git a/ntoskrnl/po/power.c b/ntoskrnl/po/power.c
index 7b5b39fa818..3170544f53e 100644
--- a/ntoskrnl/po/power.c
+++ b/ntoskrnl/po/power.c
@@ -996,7 +996,6 @@ NtSetSystemPowerState(IN POWER_ACTION SystemAction,
     KPROCESSOR_MODE PreviousMode = KeGetPreviousMode();
     POP_POWER_ACTION Action = {0};
     NTSTATUS Status;
-    ULONG Dummy;
 
     /* Check for invalid parameter combinations */
     if ((MinSystemState >= PowerSystemMaximum) ||
@@ -1085,15 +1084,6 @@ NtSetSystemPowerState(IN POWER_ACTION SystemAction,
         DPRINT("Flushing volumes\n");
         PopFlushVolumes(PopAction.Shutdown);
 
-#ifndef NEWCC
-        /* Flush dirty cache pages */
-        /* XXX: Is that still mandatory? As now we'll wait on lazy writer to complete? */
-        CcRosFlushDirtyPages(MAXULONG, &Dummy, TRUE, FALSE);
-        DPRINT("Cache flushed %lu pages\n", Dummy);
-#else
-        Dummy = 0;
-#endif
-
         /* Set IRP for drivers */
         PopAction.IrpMinor = IRP_MN_SET_POWER;
         if (PopAction.Shutdown)
diff --git a/sdk/include/crt/mingw32/intrin_x86.h b/sdk/include/crt/mingw32/intrin_x86.h
index 888bf795313..14aeecd14c6 100644
--- a/sdk/include/crt/mingw32/intrin_x86.h
+++ b/sdk/include/crt/mingw32/intrin_x86.h
@@ -1968,7 +1968,7 @@ __INTRIN_INLINE void __writedr(unsigned reg, unsigned int value)
 
 __INTRIN_INLINE void __invlpg(void *Address)
 {
-	__asm__ __volatile__ ("invlpg (%[Address])" : : [Address] "b" (Address) : "memory");
+	__asm__ __volatile__ ("invlpg (%[Address])" : : [Address] "r" (Address) : "memory");
 }
 
 
