ksm.rst 14 KB

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