Проблема высокой загрузки памяти системным файловым кэшем на Windows Server 2008 R2
На одном из файловых серверов под управлением Windows Server 2008 R2 обнаружилась проблема с высокой загрузки оперативной памяти (RAM), выливающаяся в проблемы с производительностью сервера и запущенных на нем служб. Как оказалось, память забивалась системным файловым кэшем с метаданными файловой системы. Проблеме потенциально подвержены все файловые сервера с большим количеством файлов, к которым обращаются пользователя. Наиболее критична проблема для 64 битных версий Windows, на которых размер метафайла в памяти может занять практически всю емкость установленной оперативной памяти. В статье разберемся как проявляется проблема, выявим ее источники и способы решения.
Высокая загрузка оперативной памяти на файловом сервере Windows
Проблема проявляется следующим образом: в диспетчере задач (Task Manager) видим, что на сервере оперативная память занята на 95-99%.
Перейдя на вкладку процессов, не удастся найти какой-то утекший процесс с аномально высоким потреблением памяти. Кроме того, если навскидку сложить память, занятую всеми процессами, отображаемыми в диспетчере задач, даже близко не удается приблизиться к 50% физической памяти, установленной на сервере. Так кто же съел всю память?
Реальный расклад по использованию оперативной памяти может дать утилита RAMMap (Марка Руссиновича). Качаем архив с утилитой и запускаем из архива файл RAMMap.exe с правами администратора. На вкладке Use Counts, видим, что больше всего физической памяти использует объектом Metafile (в нашем случае на него приходится 11 из 25 Гб оперативной памяти сервера).
Что такое метафайл в Windows?
Метафайл (Metafile) — это часть системного кэша, который содержит метаданные файловой системы NTFS и используется для увеличения быстродействия файловой системы при доступе к файлам. Метаданные NTFS включают в себя данные таблицы MFT (Master File Table). Для каждого файла/папки, к которому обращались пользователи, в метафайле создается соответствующий блок, размером как минимум 1 Кб (запись об атрибуте каждого файла занимает 1кб, и каждый файл имеет как минимум один атрибут). Таким образом, на файловых серверах с большим количеством файлов, к которым идут постоянные обращения, размер системного кэша NTFS (метафайла) может достигать нескольких гигабайт.
Отключить этот кэш или управлять им с помощью стандартных средств Windows не получится. Как решение, можно увеличить количество памяти на сервере, но реализуемо это далеко не всегда.
Если перезагрузить сервер, память используемая метафайлом освобождается, но со временем размер метафайла в памяти все равно начинает неконтролируемо расти.
К примеру, оценить размер MFT таблицы можно с помощью еще одной утилиты Руссиновича – ntfsinfo. К примеру, в нашем примере для 2 Тб диска размер MFT таблицы составляет 13 Гб.
Быстрая очистка метафайла MFT в памяти
Утилита RAMMap предоставляет возможность быстрой очистки используемой памяти от мусора без необходимости перезагрузки сервера. Для этого нужно в меню выбрать раздел Empty -> Empty System Working Set. После этой операции размер памяти под metafile уменьшился в десятки раз, а процент использования RAM сервером упал с 95% до 26%.
Основной недостаток такого метода – процесс очистки ручной и никак не автоматизируется.
Служба Dynamic Cache Service для управления файловым кэшем
Другим, более кардинальным, решением проблемы высокой загрузки оперативной памяти метафайлом файловой системы является установка службы Dynamic Cache Service (http://www.microsoft.com/en-us/download/details.aspx?id=9258). Данная служба через системные API позволяет управлять параметрами выделяемого кэша.
Установка DynCache довольно простая (подробные инструкции есть в архиве с программой).
- Копируем файл в DynCache.exe в каталог %SystemRoot%\System32
- Создадим службу DynCache командой sc create DynCache binpath= %SystemRoot%\System32\DynCache.exe start= auto type= own DisplayName= «Dynamic Cache Service»
- Импортируем файл DynCache.reg в реестр (содержит дефолтные значения)
- Изменим значения следующих ключей реестра HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\DynCache\Parameters
- MaxSystemCacheMBytes: 4096 (dec) – максимальный размер кэша
- MinSystemCacheMBytes: 100 (dec) – минимальный размер
В нашем случае, после установки службы DynCache, использование памяти метафайлом перестало превышать заданного нами значения 4 Гб. Пользователи каких-либо проблем с ухудшением производительности файлового сервера не выявили.
Как я могу ограничить или даже отключить кэш файлов на Windows Server 2008R2?
есть машина с очень быстрым массивом RAID и быстрым подключением к интернету. Но, он получил только 8 ГБ памяти, который заканчивается действительно быстро, когда загрузка идет вверх.
любые идеи, как я могу отключить или ограничить кэш?
(Я попытался отключить кэш записи из Диспетчера устройств. Но это просто кэш записи, и это не помогло.)
4 ответов
весь смысл кэша в том, что он использует неиспользованный ram, и дает его, как только приложение запрашивает больше. Таким образом, вы не хотите, чтобы ограничить его размер, как это было бы просто оставить свободной оперативной памяти полностью впустую.
вы должны вызвать системный API SetSystemFileCacheSize ()
Документально здесь: http://msdn.microsoft.com/en-us/library/aa965240.aspx
некоторые программы позволяют это: http://technet.microsoft.com/en-us/sysinternals/bb897561
Но вы можете предпочесть CLI, чтобы автоматически запускать его при запуске системы:http://www.uwe-sieber.de/ntcacheset_e.html (Посмотрите в середине страницы, он работает для 2k8)
или просто напишите сценарий powershell, вызывающий SetSystemFileCacheSize ()
Примечание настоятельно не рекомендуется отключать кэш для использования в рабочей среде.
Часто размер кэша ограничивается небольшим значением для виртуальных машин, а не отключается.
мы также испытывали этот вопрос на сервере 2008 Р2 Виндовс в нашей компании. В нашем случае машина полностью застряла. Это, кажется, ошибка на этой версии сервера Windows, потому что это не произошло при тех же обстоятельствах, либо на моем гораздо меньше Windows 7 машина работает в VirtualBox, или под Linux.
вы можете установить кэш до определенного предела с API, как другие уже размещены, но вы можете найти приложения, чтобы непосредственно использовать его, такие как SetSystemFileCacheSize.exe или NT Cache Setter.
недостатком является то, что вам нужно установить кэш после каждой перезагрузки. Вы также можете очистить весь кэш за один раз.
мы установить кэш файл на наш ВМ с 14 ГБ до 4 ГБ и она работает. Также flush работает хорошо, и вы можете увидеть его непосредственно в Диспетчере задач.
примеры командной строки:
показать текущие окна настройки:
установите минимальный размер 8 МБ и максимальный размер 128 МБ:
отключить минимальный размер и установить максимальный размер 128 МБ:
отключить минимальный и максимальный размер:
Примечание: инструмент должен быть запущен с права администратора.
Windows 2008 r2 cached memory
Question
I have an issue with my 2008R2 Enterprise file server gradually using more and more physical memory until most of it is taken up, and only a reboot clears it. This server is not currently in production, and I just happened to notice the memory creeping up over a couple of days as I was copying files to it.
I have done some research on this problem and it seems it has to do with «Excessive Cached Read I/O». This behavior is nicely explained in this msdn blog (http://blogs.msdn.com/ntdebugging/archive/2007/11/27/too-much-cache.aspx)
The «unsupported» fix in the blog, became the supported fix listed in the Performance Tuning Guidelines for Windows Server 2008 as the «Microsoft Windows Dynamic Cache Service» (http://www.microsoft.com/downloads/details.aspx?FamilyID=E24ADE0A-5EFE-43C8-B9C3-5D0ECB2F39AF&displaylang=en)
Unfortunately, 2008R2 is not supported by this download and the Performance Tuning Guidelines for Windows Server 2008R2 doc states that;
«Previous releases of Windows Server sometimes benefitted from tools that limit the working-set size of the Windows file cache. These tools are not necessary on most servers running Windows Server 2008 R2. You should reevaluate your use of such tools.»
I still seem to have the same problem, physical memory being used up by cached read I/O, but there is no supported method of controling it in 2008R2.
My concern is that there is no way to stop the cached read I/O from squeezing kernel processes out to virtual memory (disk) and killing performance.
Is there another fix available for R2? Is there an upgrade to the cache manager in R2 that fixes the problem?
All replies
I’ve done some additional research and it does look like Microsoft is was aware this was an issue in Server 2008, but does not believe it is a problem in Server 2008R2. they have said as much in the Performance Tuning Guidelines for Windows Server 2008R2 doc, mentioned above, and its also mentioned in http://support.microsoft.com/kb/976618
«The memory management algorithms were updated to address this problem in Windows 7 and Windows Server 2008 R2 operating systems. Therefore, we do not recommend that you use the provided functions or the Microsoft Windows Dynamic Cache Service in computers that are running Windows 7 or Windows Server 2008 R2.»
Ok, so the system caches files, and the memory manager is now updated to handle them (no details given on how). However when I look at performance monitor to see where/how all the memory is allocated, things don’t seem to add up.
An MSDN article on memory performance information (http://msdn.microsoft.com/en-us/library/aa965225(VS.85).aspx#system_memory_performance_information) says that the following performance counters should correspond to the «Physical Memory (MB): Cached» displayed by Task Manager.
Cache Bytes + Modified Page List Bytes + Standby Cache Reserve Bytes + Standby Cache Normal Priority Bytes + Standby Cache Code Bytes (I beleive this last counter is actually «Standby Cache Core Bytes» as «Standby Cache Code Bytes» doesn’t exist)
The weird thing is that when I add all the values up for these counters and do a little math to get to MB it does not match. Task Manager displays 599 MB as the «Physical Memory (MB): Cached» value, yet the counter add up to 3,287 MB. Big difference.
Note: The larger number I get from the performance counters does seem to jive with what I see in Task Manager for real time memory usage.
So my confusion. I’m seeing real time memory usage, in Task Manager, increase to the point of using up all the physical memory. Microsoft says that this is system cache, and the memory manager is handling it better in R2. Task manager says it isn’t cached (in physical memory), but Perfmon counters say it is cached, and the MSDN article says that should be reflected in Task Manager, but it isn’t.
Is there anything out there that explains what R2 is doing, and what I’m looking at here?
«Task Manager displays 599 MB as the «Physical Memory (MB): Cached» value, yet the counter add up to 3,287 MB. Big ,
difference. «
Usually every one has the tendency to monitor task manager and come into faster conclusion that they have a memory leak or application leak. To be precise task manager doesnt gives you the actual memory in usage. So you should use performance counter to calculate the bytes so that you will get what is the total amount of bytes residing in memory. So you need to get the working set of the system cache with which you can decide if there is a performance bottleneck.
Yes the memory manage is very much different from windows 2008 to windows 2008 R2. PFN lock mechanism has been re-designed.
When you said enterprise server using more memory, can you be specific at the module ? , are you seeing increase in srv.sys ? or mrxsmb.sys ?. Microsoft uses SMB protocol , earlier versions of operating systems used smb 1.1 version , and newer operating systems are using smb 2.0 with more data handling abilities per packet. So you have to further dwell down and check what is the behavior , SMB is one of the complex protocol to understand as its implementation falls into many drivers and protocols. It uses MRXSMB.sys, SRV.sys, Netbt.sys file , mup.sys file etc.
So you need to check if there is an excessive write I/o or excessive read I/O ?, Also one of the important consideration not to forget is the shell32.dll, when you are accessing file using explorer.exe it uses shell , so there is an additional overhead on the communication . Following are some of the things which i would like you to follow to get more understanding of the behavior.
a) which process is occupying more memory
b) does the memory depletion happen locally ( eg: when accessing using \\localhost\share )
c) check the behavior in safe mode with networking : if the problem doesnt exhibits in safe mode with networking , you can safely think that there is no microsoft component involved in the communication and hence the memory bottleneck.
d) try performing net use and access the share .
e) does the memory depletion occurs while accessing certain files ( file type , file size ) or with any file and any size
f) you need to monitor the process’s memory activity which gives you clear understanding of whether the memory is increasing at regular intervals or it spikes up when there is a session established by any user.
I would then use adplus dump to dump the process memory activity and then perform debuging on the process memory / vm activity.
Thanks for the reply.
I’m a little confused at your statement that «To be precise task manager doesnt gives you the actual memory in usage». I thought that was exactly what it did. Just that in 2008 and 2008R2, it displayed physical memory in use, not virtual memory. Also note that the MSDN article does state quite clearly that the performance counters I’m looking at to ascertain cached memory should correspond directly with the «Physical Memory (MB): Cached» displayed by Task Manager.
I think if I explain exactly what I’m doing with this server it might help.
I’m migrating a large physical file server to a virtual server. Our virtual environment is VMware 3.5 update 4
I noticed the uptick in memory when I would either restore files via backup exec, or copy over files using scriptlogic’s SecureCopy software. I have verified with Symantec we have the latest agent for 2008R2.
I am copying / synching 1.7 terabytes of data total to the new server. The SecureCopy software is located on the local machine, and also on another 2008R2 server (using it as a data mover).
Apart from copies and sync’s, nothing else touches this machine. After the copies / sync’s are done, physical memory usage is reported as high by the operating system (perfmon, resource monitor and task manager). Some physical memory is released (approx. 300MB) after the data transfer, but that it. After 4 days, my physical memory is still 84% used according to resource monitor.
However, none of the processes are using much memory. explore.exe is the largest user by far at 40MB total memory usage by all processes is less than 400MB. yet resource monitor is showing that 3247MB of physical memory is in use, and that 586MB of physical memory is cached. (todays numbers). This is the mystery, what is using all the physical memory? So far, I believe its the read cache I/O mentioned in the articles above. I think I can see this in the perfmon counters, but it doesn’t match up with the task managers «Physical Memory (MB): Cached», which according to MS, its supposed to. I also cannot find anything on how the new memory manager handles read cache I/O and other caching. This would be nice to see.
networking seems fine. I can access shares locally and across the network with no problem.
I will monitor the memory activity of the processes at the next copy, but as mentioned above, they seem to be acting normally.
I’m begining to think that files are cached in memory in a sort of FIFO (first in first out) fashion, as part ofthe read cache I/O operation, and there is just some weird reporting problem in task manager.
my main concern is around performance when this machine is in production. It will have many files copied to it daily, and I’m just trying to get a handle on how this memory issue will impact it. It just may be that what I’m seeing is by design, I just can’t find anything that says so, and the monitors available to me seem to give conflicting info.