본문 바로가기

Programming/Linux Tip

proc/meminfo 분석하기 와 pagecache size limitation(restrict) 하는 방법

1. meminfo 분석하기

전반적인 내용 : https://ssambback.tistory.com/entry/Linux-Memory%EC%9D%98-%EC%83%81%ED%83%9C%EB%A5%BC-%EB%B6%84%EC%84%9D%ED%95%98%EB%9D%BC

 

Linux Memory의 상태를 분석하라

리눅스의 메모리 사용량의 경우 항상 물리적인 메모리 대비 Cache 와 Buffer의 사용량에 대해서 논쟁이도고는 한다. 물론 운영중에 갑자기 물리적인 메모리의 사용량이 늘어서 SWAP을 사용하는 경우라면 달라지겠..

ssambback.tistory.com

정보는 최고사용량과 최저사용량으로 표현되며, 먼저 최고사용량에 대해 살펴보면 다음과 같다.


- MemoryTotal :
 사용 가능한 최대 메모리(RAM)량
( Physical RAM - a few reserved bits - kernel binary code )


- MemFree :
 LowFree + HighFree


- MemShared :
 호환성을 위한 값이며 항상 0임


- Buffers :
 버퍼 캐시 메모리로 최근에는 거의 쓸모없는 값


- Cached :
 pagecache(diskcache) - SwapCache


- SwapCache :
 스와핑 아웃되었던 메모리로, 스와핑 인되었지만 여전히 스왑 파일에 존재하는
메모리(메모리가 다시 필요하다면 이미 스왑파일에 존재하므로 또 다시 스와핑
아웃될 필요가 없음. 이는 I/O를 절약할 수 있음)

가상 메모리 통계는 다음과 같다.

가상 메모리는 캐시 페이지를 active와 inactive 메모리로 나누고,

The idea is that if you need memory and some cache needs to be sacrificed for that, you take it from inactive since that's expected to be not used. The vm checks what is used on a regular basis and moves stuff around.

When you use memory, the CPU sets a bit in the pagetable and the VM checks that bit occasionally, and based on that, it can move pages back to active. And within active there's an order of "longest ago not used" (roughly, it's a little more complex in reality). The longest-ago used ones can get moved to inactive. Inactive is split into two in the above kernel (2.4.18-24.8.0). Some have it three.

- Active : 가장 최근에 사용되었던 메모리로 완전히 불필요하지 않은 경우를 제외하고서는
반환되지 않음


- Inact_dirty :
 여기서 dirty의 의미는 "디스크나 스왑 공간으로 기록될 필요가 있음"을 의미하며,
빈 공간으로 반환되기 위해서는 몇가지 작업이 필요하다. 아직 기록되지 않은
파일이 예가 될 것이다. 너무 일찍 메모리에 기록하여 I/O의 성능을 떨어뜨릴
필요가 없기 때문이다. 예를 들어 log를 기록한다고 할 때 완벽한 로그가 구성될
때까지 디스크에 기록하지 않는 것이 성능에 도움이 된다.


- Inact_clean :
 쉽게 빈 공간으로 반환될 수 있음을 의미한다. 커널은 항상 일정한 양의 빈 공간을
확보하고 있는데, 이는 움직일 수 있는 여유를 가지기 위함이다.


- Inact_target :

Just a goal metric the kernel uses for making sure there are enough inactive pages around. When exceeded, the kernel will not do work to move pages from active to inactive. A page can also get inactive in a few other ways, e.g. if you do a long sequential I/O, the kernel assumes you're not going to use that memory and makes it inactive preventively. So you can get more inactive pages than the target because the kernel marks some cache as "more likely to be never used" and lets it cheat in the "last used" order.

메모리 통계


- HighTotal :
 상위 영역(high region)에 존재하는 메모리의 전체 양으로, Highmem은
physical RAM에서 대략 860MB 위의 메모리를 의미한다. 커널은 상위 영역의
메모리 메모리에 접근하기 위해 간접적인 트릭(indirect tricks)을 사용한다.
데이터 캐시가 이 메모리 영역에 포함될 수 있다.


- LowTotal :
 비상위메모리(non-highmem) 영역에 대한 총량


- LowFree :
 하위메모리 영역(low memory region)의 빈 공간. 커널이 직접적으로 접근할 수
있는 메모리 영역으로, 모든 커널 데이터구조(datastructures)가 이 메모리 영역에
저장된다.


- SwapTotal :
 물리적인 스왑 메모리(physical swap memory)의 총량


- SwapFree :
 스왑 공간의 빈 영역의 총량


- Committed_AS :
 99.99%의 보장(이러한 부하에서는 OOM[Out of Memory]를 결코 발생시키지
않음)을 위해 필요로 하는 RAM의 추측값으로, 일반적인 상황에서는 커널이 메모리를
지나치게 낭비하는 경우이다. 즉, 1GB malloc를 사용한다고 할 때 실제적으로는
아무런 일도 발생하지 않는다. 단지 메모리를 실제로 사용하기 시작할 때 malloc에
의해 필요로 하는 메모리가 요구된다. 즉 저당을 잡히고 은행이 망하지 않기만을
바라는 상황이 된다. 또 다른 경우에는 mmap 파일을 이용해서 두 프로세스 간에
공유할 경우가 포함된다. Committed_AS는 최악의 상황에서 필요로 하는

RAM/swap의 추측값이다.

참고url

http://docs.redhat.com/docs/en-US/Red_Hat_Enterprise_Linux/6/html/Deployment_Guide/s2-proc-meminfo.html
http://blog.daum.net/_blog/BlogTypeView.do?blogid=05S77&articleno=86&_bloghome_menu=recenttext#ajax_history_home



출처: https://ssambback.tistory.com/entry/Linux-Memory의-상태를-분석하라 [Rehoboth.. 이곳에서 부터]

 


2. cached 와 buffers 가 MemFree와 어떻게 연관되는지 분석

: https://jybaek.tistory.com/186

 

실제 사용 가능한 메모리 사이즈 (+ /proc/meminfo Explained Link)

보통 리눅스에서 "현재 free가 몇이야?" 라는 질문에서 free는, 실제 사용 가능한 메모리의 의미를 내포합니다. 하지만, 위와 같이 free command로 확인하는 free 필드는 buffers와 cached를 사용중(used)인 메모..

jybaek.tistory.com

통 리눅스에서 "현재 free가 몇이야?" 라는 질문에서 free는, 실제 사용 가능한 메모리의 의미를 내포합니다.


하지만, 위와 같이 free command로 확인하는 
free 필드는 buffers와 cached를 사용중(used)인 메모리로 간주하고 계산됩니다.
(즉 used에 buffers와 cached가 포함되어 있고 free 필드에는 buffers와 cached가 포함되지 않았다는 의미)

커널 내부적으로 buffers나 cached는 메모리가 부족한 경우 언제든지 free되어 가용 될 수 있지만,

사용자 관점에서는 그저 어딘가(두리뭉실)에서 붙잡고 있는 메모리로 여겨지기 때문에 사용중인 영역으로 표현한것이 아닐까요? (엄밀히 말하자면 아직 storage와의 sync가 되지 않은 메모리라고..)

반면, free command에서 "-/+ buffers/cache:" 로 표현되는 used와 free는 위에 언급된것과 내용이 조금 다롭니다.



이때의 used는 buffers와 cache를 포함하지 않고,
free는 buffers와 cache를 포함한 메모리를 나타냅니다.

이 필드(-/+)는 아마도 커널 관점이라고 하는것이 옳지 싶은데,
이유가 어찌되었든 관점의 차이고, 실제 사용 가능한 메모리는 분명,

free < 실제 사용 가능한 메모리 < free+(buffers,cached)

정도가 될 것입니다.

추가로 buffers와 cache의 차이점은 아래와 같습니다.

Buffers are associated with a specific block device, and cover caching of filesystem metadata as well as tracking in-flight pages. The cache only contains parked file data. That is, the buffers remember what's in directories, what file permissions are, and keep track of what memory is being written from or read to for a particular block device. The cache only contains the contents of the files themselves.


메모리 이야기가 나온 김에 /proc/meminfo 에서 출력되는 정보는 링크를 확인하도록 합시다.


좌우지간, 개발자인 필자는 buffers와 cached를 free 영역으로 포함시키렵니다 :)


그렇다면, page cache size의 limitation을 정하는 방법은?



3. page cache size 조정 방법 1 :  min_free_kbytes

https://discuss.aerospike.com/t/how-to-tune-the-linux-kernel-for-memory-performance/4195

Fine-tuning these parameters is dependant upon the current utilization. For Aerospike, it should be at least 1.1GB free in min_free_kbytes, if the available system memory allows. This means that caches will still operate sufficiently, while leaving a margin for applications to allocate into.

$ cat /proc/sys/vm/min_free_kbytes 67584

Tuning is performed by performing an echo NUMBER > /proc/sys/vm/min_free_kbytes where, NUMBER is the number of kilobytes required to be free in the system. To leave 3% of memory on a 100GB RAM machine unoccupied, the command would be:

echo 3145728 > /proc/sys/vm/min_free_kbytes

Caution should be exercised when setting this parameter, both too low and too high values can have an adverse effect upon system performance. Setting min_free_kbytes too low prevents the system from reclaiming memory. This can result in system hangs and OOM kills of processes.

Setting this parameter to a value that is too high (5-10% of total system memory) will cause the system to run out of memory immediately. Linux is designed to use all available RAM to cache file system data. Setting a high min_free_kbytes value results in the system spending too much time reclaiming memory.

 



4. page cache size 조정 방법 2 : /proc/sys/vm/pagecache

https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/5/html/tuning_and_optimizing_red_hat_enterprise_linux_for_oracle_9i_and_10g_databases/sect-oracle_9i_and_10g_tuning_guide-memory_usage_and_page_cache-tuning_the_page_cache

5.2. TUNING THE PAGE CACHE

Page cache is a disk cache which holds data of files and executable programs, for example pages with actual contents of files or block devices. Page cache (disk cache) is used to reduce the number of disk reads. To control the percentage of total memory used for page cache in Red Hat Enterprise Linux 5, change the pagecache kernel parameter. The lower the percentage, the more the system favors reclaiming unmapped pagecache memory over mapped memory. High values (like the default value of 100) are not recommended for databases.

The pagecache parameters can be changed in the proc file system without reboot:

# echo "40" > /proc/sys/vm/pagecache

Alternatively, you can use sysctl(8) to change it:

# sysctl -w vm.pagecache="40"

To make the change permanent, add the following line to the file /etc/sysctl.conf. This file is used during the boot process.

# echo "vm.pagecache=40" >> /etc/sysctl.conf

You can also adjust the minimum free pages using the following command:

# echo 1024 > /proc/sys/vm/min_free_kbytes

To make this change permanent, add the following line to the file /etc/sysctl.conf:

# echo vm.min_free_kbytes=1024 >> /etc/sysctl.conf

 



5. page cache size 조정 방법 3 : page cache params

http://unixadminschool.com/blog/2013/10/rhel-6-controlling-cache-memory-page-cache-size/

 

What are configurable kernel parameters that controls the size of the page cache ( or cache memory ) size?

 
vm.vfs_cache_pressure (default = 100)
 
it controls the tendency of the kernel to reclaim memory. Decreasing vfs_cache_pressure causes the kernel to prefer to retain dentry and inode caches. Increasing vfs_cache_pressure beyond 100 causes the kernel to prefer to reclaim dentries and inodes
 
Increasing this value ( e.g. 500) will make your cause for more frequent reclaim of cache memory and limit the size of page cache.
 
vm.dirty_background_ratio ( default = 20)
 
Indicates the percentage of a system memory, the number of pages at which the pdflush background writeback daemon will start writing out dirty data. Decreasing this number will cause the pdflush start wrtiting out the dirt data sooner, and it will limit the size of page cache.
 
vm.dirty_ratio (default=40)

Indicates the percentage of the number of pages at which the processes writes out their own dirty data. Decreasing this number will cause the processes to write out the dirty data sooner, and that will limit the page cache size.
 
vm.dirty_expire_centisecs ( default = 3000 , mentioned in milliseconds)
 
Indicates the expire time for the dirty pages , so that they became eligible to be flushed out by the pdflush. Decreasing this value wil make the more dirty data pages eligible for flush out and that will limit the page cache size.
 
vm.swappiness ( default=60)

Indicates, how soon you want to swap out the data, the more the value the more likely to swap. Decreasing this values will cause the machine to less likely to swap and thus more like to write data out to disk. And that will limit the Page cache size.
 
Note: Make this Value Zero , doesn’t stop your system from Swapping.
 
 

How to Change these kernel Parameters ?

 
If you want to change parameters dynamically on a running machine you can use the command similar to
 
echo “500” > proc/sys/vm/vfs_cache_pressure
 
If you want persistent configuration ( the below below command will make modification to /etc/sysctl.conf)
 
sysctl -w vm.vfs_cache_pressure=”500″
 
 
If you are experiencing the problem like your entire page cache occupying the physical memory you should initially consider to tune the parameters , phase by phase, changing the values by 15% to 20%. But don’t change them at one shot altogether, because modifications to these values could affect the performance of the system in significant manner either in positive or negative manner.
 
And don’t make multiple changes at a time until you confirm previous change doesn’t impact your systems negatively.