← Documents Documentation/admin-guide/mm/ksm.rst GitHub 원문 ↗

Linux 6.18.37 · Administration / Memory Management

Kernel Samepage Merging

KSM의 madvise 등록, ksmd scan·NUMA·sharing tunable, advisor, 통계와 실제 memory profit 계산을 설명합니다.

Source pathDocumentation/admin-guide/mm/ksm.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.

1. 요약·해설

원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.

KSM 운영 지도

ksm.rst:1-323

KSM은 identical anonymous page를 write-protected page 하나로 합쳐 memory를 절약합니다. Scan CPU, reverse-mapping metadata, COW·swap-in copy 비용이 있으므로 merge 범위를 신중히 고르고 tunable과 profit metric을 함께 봐야 합니다.

단계interface목적
Registermadvise(..., MADV_MERGEABLE)merge candidate 범위 지정
Daemon/sys/kernel/mm/ksm/runksmd start·stop·unmerge
Scanpages_to_scan, sleep_millisecs, smart_scanscan 비용 조절
NUMAmerge_across_nodessharing 양과 access latency 균형
Advisoradvisor_mode=scan-timecandidate 수에 맞춰 scan 자동 조정
Profitgeneral_profit, /proc/<pid>/ksm_stat절감량과 metadata 비용 비교

2. 영어 원문 전체

번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.

원문 전체 펼치기
1 =======================
2 Kernel Samepage Merging
3 =======================
4
5 Overview
6 ========
7
8 KSM is a memory-saving de-duplication feature, enabled by CONFIG_KSM=y,
9 added to the Linux kernel in 2.6.32. See ``mm/ksm.c`` for its implementation,
10 and http://lwn.net/Articles/306704/ and https://lwn.net/Articles/330589/
11
12 KSM was originally developed for use with KVM (where it was known as
13 Kernel Shared Memory), to fit more virtual machines into physical memory,
14 by sharing the data common between them. But it can be useful to any
15 application which generates many instances of the same data.
16
17 The KSM daemon ksmd periodically scans those areas of user memory
18 which have been registered with it, looking for pages of identical
19 content which can be replaced by a single write-protected page (which
20 is automatically copied if a process later wants to update its
21 content). The amount of pages that KSM daemon scans in a single pass
22 and the time between the passes are configured using :ref:`sysfs
23 interface <ksm_sysfs>`
24
25 KSM only merges anonymous (private) pages, never pagecache (file) pages.
26 KSM's merged pages were originally locked into kernel memory, but can now
27 be swapped out just like other user pages (but sharing is broken when they
28 are swapped back in: ksmd must rediscover their identity and merge again).
29
30 Controlling KSM with madvise
31 ============================
32
33 KSM only operates on those areas of address space which an application
34 has advised to be likely candidates for merging, by using the madvise(2)
35 system call::
36
37 int madvise(addr, length, MADV_MERGEABLE)
38
39 The app may call
40
41 ::
42
43 int madvise(addr, length, MADV_UNMERGEABLE)
44
45 to cancel that advice and restore unshared pages: whereupon KSM
46 unmerges whatever it merged in that range. Note: this unmerging call
47 may suddenly require more memory than is available - possibly failing
48 with EAGAIN, but more probably arousing the Out-Of-Memory killer.
49
50 If KSM is not configured into the running kernel, madvise MADV_MERGEABLE
51 and MADV_UNMERGEABLE simply fail with EINVAL. If the running kernel was
52 built with CONFIG_KSM=y, those calls will normally succeed: even if the
53 KSM daemon is not currently running, MADV_MERGEABLE still registers
54 the range for whenever the KSM daemon is started; even if the range
55 cannot contain any pages which KSM could actually merge; even if
56 MADV_UNMERGEABLE is applied to a range which was never MADV_MERGEABLE.
57
58 If a region of memory must be split into at least one new MADV_MERGEABLE
59 or MADV_UNMERGEABLE region, the madvise may return ENOMEM if the process
60 will exceed ``vm.max_map_count`` (see Documentation/admin-guide/sysctl/vm.rst).
61
62 Like other madvise calls, they are intended for use on mapped areas of
63 the user address space: they will report ENOMEM if the specified range
64 includes unmapped gaps (though working on the intervening mapped areas),
65 and might fail with EAGAIN if not enough memory for internal structures.
66
67 Applications should be considerate in their use of MADV_MERGEABLE,
68 restricting its use to areas likely to benefit. KSM's scans may use a lot
69 of processing power: some installations will disable KSM for that reason.
70
71 .. _ksm_sysfs:
72
73 KSM daemon sysfs interface
74 ==========================
75
76 The KSM daemon is controlled by sysfs files in ``/sys/kernel/mm/ksm/``,
77 readable by all but writable only by root:
78
79 pages_to_scan
80 how many pages to scan before ksmd goes to sleep
81 e.g. ``echo 100 > /sys/kernel/mm/ksm/pages_to_scan``.
82
83 The pages_to_scan value cannot be changed if ``advisor_mode`` has
84 been set to scan-time.
85
86 Default: 100 (chosen for demonstration purposes)
87
88 sleep_millisecs
89 how many milliseconds ksmd should sleep before next scan
90 e.g. ``echo 20 > /sys/kernel/mm/ksm/sleep_millisecs``
91
92 Default: 20 (chosen for demonstration purposes)
93
94 merge_across_nodes
95 specifies if pages from different NUMA nodes can be merged.
96 When set to 0, ksm merges only pages which physically reside
97 in the memory area of same NUMA node. That brings lower
98 latency to access of shared pages. Systems with more nodes, at
99 significant NUMA distances, are likely to benefit from the
100 lower latency of setting 0. Smaller systems, which need to
101 minimize memory usage, are likely to benefit from the greater
102 sharing of setting 1 (default). You may wish to compare how
103 your system performs under each setting, before deciding on
104 which to use. ``merge_across_nodes`` setting can be changed only
105 when there are no ksm shared pages in the system: set run 2 to
106 unmerge pages first, then to 1 after changing
107 ``merge_across_nodes``, to remerge according to the new setting.
108
109 Default: 1 (merging across nodes as in earlier releases)
110
111 run
112 * set to 0 to stop ksmd from running but keep merged pages,
113 * set to 1 to run ksmd e.g. ``echo 1 > /sys/kernel/mm/ksm/run``,
114 * set to 2 to stop ksmd and unmerge all pages currently merged, but
115 leave mergeable areas registered for next run.
116
117 Default: 0 (must be changed to 1 to activate KSM, except if
118 CONFIG_SYSFS is disabled)
119
120 use_zero_pages
121 specifies whether empty pages (i.e. allocated pages that only
122 contain zeroes) should be treated specially. When set to 1,
123 empty pages are merged with the kernel zero page(s) instead of
124 with each other as it would happen normally. This can improve
125 the performance on architectures with coloured zero pages,
126 depending on the workload. Care should be taken when enabling
127 this setting, as it can potentially degrade the performance of
128 KSM for some workloads, for example if the checksums of pages
129 candidate for merging match the checksum of an empty
130 page. This setting can be changed at any time, it is only
131 effective for pages merged after the change.
132
133 Default: 0 (normal KSM behaviour as in earlier releases)
134
135 max_page_sharing
136 Maximum sharing allowed for each KSM page. This enforces a
137 deduplication limit to avoid high latency for virtual memory
138 operations that involve traversal of the virtual mappings that
139 share the KSM page. The minimum value is 2 as a newly created
140 KSM page will have at least two sharers. The higher this value
141 the faster KSM will merge the memory and the higher the
142 deduplication factor will be, but the slower the worst case
143 virtual mappings traversal could be for any given KSM
144 page. Slowing down this traversal means there will be higher
145 latency for certain virtual memory operations happening during
146 swapping, compaction, NUMA balancing and page migration, in
147 turn decreasing responsiveness for the caller of those virtual
148 memory operations. The scheduler latency of other tasks not
149 involved with the VM operations doing the virtual mappings
150 traversal is not affected by this parameter as these
151 traversals are always schedule friendly themselves.
152
153 stable_node_chains_prune_millisecs
154 specifies how frequently KSM checks the metadata of the pages
155 that hit the deduplication limit for stale information.
156 Smaller milllisecs values will free up the KSM metadata with
157 lower latency, but they will make ksmd use more CPU during the
158 scan. It's a noop if not a single KSM page hit the
159 ``max_page_sharing`` yet.
160
161 smart_scan
162 Historically KSM checked every candidate page for each scan. It did
163 not take into account historic information. When smart scan is
164 enabled, pages that have previously not been de-duplicated get
165 skipped. How often these pages are skipped depends on how often
166 de-duplication has already been tried and failed. By default this
167 optimization is enabled. The ``pages_skipped`` metric shows how
168 effective the setting is.
169
170 advisor_mode
171 The ``advisor_mode`` selects the current advisor. Two modes are
172 supported: none and scan-time. The default is none. By setting
173 ``advisor_mode`` to scan-time, the scan time advisor is enabled.
174 The section about ``advisor`` explains in detail how the scan time
175 advisor works.
176
177 adivsor_max_cpu
178 specifies the upper limit of the cpu percent usage of the ksmd
179 background thread. The default is 70.
180
181 advisor_target_scan_time
182 specifies the target scan time in seconds to scan all the candidate
183 pages. The default value is 200 seconds.
184
185 advisor_min_pages_to_scan
186 specifies the lower limit of the ``pages_to_scan`` parameter of the
187 scan time advisor. The default is 500.
188
189 adivsor_max_pages_to_scan
190 specifies the upper limit of the ``pages_to_scan`` parameter of the
191 scan time advisor. The default is 30000.
192
193 The effectiveness of KSM and MADV_MERGEABLE is shown in ``/sys/kernel/mm/ksm/``:
194
195 general_profit
196 how effective is KSM. The calculation is explained below.
197 pages_scanned
198 how many pages are being scanned for ksm
199 pages_shared
200 how many shared pages are being used
201 pages_sharing
202 how many more sites are sharing them i.e. how much saved
203 pages_unshared
204 how many pages unique but repeatedly checked for merging
205 pages_volatile
206 how many pages changing too fast to be placed in a tree
207 pages_skipped
208 how many pages did the "smart" page scanning algorithm skip
209 full_scans
210 how many times all mergeable areas have been scanned
211 stable_node_chains
212 the number of KSM pages that hit the ``max_page_sharing`` limit
213 stable_node_dups
214 number of duplicated KSM pages
215 ksm_zero_pages
216 how many zero pages that are still mapped into processes were mapped by
217 KSM when deduplicating.
218
219 When ``use_zero_pages`` is/was enabled, the sum of ``pages_sharing`` +
220 ``ksm_zero_pages`` represents the actual number of pages saved by KSM.
221 if ``use_zero_pages`` has never been enabled, ``ksm_zero_pages`` is 0.
222
223 A high ratio of ``pages_sharing`` to ``pages_shared`` indicates good
224 sharing, but a high ratio of ``pages_unshared`` to ``pages_sharing``
225 indicates wasted effort. ``pages_volatile`` embraces several
226 different kinds of activity, but a high proportion there would also
227 indicate poor use of madvise MADV_MERGEABLE.
228
229 The maximum possible ``pages_sharing/pages_shared`` ratio is limited by the
230 ``max_page_sharing`` tunable. To increase the ratio ``max_page_sharing`` must
231 be increased accordingly.
232
233 Monitoring KSM profit
234 =====================
235
236 KSM can save memory by merging identical pages, but also can consume
237 additional memory, because it needs to generate a number of rmap_items to
238 save each scanned page's brief rmap information. Some of these pages may
239 be merged, but some may not be abled to be merged after being checked
240 several times, which are unprofitable memory consumed.
241
242 1) How to determine whether KSM save memory or consume memory in system-wide
243 range? Here is a simple approximate calculation for reference::
244
245 general_profit =~ ksm_saved_pages * sizeof(page) - (all_rmap_items) *
246 sizeof(rmap_item);
247
248 where ksm_saved_pages equals to the sum of ``pages_sharing`` +
249 ``ksm_zero_pages`` of the system, and all_rmap_items can be easily
250 obtained by summing ``pages_sharing``, ``pages_shared``, ``pages_unshared``
251 and ``pages_volatile``.
252
253 2) The KSM profit inner a single process can be similarly obtained by the
254 following approximate calculation::
255
256 process_profit =~ ksm_saved_pages * sizeof(page) -
257 ksm_rmap_items * sizeof(rmap_item).
258
259 where ksm_saved_pages equals to the sum of ``ksm_merging_pages`` and
260 ``ksm_zero_pages``, both of which are shown under the directory
261 ``/proc/<pid>/ksm_stat``, and ksm_rmap_items is also shown in
262 ``/proc/<pid>/ksm_stat``. The process profit is also shown in
263 ``/proc/<pid>/ksm_stat`` as ksm_process_profit.
264
265 From the perspective of application, a high ratio of ``ksm_rmap_items`` to
266 ``ksm_merging_pages`` means a bad madvise-applied policy, so developers or
267 administrators have to rethink how to change madvise policy. Giving an example
268 for reference, a page's size is usually 4K, and the rmap_item's size is
269 separately 32B on 32-bit CPU architecture and 64B on 64-bit CPU architecture.
270 so if the ``ksm_rmap_items/ksm_merging_pages`` ratio exceeds 64 on 64-bit CPU
271 or exceeds 128 on 32-bit CPU, then the app's madvise policy should be dropped,
272 because the ksm profit is approximately zero or negative.
273
274 Monitoring KSM events
275 =====================
276
277 There are some counters in /proc/vmstat that may be used to monitor KSM events.
278 KSM might help save memory, it's a tradeoff by may suffering delay on KSM COW
279 or on swapping in copy. Those events could help users evaluate whether or how
280 to use KSM. For example, if cow_ksm increases too fast, user may decrease the
281 range of madvise(, , MADV_MERGEABLE).
282
283 cow_ksm
284 is incremented every time a KSM page triggers copy on write (COW)
285 when users try to write to a KSM page, we have to make a copy.
286
287 ksm_swpin_copy
288 is incremented every time a KSM page is copied when swapping in
289 note that KSM page might be copied when swapping in because do_swap_page()
290 cannot do all the locking needed to reconstitute a cross-anon_vma KSM page.
291
292 Advisor
293 =======
294
295 The number of candidate pages for KSM is dynamic. It can be often observed
296 that during the startup of an application more candidate pages need to be
297 processed. Without an advisor the ``pages_to_scan`` parameter needs to be
298 sized for the maximum number of candidate pages. The scan time advisor can
299 changes the ``pages_to_scan`` parameter based on demand.
300
301 The advisor can be enabled, so KSM can automatically adapt to changes in the
302 number of candidate pages to scan. Two advisors are implemented: none and
303 scan-time. With none, no advisor is enabled. The default is none.
304
305 The scan time advisor changes the ``pages_to_scan`` parameter based on the
306 observed scan times. The possible values for the ``pages_to_scan`` parameter is
307 limited by the ``advisor_max_cpu`` parameter. In addition there is also the
308 ``advisor_target_scan_time`` parameter. This parameter sets the target time to
309 scan all the KSM candidate pages. The parameter ``advisor_target_scan_time``
310 decides how aggressive the scan time advisor scans candidate pages. Lower
311 values make the scan time advisor to scan more aggressively. This is the most
312 important parameter for the configuration of the scan time advisor.
313
314 The initial value and the maximum value can be changed with
315 ``advisor_min_pages_to_scan`` and ``advisor_max_pages_to_scan``. The default
316 values are sufficient for most workloads and use cases.
317
318 The ``pages_to_scan`` parameter is re-calculated after a scan has been completed.
319
320
321 --
322 Izik Eidus,
323 Hugh Dickins, 17 Nov 2009
324

3. 한국어 전문 번역

영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.

KSM 개요

1-29

Kernel Samepage Merging(KSM)은 `CONFIG_KSM=y`로 활성화하는 memory deduplication 기능이며 Linux 2.6.32에 추가됐습니다. 구현은 `mm/ksm.c`에 있습니다.

KSM은 원래 KVM에서 여러 virtual machine의 공통 데이터를 공유해 physical memory에 더 많은 VM을 넣기 위해 Kernel Shared Memory라는 이름으로 개발됐지만, 동일 데이터 instance를 많이 만드는 application에도 유용합니다.

KSM daemon `ksmd`는 등록된 user memory area를 주기적으로 scan하고 내용이 같은 page들을 write-protected page 하나로 대체합니다. Process가 나중에 내용을 수정하면 copy-on-write로 자동 복사합니다. 한 pass의 scan page 수와 pass 간격은 sysfs interface로 조절합니다.

KSM은 anonymous private page만 merge하고 pagecache file page는 merge하지 않습니다. Merged page도 일반 user page처럼 swap out할 수 있지만 swap-in 뒤에는 sharing이 깨지므로 ksmd가 같은 내용을 다시 발견해 merge해야 합니다.

madvise로 범위 제어

30-70

KSM은 application이 `madvise(2)`로 merge candidate라고 알린 address range에서만 동작합니다.

int madvise(addr, length, MADV_MERGEABLE)

Advice를 취소하고 page를 다시 private하게 만들려면 다음 호출을 사용합니다. KSM은 해당 range에서 merge한 page를 unmerge합니다.

int madvise(addr, length, MADV_UNMERGEABLE)

`MADV_UNMERGEABLE`은 갑자기 더 많은 memory가 필요할 수 있습니다. Memory가 부족하면 `EAGAIN`으로 실패할 수 있지만 Out-Of-Memory killer를 깨울 가능성이 더 큽니다.

실행 kernel에 KSM이 없으면 `MADV_MERGEABLE`과 `MADV_UNMERGEABLE`은 `EINVAL`로 실패합니다. `CONFIG_KSM=y` build라면 ksmd가 멈춰 있어도 MERGEABLE range를 다음 실행을 위해 등록하고, 실제 merge 가능한 page가 없어도 성공합니다. 한 번도 MERGEABLE이 아니었던 range에 UNMERGEABLE을 적용해도 보통 성공합니다.

새 MERGEABLE 또는 UNMERGEABLE region을 만들기 위해 VMA를 split해야 하고 process가 `vm.max_map_count`를 넘으면 `ENOMEM`을 반환할 수 있습니다. 설정은 `Documentation/admin-guide/sysctl/vm.rst`를 참조합니다.

다른 `madvise`처럼 mapped user address area에 사용해야 합니다. Range에 unmapped gap이 있으면 사이의 mapped area에는 작업하면서 `ENOMEM`을 보고하고, 내부 구조용 memory가 부족하면 `EAGAIN`일 수 있습니다. Scan은 CPU를 많이 쓸 수 있으므로 실제 deduplication 이익이 예상되는 range로 제한해야 합니다.

핵심 daemon tunable

71-118

KSM daemon은 `/sys/kernel/mm/ksm/` 아래 sysfs 파일로 제어합니다. 모든 사용자가 읽을 수 있지만 root만 쓸 수 있습니다.

파일기본값역할
pages_to_scan100ksmd가 sleep하기 전 한 pass에서 scan할 page 수
sleep_millisecs20다음 scan 전 ksmd sleep 시간, milliseconds
merge_across_nodes1다른 NUMA node의 동일 page를 merge할지 선택
run00 stop, 1 run, 2 stop하고 현재 merge page를 모두 unmerge

`pages_to_scan`은 ksmd가 sleep하기 전 scan할 page 수이며 예시는 `echo 100 > /sys/kernel/mm/ksm/pages_to_scan`입니다. `advisor_mode=scan-time`이면 advisor가 값을 관리하므로 직접 바꿀 수 없습니다. `sleep_millisecs`는 pass 사이 sleep milliseconds입니다.

`merge_across_nodes=0`은 같은 NUMA node의 physical memory에 있는 page끼리만 merge해 shared page access latency를 낮춥니다. NUMA distance가 큰 system에 유리할 수 있습니다. 1은 node를 넘어 더 많이 공유해 memory 사용량을 최소화하며 기본값입니다.

`merge_across_nodes`는 system에 KSM shared page가 없을 때만 바꿀 수 있습니다. `run=2`로 먼저 unmerge하고 설정을 바꾼 뒤 `run=1`로 새 정책에 따라 다시 merge합니다.

`run=0`은 ksmd만 멈추고 merged page를 유지합니다. 1은 ksmd를 실행하며 `echo 1 > /sys/kernel/mm/ksm/run`으로 설정합니다. 2는 daemon을 멈추고 현재 merged page를 모두 unmerge하지만 mergeable area 등록은 다음 실행을 위해 남깁니다. 기본값은 0이며 `CONFIG_SYSFS`가 꺼진 경우를 제외하면 1로 바꿔야 KSM이 활성화됩니다.

zero page와 sharing limit

119-160
파일기본값역할
use_zero_pages0empty page를 서로 merge하는 대신 kernel zero page에 mapping
max_page_sharingkernel defaultKSM page 하나가 허용할 최대 sharer 수, 최솟값 2
stable_node_chains_prune_millisecskernel defaultdeduplication limit에 닿은 page metadata의 stale check 간격

`use_zero_pages=1`은 내용이 모두 0인 allocated page를 서로 merge하지 않고 kernel zero page에 mapping합니다. Coloured zero page architecture에서는 성능을 높일 수 있지만 candidate checksum이 empty page와 자주 같으면 일부 workload에서 KSM 성능을 낮출 수 있습니다. 언제든 바꿀 수 있으나 변경 뒤 새로 merge하는 page에만 적용됩니다.

`max_page_sharing`은 KSM page 하나의 sharer 상한입니다. 새 KSM page에는 적어도 두 sharer가 있으므로 최솟값은 2입니다. 값을 높이면 merge 속도와 deduplication factor는 좋아지지만 virtual mapping traversal의 최악 latency가 커집니다.

긴 mapping traversal은 swapping, compaction, NUMA balancing, page migration의 일부 VM operation 응답성을 낮출 수 있습니다. Traversal 자체가 scheduler-friendly하므로 해당 VM operation에 관여하지 않는 task의 scheduler latency에는 영향을 주지 않습니다.

`stable_node_chains_prune_millisecs`는 sharing limit에 닿은 page metadata의 stale 정보를 검사하는 주기입니다. 값을 줄이면 metadata를 빨리 해제하지만 scan 중 ksmd CPU 사용이 늘며, 어떤 KSM page도 `max_page_sharing`에 닿지 않았다면 no-op입니다.

smart scan과 advisor 설정

161-192
파일기본값역할
smart_scan1반복해서 deduplicate되지 않은 page를 적응적으로 skip
advisor_modenone`none` 또는 `scan-time` advisor 선택
adivsor_max_cpu70ksmd background thread CPU 사용률 상한, percent
advisor_target_scan_time200모든 candidate page를 scan할 목표 시간, seconds
advisor_min_pages_to_scan500scan-time advisor가 정할 `pages_to_scan` 하한
adivsor_max_pages_to_scan30000scan-time advisor가 정할 `pages_to_scan` 상한

과거 KSM은 매 scan마다 모든 candidate page를 검사했습니다. `smart_scan`은 이전 deduplication 시도가 반복해서 실패한 page를 건너뛰며 실패 횟수에 따라 skip 빈도를 조절합니다. 기본으로 켜져 있고 `pages_skipped`가 효과를 보여 줍니다.

`advisor_mode`는 `none`과 `scan-time`을 지원하며 기본값은 none입니다. Scan-time advisor는 뒤의 Advisor 절에서 설명하는 방식으로 `pages_to_scan`을 자동 조절합니다.

원문 sysfs 목록은 `adivsor_max_cpu`와 `adivsor_max_pages_to_scan`으로 표기하지만 뒤의 설명은 `advisor_max_cpu`, `advisor_max_pages_to_scan`을 사용합니다. 오탈자 형태와 의도한 실제 이름을 모두 보존합니다.

KSM 효과 통계

193-232

`/sys/kernel/mm/ksm/`의 다음 metric으로 KSM과 `MADV_MERGEABLE`의 효과를 확인합니다.

metric의미
general_profitKSM의 system-wide 추정 순이익
pages_scannedKSM이 scan한 page 수
pages_shared현재 사용하는 대표 shared KSM page 수
pages_sharing대표 page를 추가로 공유하는 mapping 수, 기본 절감량
pages_unshared고유하지만 merge 가능성을 반복 검사한 page 수
pages_volatile너무 빨리 바뀌어 tree에 둘 수 없는 page 수
pages_skippedsmart page scan algorithm이 건너뛴 page 수
full_scans모든 mergeable area를 scan한 횟수
stable_node_chains`max_page_sharing` limit에 도달한 KSM page 수
stable_node_dups중복 KSM page 수
ksm_zero_pagesKSM이 zero page로 deduplicate해 process에 mapping한 수

`use_zero_pages`가 현재 또는 과거에 켜졌다면 실제 절약 page 수는 `pages_sharing + ksm_zero_pages`입니다. 한 번도 켠 적이 없으면 `ksm_zero_pages`는 0입니다.

`pages_sharing / pages_shared`가 높으면 sharing 효율이 좋습니다. 반면 `pages_unshared / pages_sharing`이나 `pages_volatile` 비중이 높으면 `MADV_MERGEABLE` 범위에 낭비가 많다는 신호입니다. 가능한 최대 sharing ratio는 `max_page_sharing`이 제한하므로 더 높이려면 tunable도 늘려야 합니다.

memory 절감 이익 계산

233-273

KSM은 identical page를 합쳐 memory를 절약하지만 scan page마다 짧은 reverse mapping 정보를 저장하는 `rmap_item` metadata memory를 추가로 씁니다. 여러 번 검사해도 merge되지 않는 page의 metadata는 순손실이 될 수 있습니다.

System-wide KSM profit의 단순 근사식은 다음과 같습니다.

general_profit =~ ksm_saved_pages * sizeof(page) - (all_rmap_items) *
sizeof(rmap_item);

`ksm_saved_pages`는 system의 `pages_sharing + ksm_zero_pages`이고, `all_rmap_items`는 `pages_sharing + pages_shared + pages_unshared + pages_volatile`로 구합니다.

Process 하나의 profit도 비슷하게 계산합니다.

process_profit =~ ksm_saved_pages * sizeof(page) -
ksm_rmap_items * sizeof(rmap_item).
범위saved pagesrmap items노출 profit
Systempages_sharing + ksm_zero_pagespages_sharing + pages_shared + pages_unshared + pages_volatilegeneral_profit
Processksm_merging_pages + ksm_zero_pagesksm_rmap_itemsksm_process_profit

Process 값은 `/proc/<pid>/ksm_stat`의 `ksm_merging_pages`, `ksm_zero_pages`, `ksm_rmap_items`, `ksm_process_profit`에서 확인합니다. `ksm_rmap_items / ksm_merging_pages`가 높으면 madvise policy가 좋지 않다는 뜻입니다.

일반 page가 4 KiB이고 `rmap_item`이 64-bit CPU에서 64 B, 32-bit CPU에서 32 B라고 보면 ratio가 각각 64 또는 128을 넘을 때 profit이 대략 0 이하가 되므로 application의 madvise policy를 제거해야 합니다.

KSM vmstat event

274-291

`/proc/vmstat`의 event counter는 KSM이 절약한 memory와 COW 또는 swap-in copy latency 사이의 tradeoff를 평가하게 합니다. 예를 들어 `cow_ksm`이 너무 빨리 증가하면 `madvise(..., MADV_MERGEABLE)` 범위를 줄일 수 있습니다.

event증가 조건
cow_ksmKSM page write가 copy-on-write를 일으킬 때마다 증가
ksm_swpin_copyswap-in 중 cross-anon_vma KSM page를 재구성하지 못해 copy할 때 증가

`ksm_swpin_copy`는 `do_swap_page()`가 cross-anon_vma KSM page를 재구성하는 데 필요한 모든 lock을 잡을 수 없어 swap-in 중 page를 복사할 때 증가합니다.

Scan-time advisor

292-320

KSM candidate page 수는 동적이며 application startup 때 특히 많아질 수 있습니다. Advisor가 없으면 최대 candidate 수에 맞춰 `pages_to_scan`을 고정해야 하지만 scan-time advisor는 수요에 따라 값을 바꿉니다.

구현된 mode는 `none`과 `scan-time` 두 가지이며 기본값 none은 advisor를 사용하지 않습니다. Scan-time advisor는 관측한 scan time을 바탕으로 `pages_to_scan`을 조정합니다.

`advisor_max_cpu`는 가능한 `pages_to_scan` 값에 CPU 상한을 적용합니다. `advisor_target_scan_time`은 모든 KSM candidate page를 scan할 목표 시간이며 낮을수록 더 공격적으로 scan합니다. Advisor 설정에서 가장 중요한 parameter입니다.

`advisor_min_pages_to_scan`과 `advisor_max_pages_to_scan`으로 초기·최대 범위를 바꿀 수 있지만 기본값은 대부분의 workload에 충분합니다. `pages_to_scan`은 full scan이 끝날 때마다 다시 계산됩니다.

작성자

321-323

이 문서의 원 작성자는 Izik Eidus와 Hugh Dickins이며 날짜는 2009년 11월 17일입니다.