요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.
1. 요약·해설
원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.
2. 영어 원문 전체
번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.
원문 전체 펼치기
=======================
Kernel Samepage Merging
=======================
Overview
========
KSM is a memory-saving de-duplication feature, enabled by CONFIG_KSM=y,
added to the Linux kernel in 2.6.32. See ``mm/ksm.c`` for its implementation,
and http://lwn.net/Articles/306704/ and https://lwn.net/Articles/330589/
KSM was originally developed for use with KVM (where it was known as
Kernel Shared Memory), to fit more virtual machines into physical memory,
by sharing the data common between them. But it can be useful to any
application which generates many instances of the same data.
The KSM daemon ksmd periodically scans those areas of user memory
which have been registered with it, looking for pages of identical
content which can be replaced by a single write-protected page (which
is automatically copied if a process later wants to update its
content). The amount of pages that KSM daemon scans in a single pass
and the time between the passes are configured using :ref:`sysfs
interface <ksm_sysfs>`
KSM only merges anonymous (private) pages, never pagecache (file) pages.
KSM's merged pages were originally locked into kernel memory, but can now
be swapped out just like other user pages (but sharing is broken when they
are swapped back in: ksmd must rediscover their identity and merge again).
Controlling KSM with madvise
============================
KSM only operates on those areas of address space which an application
has advised to be likely candidates for merging, by using the madvise(2)
system call::
int madvise(addr, length, MADV_MERGEABLE)
The app may call
::
int madvise(addr, length, MADV_UNMERGEABLE)
to cancel that advice and restore unshared pages: whereupon KSM
unmerges whatever it merged in that range. Note: this unmerging call
may suddenly require more memory than is available - possibly failing
with EAGAIN, but more probably arousing the Out-Of-Memory killer.
If KSM is not configured into the running kernel, madvise MADV_MERGEABLE
and MADV_UNMERGEABLE simply fail with EINVAL. If the running kernel was
built with CONFIG_KSM=y, those calls will normally succeed: even if the
KSM daemon is not currently running, MADV_MERGEABLE still registers
the range for whenever the KSM daemon is started; even if the range
cannot contain any pages which KSM could actually merge; even if
MADV_UNMERGEABLE is applied to a range which was never MADV_MERGEABLE.
If a region of memory must be split into at least one new MADV_MERGEABLE
or MADV_UNMERGEABLE region, the madvise may return ENOMEM if the process
will exceed ``vm.max_map_count`` (see Documentation/admin-guide/sysctl/vm.rst).
Like other madvise calls, they are intended for use on mapped areas of
the user address space: they will report ENOMEM if the specified range
includes unmapped gaps (though working on the intervening mapped areas),
and might fail with EAGAIN if not enough memory for internal structures.
Applications should be considerate in their use of MADV_MERGEABLE,
restricting its use to areas likely to benefit. KSM's scans may use a lot
of processing power: some installations will disable KSM for that reason.
.. _ksm_sysfs:
KSM daemon sysfs interface
==========================
The KSM daemon is controlled by sysfs files in ``/sys/kernel/mm/ksm/``,
readable by all but writable only by root:
pages_to_scan
how many pages to scan before ksmd goes to sleep
e.g. ``echo 100 > /sys/kernel/mm/ksm/pages_to_scan``.
The pages_to_scan value cannot be changed if ``advisor_mode`` has
been set to scan-time.
Default: 100 (chosen for demonstration purposes)
sleep_millisecs
how many milliseconds ksmd should sleep before next scan
e.g. ``echo 20 > /sys/kernel/mm/ksm/sleep_millisecs``
Default: 20 (chosen for demonstration purposes)
merge_across_nodes
specifies if pages from different NUMA nodes can be merged.
When set to 0, ksm merges only pages which physically reside
in the memory area of same NUMA node. That brings lower
latency to access of shared pages. Systems with more nodes, at
significant NUMA distances, are likely to benefit from the
lower latency of setting 0. Smaller systems, which need to
minimize memory usage, are likely to benefit from the greater
sharing of setting 1 (default). You may wish to compare how
your system performs under each setting, before deciding on
which to use. ``merge_across_nodes`` setting can be changed only
when there are no ksm shared pages in the system: set run 2 to
unmerge pages first, then to 1 after changing
``merge_across_nodes``, to remerge according to the new setting.
Default: 1 (merging across nodes as in earlier releases)
run
* set to 0 to stop ksmd from running but keep merged pages,
* set to 1 to run ksmd e.g. ``echo 1 > /sys/kernel/mm/ksm/run``,
* set to 2 to stop ksmd and unmerge all pages currently merged, but
leave mergeable areas registered for next run.
Default: 0 (must be changed to 1 to activate KSM, except if
CONFIG_SYSFS is disabled)
use_zero_pages
specifies whether empty pages (i.e. allocated pages that only
contain zeroes) should be treated specially. When set to 1,
empty pages are merged with the kernel zero page(s) instead of
with each other as it would happen normally. This can improve
the performance on architectures with coloured zero pages,
depending on the workload. Care should be taken when enabling
this setting, as it can potentially degrade the performance of
KSM for some workloads, for example if the checksums of pages
candidate for merging match the checksum of an empty
page. This setting can be changed at any time, it is only
effective for pages merged after the change.
Default: 0 (normal KSM behaviour as in earlier releases)
max_page_sharing
Maximum sharing allowed for each KSM page. This enforces a
deduplication limit to avoid high latency for virtual memory
operations that involve traversal of the virtual mappings that
share the KSM page. The minimum value is 2 as a newly created
KSM page will have at least two sharers. The higher this value
the faster KSM will merge the memory and the higher the
deduplication factor will be, but the slower the worst case
virtual mappings traversal could be for any given KSM
page. Slowing down this traversal means there will be higher
latency for certain virtual memory operations happening during
swapping, compaction, NUMA balancing and page migration, in
turn decreasing responsiveness for the caller of those virtual
memory operations. The scheduler latency of other tasks not
involved with the VM operations doing the virtual mappings
traversal is not affected by this parameter as these
traversals are always schedule friendly themselves.
stable_node_chains_prune_millisecs
specifies how frequently KSM checks the metadata of the pages
that hit the deduplication limit for stale information.
Smaller milllisecs values will free up the KSM metadata with
lower latency, but they will make ksmd use more CPU during the
scan. It's a noop if not a single KSM page hit the
``max_page_sharing`` yet.
smart_scan
Historically KSM checked every candidate page for each scan. It did
not take into account historic information. When smart scan is
enabled, pages that have previously not been de-duplicated get
skipped. How often these pages are skipped depends on how often
de-duplication has already been tried and failed. By default this
optimization is enabled. The ``pages_skipped`` metric shows how
effective the setting is.
advisor_mode
The ``advisor_mode`` selects the current advisor. Two modes are
supported: none and scan-time. The default is none. By setting
``advisor_mode`` to scan-time, the scan time advisor is enabled.
The section about ``advisor`` explains in detail how the scan time
advisor works.
adivsor_max_cpu
specifies the upper limit of the cpu percent usage of the ksmd
background thread. The default is 70.
advisor_target_scan_time
specifies the target scan time in seconds to scan all the candidate
pages. The default value is 200 seconds.
advisor_min_pages_to_scan
specifies the lower limit of the ``pages_to_scan`` parameter of the
scan time advisor. The default is 500.
adivsor_max_pages_to_scan
specifies the upper limit of the ``pages_to_scan`` parameter of the
scan time advisor. The default is 30000.
The effectiveness of KSM and MADV_MERGEABLE is shown in ``/sys/kernel/mm/ksm/``:
general_profit
how effective is KSM. The calculation is explained below.
pages_scanned
how many pages are being scanned for ksm
pages_shared
how many shared pages are being used
pages_sharing
how many more sites are sharing them i.e. how much saved
pages_unshared
how many pages unique but repeatedly checked for merging
pages_volatile
how many pages changing too fast to be placed in a tree
pages_skipped
how many pages did the "smart" page scanning algorithm skip
full_scans
how many times all mergeable areas have been scanned
stable_node_chains
the number of KSM pages that hit the ``max_page_sharing`` limit
stable_node_dups
number of duplicated KSM pages
ksm_zero_pages
how many zero pages that are still mapped into processes were mapped by
KSM when deduplicating.
When ``use_zero_pages`` is/was enabled, the sum of ``pages_sharing`` +
``ksm_zero_pages`` represents the actual number of pages saved by KSM.
if ``use_zero_pages`` has never been enabled, ``ksm_zero_pages`` is 0.
A high ratio of ``pages_sharing`` to ``pages_shared`` indicates good
sharing, but a high ratio of ``pages_unshared`` to ``pages_sharing``
indicates wasted effort. ``pages_volatile`` embraces several
different kinds of activity, but a high proportion there would also
indicate poor use of madvise MADV_MERGEABLE.
The maximum possible ``pages_sharing/pages_shared`` ratio is limited by the
``max_page_sharing`` tunable. To increase the ratio ``max_page_sharing`` must
be increased accordingly.
Monitoring KSM profit
=====================
KSM can save memory by merging identical pages, but also can consume
additional memory, because it needs to generate a number of rmap_items to
save each scanned page's brief rmap information. Some of these pages may
be merged, but some may not be abled to be merged after being checked
several times, which are unprofitable memory consumed.
1) How to determine whether KSM save memory or consume memory in system-wide
range? Here is a simple approximate calculation for reference::
general_profit =~ ksm_saved_pages * sizeof(page) - (all_rmap_items) *
sizeof(rmap_item);
where ksm_saved_pages equals to the sum of ``pages_sharing`` +
``ksm_zero_pages`` of the system, and all_rmap_items can be easily
obtained by summing ``pages_sharing``, ``pages_shared``, ``pages_unshared``
and ``pages_volatile``.
2) The KSM profit inner a single process can be similarly obtained by the
following approximate calculation::
process_profit =~ ksm_saved_pages * sizeof(page) -
ksm_rmap_items * sizeof(rmap_item).
where ksm_saved_pages equals to the sum of ``ksm_merging_pages`` and
``ksm_zero_pages``, both of which are shown under the directory
``/proc/<pid>/ksm_stat``, and ksm_rmap_items is also shown in
``/proc/<pid>/ksm_stat``. The process profit is also shown in
``/proc/<pid>/ksm_stat`` as ksm_process_profit.
From the perspective of application, a high ratio of ``ksm_rmap_items`` to
``ksm_merging_pages`` means a bad madvise-applied policy, so developers or
administrators have to rethink how to change madvise policy. Giving an example
for reference, a page's size is usually 4K, and the rmap_item's size is
separately 32B on 32-bit CPU architecture and 64B on 64-bit CPU architecture.
so if the ``ksm_rmap_items/ksm_merging_pages`` ratio exceeds 64 on 64-bit CPU
or exceeds 128 on 32-bit CPU, then the app's madvise policy should be dropped,
because the ksm profit is approximately zero or negative.
Monitoring KSM events
=====================
There are some counters in /proc/vmstat that may be used to monitor KSM events.
KSM might help save memory, it's a tradeoff by may suffering delay on KSM COW
or on swapping in copy. Those events could help users evaluate whether or how
to use KSM. For example, if cow_ksm increases too fast, user may decrease the
range of madvise(, , MADV_MERGEABLE).
cow_ksm
is incremented every time a KSM page triggers copy on write (COW)
when users try to write to a KSM page, we have to make a copy.
ksm_swpin_copy
is incremented every time a KSM page is copied when swapping in
note that KSM page might be copied when swapping in because do_swap_page()
cannot do all the locking needed to reconstitute a cross-anon_vma KSM page.
Advisor
=======
The number of candidate pages for KSM is dynamic. It can be often observed
that during the startup of an application more candidate pages need to be
processed. Without an advisor the ``pages_to_scan`` parameter needs to be
sized for the maximum number of candidate pages. The scan time advisor can
changes the ``pages_to_scan`` parameter based on demand.
The advisor can be enabled, so KSM can automatically adapt to changes in the
number of candidate pages to scan. Two advisors are implemented: none and
scan-time. With none, no advisor is enabled. The default is none.
The scan time advisor changes the ``pages_to_scan`` parameter based on the
observed scan times. The possible values for the ``pages_to_scan`` parameter is
limited by the ``advisor_max_cpu`` parameter. In addition there is also the
``advisor_target_scan_time`` parameter. This parameter sets the target time to
scan all the KSM candidate pages. The parameter ``advisor_target_scan_time``
decides how aggressive the scan time advisor scans candidate pages. Lower
values make the scan time advisor to scan more aggressively. This is the most
important parameter for the configuration of the scan time advisor.
The initial value and the maximum value can be changed with
``advisor_min_pages_to_scan`` and ``advisor_max_pages_to_scan``. The default
values are sufficient for most workloads and use cases.
The ``pages_to_scan`` parameter is re-calculated after a scan has been completed.
--
Izik Eidus,
Hugh Dickins, 17 Nov 2009
3. 한국어 전문 번역
영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.
KSM 개요
1-29Kernel 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-70KSM은 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-118KSM daemon은 `/sys/kernel/mm/ksm/` 아래 sysfs 파일로 제어합니다. 모든 사용자가 읽을 수 있지만 root만 쓸 수 있습니다.
| 파일 | 기본값 | 역할 |
|---|---|---|
| pages_to_scan | 100 | ksmd가 sleep하기 전 한 pass에서 scan할 page 수 |
| sleep_millisecs | 20 | 다음 scan 전 ksmd sleep 시간, milliseconds |
| merge_across_nodes | 1 | 다른 NUMA node의 동일 page를 merge할지 선택 |
| run | 0 | 0 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_pages | 0 | empty page를 서로 merge하는 대신 kernel zero page에 mapping |
| max_page_sharing | kernel default | KSM page 하나가 허용할 최대 sharer 수, 최솟값 2 |
| stable_node_chains_prune_millisecs | kernel default | deduplication 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_scan | 1 | 반복해서 deduplicate되지 않은 page를 적응적으로 skip |
| advisor_mode | none | `none` 또는 `scan-time` advisor 선택 |
| adivsor_max_cpu | 70 | ksmd background thread CPU 사용률 상한, percent |
| advisor_target_scan_time | 200 | 모든 candidate page를 scan할 목표 시간, seconds |
| advisor_min_pages_to_scan | 500 | scan-time advisor가 정할 `pages_to_scan` 하한 |
| adivsor_max_pages_to_scan | 30000 | scan-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_profit | KSM의 system-wide 추정 순이익 |
| pages_scanned | KSM이 scan한 page 수 |
| pages_shared | 현재 사용하는 대표 shared KSM page 수 |
| pages_sharing | 대표 page를 추가로 공유하는 mapping 수, 기본 절감량 |
| pages_unshared | 고유하지만 merge 가능성을 반복 검사한 page 수 |
| pages_volatile | 너무 빨리 바뀌어 tree에 둘 수 없는 page 수 |
| pages_skipped | smart 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_pages | KSM이 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-273KSM은 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 pages | rmap items | 노출 profit |
|---|---|---|---|
| System | pages_sharing + ksm_zero_pages | pages_sharing + pages_shared + pages_unshared + pages_volatile | general_profit |
| Process | ksm_merging_pages + ksm_zero_pages | ksm_rmap_items | ksm_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_ksm | KSM page write가 copy-on-write를 일으킬 때마다 증가 |
| ksm_swpin_copy | swap-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-320KSM 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일입니다.
KSM 운영 지도
ksm.rst:1-323KSM은 identical anonymous page를 write-protected page 하나로 합쳐 memory를 절약합니다. Scan CPU, reverse-mapping metadata, COW·swap-in copy 비용이 있으므로 merge 범위를 신중히 고르고 tunable과 profit metric을 함께 봐야 합니다.