Search code examples
windowsmemory-mapped-files

How does Windows deal with flushing modified pages in a consistent way?


Imagine there's a memory-mapped file and the application is writing to it constantly. Eventually, Windows will probably flush that page to disk. How does Windows ensure that a stable snapshot of that page is flushed to disk?

Probably, the disk hardware is copying the memory into it's internal memory before writing it. That's not atomic. If the application writes randomly to that page the disk hardware might copy data that has never existed at any point in time.

Does this mean that memory mapped files might leave a page on disk in a state that has never actually existed? That could be a problem to consistency.

Or does Windows lock the page during flushing? That could be a problem because a write to that page might result in very high latency.


Solution

  • How does Windows ensure that a stable snapshot of that page is flushed to disk?

    It doesn't need to. If the page doesn't get changed during the flush operation, the data is consistent. If the page does get changed during the flush operation, then the page is marked as dirty, so it will be flushed again in due course and the data that got written to the disk is ignored.

    (Incidentally, the data is probably not copied internally. The system should normally be able to use DMA to transfer it directly to the physical device.)