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. Seemm/ksm.c for its implementation,andhttp://lwn.net/Articles/306704/ andhttps://lwn.net/Articles/330589/

KSM was originally developed for use with KVM (where it was known asKernel Shared Memory), to fit more virtual machines into physical memory,by sharing the data common between them. But it can be useful to anyapplication which generates many instances of the same data.

The KSM daemon ksmd periodically scans those areas of user memorywhich have been registered with it, looking for pages of identicalcontent which can be replaced by a single write-protected page (whichis automatically copied if a process later wants to update itscontent). The amount of pages that KSM daemon scans in a single passand the time between the passes are configured usingsysfsinterface

KSM only merges anonymous (private) pages, never pagecache (file) pages.KSM’s merged pages were originally locked into kernel memory, but can nowbe swapped out just like other user pages (but sharing is broken when theyare 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 applicationhas 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 KSMunmerges whatever it merged in that range. Note: this unmerging callmay suddenly require more memory than is available - possibly failingwith EAGAIN, but more probably arousing the Out-Of-Memory killer.

If KSM is not configured into the running kernel, madvise MADV_MERGEABLEand MADV_UNMERGEABLE simply fail with EINVAL. If the running kernel wasbuilt with CONFIG_KSM=y, those calls will normally succeed: even if theKSM daemon is not currently running, MADV_MERGEABLE still registersthe range for whenever the KSM daemon is started; even if the rangecannot contain any pages which KSM could actually merge; even ifMADV_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_MERGEABLEor MADV_UNMERGEABLE region, the madvise may return ENOMEM if the processwill exceedvm.max_map_count (seeDocumentation for /proc/sys/vm/).

Like other madvise calls, they are intended for use on mapped areas ofthe user address space: they will report ENOMEM if the specified rangeincludes 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 lotof processing power: some installations will disable KSM for that reason.

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 sleepe.g.echo100>/sys/kernel/mm/ksm/pages_to_scan.

The pages_to_scan value cannot be changed ifadvisor_mode hasbeen set to scan-time.

Default: 100 (chosen for demonstration purposes)

sleep_millisecs

how many milliseconds ksmd should sleep before next scane.g.echo20>/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 residein the memory area of same NUMA node. That brings lowerlatency to access of shared pages. Systems with more nodes, atsignificant NUMA distances, are likely to benefit from thelower latency of setting 0. Smaller systems, which need tominimize memory usage, are likely to benefit from the greatersharing of setting 1 (default). You may wish to compare howyour system performs under each setting, before deciding onwhich to use.merge_across_nodes setting can be changed onlywhen there are no ksm shared pages in the system: set run 2 tounmerge pages first, then to 1 after changingmerge_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.echo1>/sys/kernel/mm/ksm/run,

  • set to 2 to stop ksmd and unmerge all pages currently merged, butleave mergeable areas registered for next run.

Default: 0 (must be changed to 1 to activate KSM, except ifCONFIG_SYSFS is disabled)

use_zero_pages

specifies whether empty pages (i.e. allocated pages that onlycontain zeroes) should be treated specially. When set to 1,empty pages are merged with the kernel zero page(s) instead ofwith each other as it would happen normally. This can improvethe performance on architectures with coloured zero pages,depending on the workload. Care should be taken when enablingthis setting, as it can potentially degrade the performance ofKSM for some workloads, for example if the checksums of pagescandidate for merging match the checksum of an emptypage. This setting can be changed at any time, it is onlyeffective 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 adeduplication limit to avoid high latency for virtual memoryoperations that involve traversal of the virtual mappings thatshare the KSM page. The minimum value is 2 as a newly createdKSM page will have at least two sharers. The higher this valuethe faster KSM will merge the memory and the higher thededuplication factor will be, but the slower the worst casevirtual mappings traversal could be for any given KSMpage. Slowing down this traversal means there will be higherlatency for certain virtual memory operations happening duringswapping, compaction, NUMA balancing and page migration, inturn decreasing responsiveness for the caller of those virtualmemory operations. The scheduler latency of other tasks notinvolved with the VM operations doing the virtual mappingstraversal is not affected by this parameter as thesetraversals are always schedule friendly themselves.

stable_node_chains_prune_millisecs

specifies how frequently KSM checks the metadata of the pagesthat hit the deduplication limit for stale information.Smaller milllisecs values will free up the KSM metadata withlower latency, but they will make ksmd use more CPU during thescan. It’s a noop if not a single KSM page hit themax_page_sharing yet.

smart_scan

Historically KSM checked every candidate page for each scan. It didnot take into account historic information. When smart scan isenabled, pages that have previously not been de-duplicated getskipped. How often these pages are skipped depends on how oftende-duplication has already been tried and failed. By default thisoptimization is enabled. Thepages_skipped metric shows howeffective the setting is.

advisor_mode

Theadvisor_mode selects the current advisor. Two modes aresupported: none and scan-time. The default is none. By settingadvisor_mode to scan-time, the scan time advisor is enabled.The section aboutadvisor explains in detail how the scan timeadvisor works.

adivsor_max_cpu

specifies the upper limit of the cpu percent usage of the ksmdbackground thread. The default is 70.

advisor_target_scan_time

specifies the target scan time in seconds to scan all the candidatepages. The default value is 200 seconds.

advisor_min_pages_to_scan

specifies the lower limit of thepages_to_scan parameter of thescan time advisor. The default is 500.

adivsor_max_pages_to_scan

specifies the upper limit of thepages_to_scan parameter of thescan 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 themax_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 byKSM when deduplicating.

Whenuse_zero_pages is/was enabled, the sum ofpages_sharing +ksm_zero_pages represents the actual number of pages saved by KSM.ifuse_zero_pages has never been enabled,ksm_zero_pages is 0.

A high ratio ofpages_sharing topages_shared indicates goodsharing, but a high ratio ofpages_unshared topages_sharingindicates wasted effort.pages_volatile embraces severaldifferent kinds of activity, but a high proportion there would alsoindicate poor use of madvise MADV_MERGEABLE.

The maximum possiblepages_sharing/pages_shared ratio is limited by themax_page_sharing tunable. To increase the ratiomax_page_sharing mustbe increased accordingly.

Monitoring KSM profit

KSM can save memory by merging identical pages, but also can consumeadditional memory, because it needs to generate a number of rmap_items tosave each scanned page’s brief rmap information. Some of these pages maybe merged, but some may not be abled to be merged after being checkedseveral times, which are unprofitable memory consumed.

  1. How to determine whether KSM save memory or consume memory in system-widerange? 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 ofpages_sharing +ksm_zero_pages of the system, and all_rmap_items can be easilyobtained by summingpages_sharing,pages_shared,pages_unsharedandpages_volatile.

  2. The KSM profit inner a single process can be similarly obtained by thefollowing approximate calculation:

    process_profit =~ ksm_saved_pages * sizeof(page) -                  ksm_rmap_items * sizeof(rmap_item).

    where ksm_saved_pages equals to the sum ofksm_merging_pages andksm_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 ofksm_rmap_items toksm_merging_pages means a bad madvise-applied policy, so developers oradministrators have to rethink how to change madvise policy. Giving an examplefor reference, a page’s size is usually 4K, and the rmap_item’s size isseparately 32B on 32-bit CPU architecture and 64B on 64-bit CPU architecture.so if theksm_rmap_items/ksm_merging_pages ratio exceeds 64 on 64-bit CPUor 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 COWor on swapping in copy. Those events could help users evaluate whether or howto use KSM. For example, if cow_ksm increases too fast, user may decrease therange 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 innote that KSM page might be copied when swapping in becausedo_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 observedthat during the startup of an application more candidate pages need to beprocessed. Without an advisor thepages_to_scan parameter needs to besized for the maximum number of candidate pages. The scan time advisor canchanges thepages_to_scan parameter based on demand.

The advisor can be enabled, so KSM can automatically adapt to changes in thenumber of candidate pages to scan. Two advisors are implemented: none andscan-time. With none, no advisor is enabled. The default is none.

The scan time advisor changes thepages_to_scan parameter based on theobserved scan times. The possible values for thepages_to_scan parameter islimited by theadvisor_max_cpu parameter. In addition there is also theadvisor_target_scan_time parameter. This parameter sets the target time toscan all the KSM candidate pages. The parameteradvisor_target_scan_timedecides how aggressive the scan time advisor scans candidate pages. Lowervalues make the scan time advisor to scan more aggressively. This is the mostimportant parameter for the configuration of the scan time advisor.

The initial value and the maximum value can be changed withadvisor_min_pages_to_scan andadvisor_max_pages_to_scan. The defaultvalues are sufficient for most workloads and use cases.

Thepages_to_scan parameter is re-calculated after a scan has been completed.

--Izik Eidus,Hugh Dickins, 17 Nov 2009