- MapViewOfFileEx function (memoryapi.h)
- Syntax
- Parameters
- Return value
- Remarks
- File Mapping
- Проблема высокой загрузки памяти системным файловым кэшем на Windows Server 2008 R2
- Высокая загрузка оперативной памяти на файловом сервере Windows
- Что такое метафайл в Windows?
- Быстрая очистка метафайла MFT в памяти
- Служба Dynamic Cache Service для управления файловым кэшем
MapViewOfFileEx function (memoryapi.h)
Maps a view of a file mapping into the address space of a calling process. A caller can optionally specify a suggested base memory address for the view.
To specify the NUMA node for the physical memory, see MapViewOfFileExNuma.
Syntax
Parameters
A handle to a file mapping object. The CreateFileMapping and OpenFileMapping functions return this handle.
The type of access to a file mapping object, which determines the page protection of the pages. This parameter can be one of the following values, or a bitwise OR combination of multiple values where appropriate.
Value | Meaning | ||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
FILE_MAP_ALL_ACCESS | A read/write view of the file is mapped. The file mapping object must have been created with PAGE_READWRITE or PAGE_EXECUTE_READWRITE protection. When used with the MapViewOfFileEx function, FILE_MAP_ALL_ACCESS is equivalent to FILE_MAP_WRITE. | ||||||||||
FILE_MAP_READ | A read-only view of the file is mapped. An attempt to write to the file view results in an access violation. The file mapping object must have been created with PAGE_READONLY, PAGE_READWRITE, PAGE_EXECUTE_READ, or PAGE_EXECUTE_READWRITE protection. | ||||||||||
FILE_MAP_WRITE | A read/write view of the file is mapped. The file mapping object must have been created with PAGE_READWRITE or PAGE_EXECUTE_READWRITE protection. When used with MapViewOfFileEx, (FILE_MAP_WRITE | FILE_MAP_READ) and FILE_MAP_ALL_ACCESS are equivalent to FILE_MAP_WRITE. Using bitwise OR, you can combine the values above with these values.
В For file-mapping objects created with the SEC_IMAGE attribute, the dwDesiredAccess parameter has no effect, and should be set to any valid value such as FILE_MAP_READ. For more information about access to file mapping objects, see File Mapping Security and Access Rights. The high-order DWORD of the file offset where the view is to begin. The low-order DWORD of the file offset where the view is to begin. The combination of the high and low offsets must specify an offset within the file mapping. They must also match the memory allocation granularity of the system. That is, the offset must be a multiple of the allocation granularity. To obtain the memory allocation granularity of the system, use the GetSystemInfo function, which fills in the members of a SYSTEM_INFO structure. The number of bytes of a file mapping to map to a view. All bytes must be within the maximum size specified by CreateFileMapping. If this parameter is 0 (zero), the mapping extends from the specified offset to the end of the file mapping. A pointer to the memory address in the calling process address space where mapping begins. This must be a multiple of the system’s memory allocation granularity, or the function fails. To determine the memory allocation granularity of the system, use the GetSystemInfo function. If there is not enough address space at the specified address, the function fails. If lpBaseAddress is NULL, the operating system chooses the mapping address. In this scenario, the function is equivalent to the MapViewOfFile function. While it is possible to specify an address that is safe now (not used by the operating system), there is no guarantee that the address will remain safe over time. Therefore, it is better to let the operating system choose the address. In this case, you would not store pointers in the memory mapped file, you would store offsets from the base of the file mapping so that the mapping can be used at any address. Return valueIf the function succeeds, the return value is the starting address of the mapped view. If the function fails, the return value is NULL. To get extended error information, call GetLastError. RemarksMapping a file makes the specified portion of the file visible in the address space of the calling process. For files that are larger than the address space, you can only map a small portion of the file data at one time. When the first view is complete, then you unmap it and map a new view. To obtain the size of a view, use the VirtualQueryEx function. The initial contents of the pages in a file mapping object backed by the page file are 0 (zero). Typically, the suggested address is used to specify that a file should be mapped at the same address in multiple processes. This requires the region of address space to be available in all involved processes. No other memory allocation can take place in the region that is used for mapping, including the use of the VirtualAlloc or VirtualAllocEx function to reserve memory. If the lpBaseAddress parameter specifies a base offset, the function succeeds if the specified memory region is not already in use by the calling process. The system does not ensure that the same memory region is available for the memory mapped file in other 32-bit processes. Multiple views of a file (or a file mapping object and its mapped file) are coherent if they contain identical data at a specified time. This occurs if the file views are derived from the same file mapping object. A process can duplicate a file mapping object handle into another process by using the DuplicateHandle function, or another process can open a file mapping object by name by using the OpenFileMapping function. With one important exception, file views derived from any file mapping object that is backed by the same file are coherent or identical at a specific time. Coherency is guaranteed for views within a process and for views that are mapped by different processes. The exception is related to remote files. Although MapViewOfFileEx works with remote files, it does not keep them coherent. For example, if two computers both map a file as writable, and both change the same page, each computer only sees its own writes to the page. When the data gets updated on the disk, it is not merged. A mapped view of a file is not guaranteed to be coherent with a file being accessed by the ReadFile or WriteFile function. To guard against EXCEPTION_IN_PAGE_ERROR exceptions, use structured exception handling to protect any code that writes to or reads from a memory mapped view of a file other than the page file. For more information, see Reading and Writing From a File View. When modifying a file through a mapped view, the last modification timestamp may not be updated automatically. If required, the caller should use SetFileTime to set the timestamp. To have a file with executable permissions, an application must call CreateFileMapping with either PAGE_EXECUTE_READWRITE or PAGE_EXECUTE_READ, and then call MapViewOfFileEx with FILE_MAP_EXECUTE | FILE_MAP_WRITE or FILE_MAP_EXECUTE | FILE_MAP_READ. In Windows ServerВ 2012, this function is supported by the following technologies. File MappingFile mapping is the association of a file’s contents with a portion of the virtual address space of a process. The system creates a file mapping object (also known as a section object) to maintain this association. A file view is the portion of virtual address space that a process uses to access the file’s contents. File mapping allows the process to use both random input and output (I/O) and sequential I/O. It also allows the process to work efficiently with a large data file, such as a database, without having to map the whole file into memory. Multiple processes can also use memory-mapped files to share data. Processes read from and write to the file view using pointers, just as they would with dynamically allocated memory. The use of file mapping improves efficiency because the file resides on disk, but the file view resides in memory. Processes can also manipulate the file view with the VirtualProtect function. The following illustration shows the relationship between the file on disk, a file mapping object, and a file view. The file on disk can be any file that you want to map into memory, or it can be the system page file. The file mapping object can consist of all or only part of the file. It is backed by the file on disk. This means that when the system swaps out pages of the file mapping object, any changes made to the file mapping object are written to the file. When the pages of the file mapping object are swapped back in, they are restored from the file. A file view can consist of all or only part of the file mapping object. A process manipulates the file through the file views. A process can create multiple views for a file mapping object. The file views created by each process reside in the virtual address space of that process. When the process needs data from a portion of the file other than what is in the current file view, it can unmap the current file view, then create a new file view. When multiple processes use the same file mapping object to create views for a local file, the data is coherent. That is, the views contain identical copies of the file on disk. The file cannot reside on a remote computer if you want to share memory between multiple processes. For more information, see the following topics: Проблема высокой загрузки памяти системным файловым кэшем на Windows Server 2008 R2На одном из файловых серверов под управлением Windows Server 2008 R2 обнаружилась проблема с высокой загрузки оперативной памяти (RAM), выливающаяся в проблемы с производительностью сервера и запущенных на нем служб. Как оказалось, память забивалась системным файловым кэшем с метаданными файловой системы. Проблеме потенциально подвержены все файловые сервера с большим количеством файлов, к которым обращаются пользователя. Наиболее критична проблема для 64 битных версий Windows, на которых размер метафайла в памяти может занять практически всю емкость установленной оперативной памяти. В статье разберемся как проявляется проблема, выявим ее источники и способы решения. Высокая загрузка оперативной памяти на файловом сервере WindowsПроблема проявляется следующим образом: в диспетчере задач (Task Manager) видим, что на сервере оперативная память занята на 95-99%.
Что такое метафайл в Windows?Метафайл (Metafile) — это часть системного кэша, который содержит метаданные файловой системы NTFS и используется для увеличения быстродействия файловой системы при доступе к файлам. Метаданные NTFS включают в себя данные таблицы MFT (Master File Table). Для каждого файла/папки, к которому обращались пользователи, в метафайле создается соответствующий блок, размером как минимум 1 Кб (запись об атрибуте каждого файла занимает 1кб, и каждый файл имеет как минимум один атрибут). Таким образом, на файловых серверах с большим количеством файлов, к которым идут постоянные обращения, размер системного кэша NTFS (метафайла) может достигать нескольких гигабайт. Отключить этот кэш или управлять им с помощью стандартных средств Windows не получится. Как решение, можно увеличить количество памяти на сервере, но реализуемо это далеко не всегда. Если перезагрузить сервер, память используемая метафайлом освобождается, но со временем размер метафайла в памяти все равно начинает неконтролируемо расти. К примеру, оценить размер MFT таблицы можно с помощью еще одной утилиты Руссиновича – ntfsinfo. К примеру, в нашем примере для 2 Тб диска размер MFT таблицы составляет 13 Гб. Быстрая очистка метафайла MFT в памятиУтилита RAMMap предоставляет возможность быстрой очистки используемой памяти от мусора без необходимости перезагрузки сервера. Для этого нужно в меню выбрать раздел Empty -> Empty System Working Set.
Служба Dynamic Cache Service для управления файловым кэшемДругим, более кардинальным, решением проблемы высокой загрузки оперативной памяти метафайлом файловой системы является установка службы Dynamic Cache Service (http://www.microsoft.com/en-us/download/details.aspx?id=9258). Данная служба через системные API позволяет управлять параметрами выделяемого кэша. Установка DynCache довольно простая (подробные инструкции есть в архиве с программой).
В нашем случае, после установки службы DynCache, использование памяти метафайлом перестало превышать заданного нами значения 4 Гб. Пользователи каких-либо проблем с ухудшением производительности файлового сервера не выявили. |