brintos

brintos / linux-shallow public Read only

0
0
Text · 14.5 KiB · ad8e7a4 Raw
324 lines · plain
1=======================2Kernel Samepage Merging3=======================4 5Overview6========7 8KSM is a memory-saving de-duplication feature, enabled by CONFIG_KSM=y,9added to the Linux kernel in 2.6.32.  See ``mm/ksm.c`` for its implementation,10and http://lwn.net/Articles/306704/ and https://lwn.net/Articles/330589/11 12KSM was originally developed for use with KVM (where it was known as13Kernel Shared Memory), to fit more virtual machines into physical memory,14by sharing the data common between them.  But it can be useful to any15application which generates many instances of the same data.16 17The KSM daemon ksmd periodically scans those areas of user memory18which have been registered with it, looking for pages of identical19content which can be replaced by a single write-protected page (which20is automatically copied if a process later wants to update its21content). The amount of pages that KSM daemon scans in a single pass22and the time between the passes are configured using :ref:`sysfs23interface <ksm_sysfs>`24 25KSM only merges anonymous (private) pages, never pagecache (file) pages.26KSM's merged pages were originally locked into kernel memory, but can now27be swapped out just like other user pages (but sharing is broken when they28are swapped back in: ksmd must rediscover their identity and merge again).29 30Controlling KSM with madvise31============================32 33KSM only operates on those areas of address space which an application34has advised to be likely candidates for merging, by using the madvise(2)35system call::36 37	int madvise(addr, length, MADV_MERGEABLE)38 39The app may call40 41::42 43	int madvise(addr, length, MADV_UNMERGEABLE)44 45to cancel that advice and restore unshared pages: whereupon KSM46unmerges whatever it merged in that range.  Note: this unmerging call47may suddenly require more memory than is available - possibly failing48with EAGAIN, but more probably arousing the Out-Of-Memory killer.49 50If KSM is not configured into the running kernel, madvise MADV_MERGEABLE51and MADV_UNMERGEABLE simply fail with EINVAL.  If the running kernel was52built with CONFIG_KSM=y, those calls will normally succeed: even if the53KSM daemon is not currently running, MADV_MERGEABLE still registers54the range for whenever the KSM daemon is started; even if the range55cannot contain any pages which KSM could actually merge; even if56MADV_UNMERGEABLE is applied to a range which was never MADV_MERGEABLE.57 58If a region of memory must be split into at least one new MADV_MERGEABLE59or MADV_UNMERGEABLE region, the madvise may return ENOMEM if the process60will exceed ``vm.max_map_count`` (see Documentation/admin-guide/sysctl/vm.rst).61 62Like other madvise calls, they are intended for use on mapped areas of63the user address space: they will report ENOMEM if the specified range64includes unmapped gaps (though working on the intervening mapped areas),65and might fail with EAGAIN if not enough memory for internal structures.66 67Applications should be considerate in their use of MADV_MERGEABLE,68restricting its use to areas likely to benefit.  KSM's scans may use a lot69of processing power: some installations will disable KSM for that reason.70 71.. _ksm_sysfs:72 73KSM daemon sysfs interface74==========================75 76The KSM daemon is controlled by sysfs files in ``/sys/kernel/mm/ksm/``,77readable by all but writable only by root:78 79pages_to_scan80        how many pages to scan before ksmd goes to sleep81        e.g. ``echo 100 > /sys/kernel/mm/ksm/pages_to_scan``.82 83        The pages_to_scan value cannot be changed if ``advisor_mode`` has84        been set to scan-time.85 86        Default: 100 (chosen for demonstration purposes)87 88sleep_millisecs89        how many milliseconds ksmd should sleep before next scan90        e.g. ``echo 20 > /sys/kernel/mm/ksm/sleep_millisecs``91 92        Default: 20 (chosen for demonstration purposes)93 94merge_across_nodes95        specifies if pages from different NUMA nodes can be merged.96        When set to 0, ksm merges only pages which physically reside97        in the memory area of same NUMA node. That brings lower98        latency to access of shared pages. Systems with more nodes, at99        significant NUMA distances, are likely to benefit from the100        lower latency of setting 0. Smaller systems, which need to101        minimize memory usage, are likely to benefit from the greater102        sharing of setting 1 (default). You may wish to compare how103        your system performs under each setting, before deciding on104        which to use. ``merge_across_nodes`` setting can be changed only105        when there are no ksm shared pages in the system: set run 2 to106        unmerge pages first, then to 1 after changing107        ``merge_across_nodes``, to remerge according to the new setting.108 109        Default: 1 (merging across nodes as in earlier releases)110 111run112        * 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, but115	  leave mergeable areas registered for next run.116 117        Default: 0 (must be changed to 1 to activate KSM, except if118        CONFIG_SYSFS is disabled)119 120use_zero_pages121        specifies whether empty pages (i.e. allocated pages that only122        contain zeroes) should be treated specially.  When set to 1,123        empty pages are merged with the kernel zero page(s) instead of124        with each other as it would happen normally. This can improve125        the performance on architectures with coloured zero pages,126        depending on the workload. Care should be taken when enabling127        this setting, as it can potentially degrade the performance of128        KSM for some workloads, for example if the checksums of pages129        candidate for merging match the checksum of an empty130        page. This setting can be changed at any time, it is only131        effective for pages merged after the change.132 133        Default: 0 (normal KSM behaviour as in earlier releases)134 135max_page_sharing136        Maximum sharing allowed for each KSM page. This enforces a137        deduplication limit to avoid high latency for virtual memory138        operations that involve traversal of the virtual mappings that139        share the KSM page. The minimum value is 2 as a newly created140        KSM page will have at least two sharers. The higher this value141        the faster KSM will merge the memory and the higher the142        deduplication factor will be, but the slower the worst case143        virtual mappings traversal could be for any given KSM144        page. Slowing down this traversal means there will be higher145        latency for certain virtual memory operations happening during146        swapping, compaction, NUMA balancing and page migration, in147        turn decreasing responsiveness for the caller of those virtual148        memory operations. The scheduler latency of other tasks not149        involved with the VM operations doing the virtual mappings150        traversal is not affected by this parameter as these151        traversals are always schedule friendly themselves.152 153stable_node_chains_prune_millisecs154        specifies how frequently KSM checks the metadata of the pages155        that hit the deduplication limit for stale information.156        Smaller milllisecs values will free up the KSM metadata with157        lower latency, but they will make ksmd use more CPU during the158        scan. It's a noop if not a single KSM page hit the159        ``max_page_sharing`` yet.160 161smart_scan162        Historically KSM checked every candidate page for each scan. It did163        not take into account historic information.  When smart scan is164        enabled, pages that have previously not been de-duplicated get165        skipped. How often these pages are skipped depends on how often166        de-duplication has already been tried and failed. By default this167        optimization is enabled.  The ``pages_skipped`` metric shows how168        effective the setting is.169 170advisor_mode171        The ``advisor_mode`` selects the current advisor. Two modes are172        supported: none and scan-time. The default is none. By setting173        ``advisor_mode`` to scan-time, the scan time advisor is enabled.174        The section about ``advisor`` explains in detail how the scan time175        advisor works.176 177adivsor_max_cpu178        specifies the upper limit of the cpu percent usage of the ksmd179        background thread. The default is 70.180 181advisor_target_scan_time182        specifies the target scan time in seconds to scan all the candidate183        pages. The default value is 200 seconds.184 185advisor_min_pages_to_scan186        specifies the lower limit of the ``pages_to_scan`` parameter of the187        scan time advisor. The default is 500.188 189adivsor_max_pages_to_scan190        specifies the upper limit of the ``pages_to_scan`` parameter of the191        scan time advisor. The default is 30000.192 193The effectiveness of KSM and MADV_MERGEABLE is shown in ``/sys/kernel/mm/ksm/``:194 195general_profit196        how effective is KSM. The calculation is explained below.197pages_scanned198        how many pages are being scanned for ksm199pages_shared200        how many shared pages are being used201pages_sharing202        how many more sites are sharing them i.e. how much saved203pages_unshared204        how many pages unique but repeatedly checked for merging205pages_volatile206        how many pages changing too fast to be placed in a tree207pages_skipped208        how many pages did the "smart" page scanning algorithm skip209full_scans210        how many times all mergeable areas have been scanned211stable_node_chains212        the number of KSM pages that hit the ``max_page_sharing`` limit213stable_node_dups214        number of duplicated KSM pages215ksm_zero_pages216        how many zero pages that are still mapped into processes were mapped by217        KSM when deduplicating.218 219When ``use_zero_pages`` is/was enabled, the sum of ``pages_sharing`` +220``ksm_zero_pages`` represents the actual number of pages saved by KSM.221if ``use_zero_pages`` has never been enabled, ``ksm_zero_pages`` is 0.222 223A high ratio of ``pages_sharing`` to ``pages_shared`` indicates good224sharing, but a high ratio of ``pages_unshared`` to ``pages_sharing``225indicates wasted effort.  ``pages_volatile`` embraces several226different kinds of activity, but a high proportion there would also227indicate poor use of madvise MADV_MERGEABLE.228 229The maximum possible ``pages_sharing/pages_shared`` ratio is limited by the230``max_page_sharing`` tunable. To increase the ratio ``max_page_sharing`` must231be increased accordingly.232 233Monitoring KSM profit234=====================235 236KSM can save memory by merging identical pages, but also can consume237additional memory, because it needs to generate a number of rmap_items to238save each scanned page's brief rmap information. Some of these pages may239be merged, but some may not be abled to be merged after being checked240several times, which are unprofitable memory consumed.241 2421) How to determine whether KSM save memory or consume memory in system-wide243   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 easily250   obtained by summing ``pages_sharing``, ``pages_shared``, ``pages_unshared``251   and ``pages_volatile``.252 2532) The KSM profit inner a single process can be similarly obtained by the254   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`` and260   ``ksm_zero_pages``, both of which are shown under the directory261   ``/proc/<pid>/ksm_stat``, and ksm_rmap_items is also shown in262   ``/proc/<pid>/ksm_stat``. The process profit is also shown in263   ``/proc/<pid>/ksm_stat`` as ksm_process_profit.264 265From the perspective of application, a high ratio of ``ksm_rmap_items`` to266``ksm_merging_pages`` means a bad madvise-applied policy, so developers or267administrators have to rethink how to change madvise policy. Giving an example268for reference, a page's size is usually 4K, and the rmap_item's size is269separately 32B on 32-bit CPU architecture and 64B on 64-bit CPU architecture.270so if the ``ksm_rmap_items/ksm_merging_pages`` ratio exceeds 64 on 64-bit CPU271or exceeds 128 on 32-bit CPU, then the app's madvise policy should be dropped,272because the ksm profit is approximately zero or negative.273 274Monitoring KSM events275=====================276 277There are some counters in /proc/vmstat that may be used to monitor KSM events.278KSM might help save memory, it's a tradeoff by may suffering delay on KSM COW279or on swapping in copy. Those events could help users evaluate whether or how280to use KSM. For example, if cow_ksm increases too fast, user may decrease the281range of madvise(, , MADV_MERGEABLE).282 283cow_ksm284	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 287ksm_swpin_copy288	is incremented every time a KSM page is copied when swapping in289	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 292Advisor293=======294 295The number of candidate pages for KSM is dynamic. It can be often observed296that during the startup of an application more candidate pages need to be297processed. Without an advisor the ``pages_to_scan`` parameter needs to be298sized for the maximum number of candidate pages. The scan time advisor can299changes the ``pages_to_scan`` parameter based on demand.300 301The advisor can be enabled, so KSM can automatically adapt to changes in the302number of candidate pages to scan. Two advisors are implemented: none and303scan-time. With none, no advisor is enabled. The default is none.304 305The scan time advisor changes the ``pages_to_scan`` parameter based on the306observed scan times. The possible values for the ``pages_to_scan`` parameter is307limited by the ``advisor_max_cpu`` parameter. In addition there is also the308``advisor_target_scan_time`` parameter. This parameter sets the target time to309scan all the KSM candidate pages. The parameter ``advisor_target_scan_time``310decides how aggressive the scan time advisor scans candidate pages. Lower311values make the scan time advisor to scan more aggressively. This is the most312important parameter for the configuration of the scan time advisor.313 314The initial value and the maximum value can be changed with315``advisor_min_pages_to_scan`` and ``advisor_max_pages_to_scan``. The default316values are sufficient for most workloads and use cases.317 318The ``pages_to_scan`` parameter is re-calculated after a scan has been completed.319 320 321--322Izik Eidus,323Hugh Dickins, 17 Nov 2009324