Merge tag 'block-6.3-2023-03-03' of git://git.kernel.dk/linux
[linux-block.git] / Documentation / admin-guide / mm / ksm.rst
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 intraface <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         Default: 100 (chosen for demonstration purposes)
84
85 sleep_millisecs
86         how many milliseconds ksmd should sleep before next scan
87         e.g. ``echo 20 > /sys/kernel/mm/ksm/sleep_millisecs``
88
89         Default: 20 (chosen for demonstration purposes)
90
91 merge_across_nodes
92         specifies if pages from different NUMA nodes can be merged.
93         When set to 0, ksm merges only pages which physically reside
94         in the memory area of same NUMA node. That brings lower
95         latency to access of shared pages. Systems with more nodes, at
96         significant NUMA distances, are likely to benefit from the
97         lower latency of setting 0. Smaller systems, which need to
98         minimize memory usage, are likely to benefit from the greater
99         sharing of setting 1 (default). You may wish to compare how
100         your system performs under each setting, before deciding on
101         which to use. ``merge_across_nodes`` setting can be changed only
102         when there are no ksm shared pages in the system: set run 2 to
103         unmerge pages first, then to 1 after changing
104         ``merge_across_nodes``, to remerge according to the new setting.
105
106         Default: 1 (merging across nodes as in earlier releases)
107
108 run
109         * set to 0 to stop ksmd from running but keep merged pages,
110         * set to 1 to run ksmd e.g. ``echo 1 > /sys/kernel/mm/ksm/run``,
111         * set to 2 to stop ksmd and unmerge all pages currently merged, but
112           leave mergeable areas registered for next run.
113
114         Default: 0 (must be changed to 1 to activate KSM, except if
115         CONFIG_SYSFS is disabled)
116
117 use_zero_pages
118         specifies whether empty pages (i.e. allocated pages that only
119         contain zeroes) should be treated specially.  When set to 1,
120         empty pages are merged with the kernel zero page(s) instead of
121         with each other as it would happen normally. This can improve
122         the performance on architectures with coloured zero pages,
123         depending on the workload. Care should be taken when enabling
124         this setting, as it can potentially degrade the performance of
125         KSM for some workloads, for example if the checksums of pages
126         candidate for merging match the checksum of an empty
127         page. This setting can be changed at any time, it is only
128         effective for pages merged after the change.
129
130         Default: 0 (normal KSM behaviour as in earlier releases)
131
132 max_page_sharing
133         Maximum sharing allowed for each KSM page. This enforces a
134         deduplication limit to avoid high latency for virtual memory
135         operations that involve traversal of the virtual mappings that
136         share the KSM page. The minimum value is 2 as a newly created
137         KSM page will have at least two sharers. The higher this value
138         the faster KSM will merge the memory and the higher the
139         deduplication factor will be, but the slower the worst case
140         virtual mappings traversal could be for any given KSM
141         page. Slowing down this traversal means there will be higher
142         latency for certain virtual memory operations happening during
143         swapping, compaction, NUMA balancing and page migration, in
144         turn decreasing responsiveness for the caller of those virtual
145         memory operations. The scheduler latency of other tasks not
146         involved with the VM operations doing the virtual mappings
147         traversal is not affected by this parameter as these
148         traversals are always schedule friendly themselves.
149
150 stable_node_chains_prune_millisecs
151         specifies how frequently KSM checks the metadata of the pages
152         that hit the deduplication limit for stale information.
153         Smaller milllisecs values will free up the KSM metadata with
154         lower latency, but they will make ksmd use more CPU during the
155         scan. It's a noop if not a single KSM page hit the
156         ``max_page_sharing`` yet.
157
158 The effectiveness of KSM and MADV_MERGEABLE is shown in ``/sys/kernel/mm/ksm/``:
159
160 pages_shared
161         how many shared pages are being used
162 pages_sharing
163         how many more sites are sharing them i.e. how much saved
164 pages_unshared
165         how many pages unique but repeatedly checked for merging
166 pages_volatile
167         how many pages changing too fast to be placed in a tree
168 full_scans
169         how many times all mergeable areas have been scanned
170 stable_node_chains
171         the number of KSM pages that hit the ``max_page_sharing`` limit
172 stable_node_dups
173         number of duplicated KSM pages
174
175 A high ratio of ``pages_sharing`` to ``pages_shared`` indicates good
176 sharing, but a high ratio of ``pages_unshared`` to ``pages_sharing``
177 indicates wasted effort.  ``pages_volatile`` embraces several
178 different kinds of activity, but a high proportion there would also
179 indicate poor use of madvise MADV_MERGEABLE.
180
181 The maximum possible ``pages_sharing/pages_shared`` ratio is limited by the
182 ``max_page_sharing`` tunable. To increase the ratio ``max_page_sharing`` must
183 be increased accordingly.
184
185 Monitoring KSM profit
186 =====================
187
188 KSM can save memory by merging identical pages, but also can consume
189 additional memory, because it needs to generate a number of rmap_items to
190 save each scanned page's brief rmap information. Some of these pages may
191 be merged, but some may not be abled to be merged after being checked
192 several times, which are unprofitable memory consumed.
193
194 1) How to determine whether KSM save memory or consume memory in system-wide
195    range? Here is a simple approximate calculation for reference::
196
197         general_profit =~ pages_sharing * sizeof(page) - (all_rmap_items) *
198                           sizeof(rmap_item);
199
200    where all_rmap_items can be easily obtained by summing ``pages_sharing``,
201    ``pages_shared``, ``pages_unshared`` and ``pages_volatile``.
202
203 2) The KSM profit inner a single process can be similarly obtained by the
204    following approximate calculation::
205
206         process_profit =~ ksm_merging_pages * sizeof(page) -
207                           ksm_rmap_items * sizeof(rmap_item).
208
209    where ksm_merging_pages is shown under the directory ``/proc/<pid>/``,
210    and ksm_rmap_items is shown in ``/proc/<pid>/ksm_stat``.
211
212 From the perspective of application, a high ratio of ``ksm_rmap_items`` to
213 ``ksm_merging_pages`` means a bad madvise-applied policy, so developers or
214 administrators have to rethink how to change madvise policy. Giving an example
215 for reference, a page's size is usually 4K, and the rmap_item's size is
216 separately 32B on 32-bit CPU architecture and 64B on 64-bit CPU architecture.
217 so if the ``ksm_rmap_items/ksm_merging_pages`` ratio exceeds 64 on 64-bit CPU
218 or exceeds 128 on 32-bit CPU, then the app's madvise policy should be dropped,
219 because the ksm profit is approximately zero or negative.
220
221 Monitoring KSM events
222 =====================
223
224 There are some counters in /proc/vmstat that may be used to monitor KSM events.
225 KSM might help save memory, it's a tradeoff by may suffering delay on KSM COW
226 or on swapping in copy. Those events could help users evaluate whether or how
227 to use KSM. For example, if cow_ksm increases too fast, user may decrease the
228 range of madvise(, , MADV_MERGEABLE).
229
230 cow_ksm
231         is incremented every time a KSM page triggers copy on write (COW)
232         when users try to write to a KSM page, we have to make a copy.
233
234 ksm_swpin_copy
235         is incremented every time a KSM page is copied when swapping in
236         note that KSM page might be copied when swapping in because do_swap_page()
237         cannot do all the locking needed to reconstitute a cross-anon_vma KSM page.
238
239 --
240 Izik Eidus,
241 Hugh Dickins, 17 Nov 2009