memory.rst 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035
  1. ==========================
  2. Memory Resource Controller
  3. ==========================
  4. .. caution::
  5. This document is hopelessly outdated and it asks for a complete
  6. rewrite. It still contains a useful information so we are keeping it
  7. here but make sure to check the current code if you need a deeper
  8. understanding.
  9. .. note::
  10. The Memory Resource Controller has generically been referred to as the
  11. memory controller in this document. Do not confuse memory controller
  12. used here with the memory controller that is used in hardware.
  13. .. hint::
  14. When we mention a cgroup (cgroupfs's directory) with memory controller,
  15. we call it "memory cgroup". When you see git-log and source code, you'll
  16. see patch's title and function names tend to use "memcg".
  17. In this document, we avoid using it.
  18. Benefits and Purpose of the memory controller
  19. =============================================
  20. The memory controller isolates the memory behaviour of a group of tasks
  21. from the rest of the system. The article on LWN [12]_ mentions some probable
  22. uses of the memory controller. The memory controller can be used to
  23. a. Isolate an application or a group of applications
  24. Memory-hungry applications can be isolated and limited to a smaller
  25. amount of memory.
  26. b. Create a cgroup with a limited amount of memory; this can be used
  27. as a good alternative to booting with mem=XXXX.
  28. c. Virtualization solutions can control the amount of memory they want
  29. to assign to a virtual machine instance.
  30. d. A CD/DVD burner could control the amount of memory used by the
  31. rest of the system to ensure that burning does not fail due to lack
  32. of available memory.
  33. e. There are several other use cases; find one or use the controller just
  34. for fun (to learn and hack on the VM subsystem).
  35. Current Status: linux-2.6.34-mmotm(development version of 2010/April)
  36. Features:
  37. - accounting anonymous pages, file caches, swap caches usage and limiting them.
  38. - pages are linked to per-memcg LRU exclusively, and there is no global LRU.
  39. - optionally, memory+swap usage can be accounted and limited.
  40. - hierarchical accounting
  41. - soft limit
  42. - moving (recharging) account at moving a task is selectable.
  43. - usage threshold notifier
  44. - memory pressure notifier
  45. - oom-killer disable knob and oom-notifier
  46. - Root cgroup has no limit controls.
  47. Kernel memory support is a work in progress, and the current version provides
  48. basically functionality. (See :ref:`section 2.7
  49. <cgroup-v1-memory-kernel-extension>`)
  50. Brief summary of control files.
  51. ==================================== ==========================================
  52. tasks attach a task(thread) and show list of
  53. threads
  54. cgroup.procs show list of processes
  55. cgroup.event_control an interface for event_fd()
  56. This knob is not available on CONFIG_PREEMPT_RT systems.
  57. memory.usage_in_bytes show current usage for memory
  58. (See 5.5 for details)
  59. memory.memsw.usage_in_bytes show current usage for memory+Swap
  60. (See 5.5 for details)
  61. memory.limit_in_bytes set/show limit of memory usage
  62. memory.memsw.limit_in_bytes set/show limit of memory+Swap usage
  63. memory.failcnt show the number of memory usage hits limits
  64. memory.memsw.failcnt show the number of memory+Swap hits limits
  65. memory.max_usage_in_bytes show max memory usage recorded
  66. memory.memsw.max_usage_in_bytes show max memory+Swap usage recorded
  67. memory.soft_limit_in_bytes set/show soft limit of memory usage
  68. This knob is not available on CONFIG_PREEMPT_RT systems.
  69. This knob is deprecated and shouldn't be
  70. used.
  71. memory.stat show various statistics
  72. memory.use_hierarchy set/show hierarchical account enabled
  73. This knob is deprecated and shouldn't be
  74. used.
  75. memory.force_empty trigger forced page reclaim
  76. memory.pressure_level set memory pressure notifications
  77. This knob is deprecated and shouldn't be
  78. used.
  79. memory.swappiness set/show swappiness parameter of vmscan
  80. (See sysctl's vm.swappiness)
  81. memory.move_charge_at_immigrate set/show controls of moving charges
  82. This knob is deprecated and shouldn't be
  83. used.
  84. memory.oom_control set/show oom controls.
  85. This knob is deprecated and shouldn't be
  86. used.
  87. memory.numa_stat show the number of memory usage per numa
  88. node
  89. memory.kmem.limit_in_bytes Deprecated knob to set and read the kernel
  90. memory hard limit. Kernel hard limit is not
  91. supported since 5.16. Writing any value to
  92. do file will not have any effect same as if
  93. nokmem kernel parameter was specified.
  94. Kernel memory is still charged and reported
  95. by memory.kmem.usage_in_bytes.
  96. memory.kmem.usage_in_bytes show current kernel memory allocation
  97. memory.kmem.failcnt show the number of kernel memory usage
  98. hits limits
  99. memory.kmem.max_usage_in_bytes show max kernel memory usage recorded
  100. memory.kmem.tcp.limit_in_bytes set/show hard limit for tcp buf memory
  101. This knob is deprecated and shouldn't be
  102. used.
  103. memory.kmem.tcp.usage_in_bytes show current tcp buf memory allocation
  104. This knob is deprecated and shouldn't be
  105. used.
  106. memory.kmem.tcp.failcnt show the number of tcp buf memory usage
  107. hits limits
  108. This knob is deprecated and shouldn't be
  109. used.
  110. memory.kmem.tcp.max_usage_in_bytes show max tcp buf memory usage recorded
  111. This knob is deprecated and shouldn't be
  112. used.
  113. ==================================== ==========================================
  114. 1. History
  115. ==========
  116. The memory controller has a long history. A request for comments for the memory
  117. controller was posted by Balbir Singh [1]_. At the time the RFC was posted
  118. there were several implementations for memory control. The goal of the
  119. RFC was to build consensus and agreement for the minimal features required
  120. for memory control. The first RSS controller was posted by Balbir Singh [2]_
  121. in Feb 2007. Pavel Emelianov [3]_ [4]_ [5]_ has since posted three versions
  122. of the RSS controller. At OLS, at the resource management BoF, everyone
  123. suggested that we handle both page cache and RSS together. Another request was
  124. raised to allow user space handling of OOM. The current memory controller is
  125. at version 6; it combines both mapped (RSS) and unmapped Page
  126. Cache Control [11]_.
  127. 2. Memory Control
  128. =================
  129. Memory is a unique resource in the sense that it is present in a limited
  130. amount. If a task requires a lot of CPU processing, the task can spread
  131. its processing over a period of hours, days, months or years, but with
  132. memory, the same physical memory needs to be reused to accomplish the task.
  133. The memory controller implementation has been divided into phases. These
  134. are:
  135. 1. Memory controller
  136. 2. mlock(2) controller
  137. 3. Kernel user memory accounting and slab control
  138. 4. user mappings length controller
  139. The memory controller is the first controller developed.
  140. 2.1. Design
  141. -----------
  142. The core of the design is a counter called the page_counter. The
  143. page_counter tracks the current memory usage and limit of the group of
  144. processes associated with the controller. Each cgroup has a memory controller
  145. specific data structure (mem_cgroup) associated with it.
  146. 2.2. Accounting
  147. ---------------
  148. .. code-block::
  149. :caption: Figure 1: Hierarchy of Accounting
  150. +--------------------+
  151. | mem_cgroup |
  152. | (page_counter) |
  153. +--------------------+
  154. / ^ \
  155. / | \
  156. +---------------+ | +---------------+
  157. | mm_struct | |.... | mm_struct |
  158. | | | | |
  159. +---------------+ | +---------------+
  160. |
  161. + --------------+
  162. |
  163. +---------------+ +------+--------+
  164. | page +----------> page_cgroup|
  165. | | | |
  166. +---------------+ +---------------+
  167. Figure 1 shows the important aspects of the controller
  168. 1. Accounting happens per cgroup
  169. 2. Each mm_struct knows about which cgroup it belongs to
  170. 3. Each page has a pointer to the page_cgroup, which in turn knows the
  171. cgroup it belongs to
  172. The accounting is done as follows: mem_cgroup_charge_common() is invoked to
  173. set up the necessary data structures and check if the cgroup that is being
  174. charged is over its limit. If it is, then reclaim is invoked on the cgroup.
  175. More details can be found in the reclaim section of this document.
  176. If everything goes well, a page meta-data-structure called page_cgroup is
  177. updated. page_cgroup has its own LRU on cgroup.
  178. (*) page_cgroup structure is allocated at boot/memory-hotplug time.
  179. 2.2.1 Accounting details
  180. ------------------------
  181. All mapped anon pages (RSS) and cache pages (Page Cache) are accounted.
  182. Some pages which are never reclaimable and will not be on the LRU
  183. are not accounted. We just account pages under usual VM management.
  184. RSS pages are accounted at page_fault unless they've already been accounted
  185. for earlier. A file page will be accounted for as Page Cache when it's
  186. inserted into inode (xarray). While it's mapped into the page tables of
  187. processes, duplicate accounting is carefully avoided.
  188. An RSS page is unaccounted when it's fully unmapped. A PageCache page is
  189. unaccounted when it's removed from xarray. Even if RSS pages are fully
  190. unmapped (by kswapd), they may exist as SwapCache in the system until they
  191. are really freed. Such SwapCaches are also accounted.
  192. A swapped-in page is accounted after adding into swapcache.
  193. Note: The kernel does swapin-readahead and reads multiple swaps at once.
  194. Since page's memcg recorded into swap whatever memsw enabled, the page will
  195. be accounted after swapin.
  196. At page migration, accounting information is kept.
  197. Note: we just account pages-on-LRU because our purpose is to control amount
  198. of used pages; not-on-LRU pages tend to be out-of-control from VM view.
  199. 2.3 Shared Page Accounting
  200. --------------------------
  201. Shared pages are accounted on the basis of the first touch approach. The
  202. cgroup that first touches a page is accounted for the page. The principle
  203. behind this approach is that a cgroup that aggressively uses a shared
  204. page will eventually get charged for it (once it is uncharged from
  205. the cgroup that brought it in -- this will happen on memory pressure).
  206. But see :ref:`section 8.2 <cgroup-v1-memory-movable-charges>` when moving a
  207. task to another cgroup, its pages may be recharged to the new cgroup, if
  208. move_charge_at_immigrate has been chosen.
  209. 2.4 Swap Extension
  210. --------------------------------------
  211. Swap usage is always recorded for each of cgroup. Swap Extension allows you to
  212. read and limit it.
  213. When CONFIG_SWAP is enabled, following files are added.
  214. - memory.memsw.usage_in_bytes.
  215. - memory.memsw.limit_in_bytes.
  216. memsw means memory+swap. Usage of memory+swap is limited by
  217. memsw.limit_in_bytes.
  218. Example: Assume a system with 4G of swap. A task which allocates 6G of memory
  219. (by mistake) under 2G memory limitation will use all swap.
  220. In this case, setting memsw.limit_in_bytes=3G will prevent bad use of swap.
  221. By using the memsw limit, you can avoid system OOM which can be caused by swap
  222. shortage.
  223. 2.4.1 why 'memory+swap' rather than swap
  224. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  225. The global LRU(kswapd) can swap out arbitrary pages. Swap-out means
  226. to move account from memory to swap...there is no change in usage of
  227. memory+swap. In other words, when we want to limit the usage of swap without
  228. affecting global LRU, memory+swap limit is better than just limiting swap from
  229. an OS point of view.
  230. 2.4.2. What happens when a cgroup hits memory.memsw.limit_in_bytes
  231. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  232. When a cgroup hits memory.memsw.limit_in_bytes, it's useless to do swap-out
  233. in this cgroup. Then, swap-out will not be done by cgroup routine and file
  234. caches are dropped. But as mentioned above, global LRU can do swapout memory
  235. from it for sanity of the system's memory management state. You can't forbid
  236. it by cgroup.
  237. 2.5 Reclaim
  238. -----------
  239. Each cgroup maintains a per cgroup LRU which has the same structure as
  240. global VM. When a cgroup goes over its limit, we first try
  241. to reclaim memory from the cgroup so as to make space for the new
  242. pages that the cgroup has touched. If the reclaim is unsuccessful,
  243. an OOM routine is invoked to select and kill the bulkiest task in the
  244. cgroup. (See :ref:`10. OOM Control <cgroup-v1-memory-oom-control>` below.)
  245. The reclaim algorithm has not been modified for cgroups, except that
  246. pages that are selected for reclaiming come from the per-cgroup LRU
  247. list.
  248. .. note::
  249. Reclaim does not work for the root cgroup, since we cannot set any
  250. limits on the root cgroup.
  251. .. note::
  252. When panic_on_oom is set to "2", the whole system will panic.
  253. When oom event notifier is registered, event will be delivered.
  254. (See :ref:`oom_control <cgroup-v1-memory-oom-control>` section)
  255. 2.6 Locking
  256. -----------
  257. Lock order is as follows::
  258. folio_lock
  259. mm->page_table_lock or split pte_lock
  260. folio_memcg_lock (memcg->move_lock)
  261. mapping->i_pages lock
  262. lruvec->lru_lock.
  263. Per-node-per-memcgroup LRU (cgroup's private LRU) is guarded by
  264. lruvec->lru_lock; the folio LRU flag is cleared before
  265. isolating a page from its LRU under lruvec->lru_lock.
  266. .. _cgroup-v1-memory-kernel-extension:
  267. 2.7 Kernel Memory Extension
  268. -----------------------------------------------
  269. With the Kernel memory extension, the Memory Controller is able to limit
  270. the amount of kernel memory used by the system. Kernel memory is fundamentally
  271. different than user memory, since it can't be swapped out, which makes it
  272. possible to DoS the system by consuming too much of this precious resource.
  273. Kernel memory accounting is enabled for all memory cgroups by default. But
  274. it can be disabled system-wide by passing cgroup.memory=nokmem to the kernel
  275. at boot time. In this case, kernel memory will not be accounted at all.
  276. Kernel memory limits are not imposed for the root cgroup. Usage for the root
  277. cgroup may or may not be accounted. The memory used is accumulated into
  278. memory.kmem.usage_in_bytes, or in a separate counter when it makes sense.
  279. (currently only for tcp).
  280. The main "kmem" counter is fed into the main counter, so kmem charges will
  281. also be visible from the user counter.
  282. Currently no soft limit is implemented for kernel memory. It is future work
  283. to trigger slab reclaim when those limits are reached.
  284. 2.7.1 Current Kernel Memory resources accounted
  285. -----------------------------------------------
  286. stack pages:
  287. every process consumes some stack pages. By accounting into
  288. kernel memory, we prevent new processes from being created when the kernel
  289. memory usage is too high.
  290. slab pages:
  291. pages allocated by the SLAB or SLUB allocator are tracked. A copy
  292. of each kmem_cache is created every time the cache is touched by the first time
  293. from inside the memcg. The creation is done lazily, so some objects can still be
  294. skipped while the cache is being created. All objects in a slab page should
  295. belong to the same memcg. This only fails to hold when a task is migrated to a
  296. different memcg during the page allocation by the cache.
  297. sockets memory pressure:
  298. some sockets protocols have memory pressure
  299. thresholds. The Memory Controller allows them to be controlled individually
  300. per cgroup, instead of globally.
  301. tcp memory pressure:
  302. sockets memory pressure for the tcp protocol.
  303. 2.7.2 Common use cases
  304. ----------------------
  305. Because the "kmem" counter is fed to the main user counter, kernel memory can
  306. never be limited completely independently of user memory. Say "U" is the user
  307. limit, and "K" the kernel limit. There are three possible ways limits can be
  308. set:
  309. U != 0, K = unlimited:
  310. This is the standard memcg limitation mechanism already present before kmem
  311. accounting. Kernel memory is completely ignored.
  312. U != 0, K < U:
  313. Kernel memory is a subset of the user memory. This setup is useful in
  314. deployments where the total amount of memory per-cgroup is overcommitted.
  315. Overcommitting kernel memory limits is definitely not recommended, since the
  316. box can still run out of non-reclaimable memory.
  317. In this case, the admin could set up K so that the sum of all groups is
  318. never greater than the total memory, and freely set U at the cost of his
  319. QoS.
  320. .. warning::
  321. In the current implementation, memory reclaim will NOT be triggered for
  322. a cgroup when it hits K while staying below U, which makes this setup
  323. impractical.
  324. U != 0, K >= U:
  325. Since kmem charges will also be fed to the user counter and reclaim will be
  326. triggered for the cgroup for both kinds of memory. This setup gives the
  327. admin a unified view of memory, and it is also useful for people who just
  328. want to track kernel memory usage.
  329. 3. User Interface
  330. =================
  331. To use the user interface:
  332. 1. Enable CONFIG_CGROUPS and CONFIG_MEMCG options
  333. 2. Prepare the cgroups (see :ref:`Why are cgroups needed?
  334. <cgroups-why-needed>` for the background information)::
  335. # mount -t tmpfs none /sys/fs/cgroup
  336. # mkdir /sys/fs/cgroup/memory
  337. # mount -t cgroup none /sys/fs/cgroup/memory -o memory
  338. 3. Make the new group and move bash into it::
  339. # mkdir /sys/fs/cgroup/memory/0
  340. # echo $$ > /sys/fs/cgroup/memory/0/tasks
  341. 4. Since now we're in the 0 cgroup, we can alter the memory limit::
  342. # echo 4M > /sys/fs/cgroup/memory/0/memory.limit_in_bytes
  343. The limit can now be queried::
  344. # cat /sys/fs/cgroup/memory/0/memory.limit_in_bytes
  345. 4194304
  346. .. note::
  347. We can use a suffix (k, K, m, M, g or G) to indicate values in kilo,
  348. mega or gigabytes. (Here, Kilo, Mega, Giga are Kibibytes, Mebibytes,
  349. Gibibytes.)
  350. .. note::
  351. We can write "-1" to reset the ``*.limit_in_bytes(unlimited)``.
  352. .. note::
  353. We cannot set limits on the root cgroup any more.
  354. We can check the usage::
  355. # cat /sys/fs/cgroup/memory/0/memory.usage_in_bytes
  356. 1216512
  357. A successful write to this file does not guarantee a successful setting of
  358. this limit to the value written into the file. This can be due to a
  359. number of factors, such as rounding up to page boundaries or the total
  360. availability of memory on the system. The user is required to re-read
  361. this file after a write to guarantee the value committed by the kernel::
  362. # echo 1 > memory.limit_in_bytes
  363. # cat memory.limit_in_bytes
  364. 4096
  365. The memory.failcnt field gives the number of times that the cgroup limit was
  366. exceeded.
  367. The memory.stat file gives accounting information. Now, the number of
  368. caches, RSS and Active pages/Inactive pages are shown.
  369. 4. Testing
  370. ==========
  371. For testing features and implementation, see memcg_test.txt.
  372. Performance test is also important. To see pure memory controller's overhead,
  373. testing on tmpfs will give you good numbers of small overheads.
  374. Example: do kernel make on tmpfs.
  375. Page-fault scalability is also important. At measuring parallel
  376. page fault test, multi-process test may be better than multi-thread
  377. test because it has noise of shared objects/status.
  378. But the above two are testing extreme situations.
  379. Trying usual test under memory controller is always helpful.
  380. .. _cgroup-v1-memory-test-troubleshoot:
  381. 4.1 Troubleshooting
  382. -------------------
  383. Sometimes a user might find that the application under a cgroup is
  384. terminated by the OOM killer. There are several causes for this:
  385. 1. The cgroup limit is too low (just too low to do anything useful)
  386. 2. The user is using anonymous memory and swap is turned off or too low
  387. A sync followed by echo 1 > /proc/sys/vm/drop_caches will help get rid of
  388. some of the pages cached in the cgroup (page cache pages).
  389. To know what happens, disabling OOM_Kill as per :ref:`"10. OOM Control"
  390. <cgroup-v1-memory-oom-control>` (below) and seeing what happens will be
  391. helpful.
  392. .. _cgroup-v1-memory-test-task-migration:
  393. 4.2 Task migration
  394. ------------------
  395. When a task migrates from one cgroup to another, its charge is not
  396. carried forward by default. The pages allocated from the original cgroup still
  397. remain charged to it, the charge is dropped when the page is freed or
  398. reclaimed.
  399. You can move charges of a task along with task migration.
  400. See :ref:`8. "Move charges at task migration" <cgroup-v1-memory-move-charges>`
  401. 4.3 Removing a cgroup
  402. ---------------------
  403. A cgroup can be removed by rmdir, but as discussed in :ref:`sections 4.1
  404. <cgroup-v1-memory-test-troubleshoot>` and :ref:`4.2
  405. <cgroup-v1-memory-test-task-migration>`, a cgroup might have some charge
  406. associated with it, even though all tasks have migrated away from it. (because
  407. we charge against pages, not against tasks.)
  408. We move the stats to parent, and no change on the charge except uncharging
  409. from the child.
  410. Charges recorded in swap information is not updated at removal of cgroup.
  411. Recorded information is discarded and a cgroup which uses swap (swapcache)
  412. will be charged as a new owner of it.
  413. 5. Misc. interfaces
  414. ===================
  415. 5.1 force_empty
  416. ---------------
  417. memory.force_empty interface is provided to make cgroup's memory usage empty.
  418. When writing anything to this::
  419. # echo 0 > memory.force_empty
  420. the cgroup will be reclaimed and as many pages reclaimed as possible.
  421. The typical use case for this interface is before calling rmdir().
  422. Though rmdir() offlines memcg, but the memcg may still stay there due to
  423. charged file caches. Some out-of-use page caches may keep charged until
  424. memory pressure happens. If you want to avoid that, force_empty will be useful.
  425. 5.2 stat file
  426. -------------
  427. memory.stat file includes following statistics:
  428. * per-memory cgroup local status
  429. =============== ===============================================================
  430. cache # of bytes of page cache memory.
  431. rss # of bytes of anonymous and swap cache memory (includes
  432. transparent hugepages).
  433. rss_huge # of bytes of anonymous transparent hugepages.
  434. mapped_file # of bytes of mapped file (includes tmpfs/shmem)
  435. pgpgin # of charging events to the memory cgroup. The charging
  436. event happens each time a page is accounted as either mapped
  437. anon page(RSS) or cache page(Page Cache) to the cgroup.
  438. pgpgout # of uncharging events to the memory cgroup. The uncharging
  439. event happens each time a page is unaccounted from the
  440. cgroup.
  441. swap # of bytes of swap usage
  442. swapcached # of bytes of swap cached in memory
  443. dirty # of bytes that are waiting to get written back to the disk.
  444. writeback # of bytes of file/anon cache that are queued for syncing to
  445. disk.
  446. inactive_anon # of bytes of anonymous and swap cache memory on inactive
  447. LRU list.
  448. active_anon # of bytes of anonymous and swap cache memory on active
  449. LRU list.
  450. inactive_file # of bytes of file-backed memory and MADV_FREE anonymous
  451. memory (LazyFree pages) on inactive LRU list.
  452. active_file # of bytes of file-backed memory on active LRU list.
  453. unevictable # of bytes of memory that cannot be reclaimed (mlocked etc).
  454. =============== ===============================================================
  455. * status considering hierarchy (see memory.use_hierarchy settings):
  456. ========================= ===================================================
  457. hierarchical_memory_limit # of bytes of memory limit with regard to
  458. hierarchy
  459. under which the memory cgroup is
  460. hierarchical_memsw_limit # of bytes of memory+swap limit with regard to
  461. hierarchy under which memory cgroup is.
  462. total_<counter> # hierarchical version of <counter>, which in
  463. addition to the cgroup's own value includes the
  464. sum of all hierarchical children's values of
  465. <counter>, i.e. total_cache
  466. ========================= ===================================================
  467. * additional vm parameters (depends on CONFIG_DEBUG_VM):
  468. ========================= ========================================
  469. recent_rotated_anon VM internal parameter. (see mm/vmscan.c)
  470. recent_rotated_file VM internal parameter. (see mm/vmscan.c)
  471. recent_scanned_anon VM internal parameter. (see mm/vmscan.c)
  472. recent_scanned_file VM internal parameter. (see mm/vmscan.c)
  473. ========================= ========================================
  474. .. hint::
  475. recent_rotated means recent frequency of LRU rotation.
  476. recent_scanned means recent # of scans to LRU.
  477. showing for better debug please see the code for meanings.
  478. .. note::
  479. Only anonymous and swap cache memory is listed as part of 'rss' stat.
  480. This should not be confused with the true 'resident set size' or the
  481. amount of physical memory used by the cgroup.
  482. 'rss + mapped_file" will give you resident set size of cgroup.
  483. (Note: file and shmem may be shared among other cgroups. In that case,
  484. mapped_file is accounted only when the memory cgroup is owner of page
  485. cache.)
  486. 5.3 swappiness
  487. --------------
  488. Overrides /proc/sys/vm/swappiness for the particular group. The tunable
  489. in the root cgroup corresponds to the global swappiness setting.
  490. Please note that unlike during the global reclaim, limit reclaim
  491. enforces that 0 swappiness really prevents from any swapping even if
  492. there is a swap storage available. This might lead to memcg OOM killer
  493. if there are no file pages to reclaim.
  494. 5.4 failcnt
  495. -----------
  496. A memory cgroup provides memory.failcnt and memory.memsw.failcnt files.
  497. This failcnt(== failure count) shows the number of times that a usage counter
  498. hit its limit. When a memory cgroup hits a limit, failcnt increases and
  499. memory under it will be reclaimed.
  500. You can reset failcnt by writing 0 to failcnt file::
  501. # echo 0 > .../memory.failcnt
  502. 5.5 usage_in_bytes
  503. ------------------
  504. For efficiency, as other kernel components, memory cgroup uses some optimization
  505. to avoid unnecessary cacheline false sharing. usage_in_bytes is affected by the
  506. method and doesn't show 'exact' value of memory (and swap) usage, it's a fuzz
  507. value for efficient access. (Of course, when necessary, it's synchronized.)
  508. If you want to know more exact memory usage, you should use RSS+CACHE(+SWAP)
  509. value in memory.stat(see 5.2).
  510. 5.6 numa_stat
  511. -------------
  512. This is similar to numa_maps but operates on a per-memcg basis. This is
  513. useful for providing visibility into the numa locality information within
  514. an memcg since the pages are allowed to be allocated from any physical
  515. node. One of the use cases is evaluating application performance by
  516. combining this information with the application's CPU allocation.
  517. Each memcg's numa_stat file includes "total", "file", "anon" and "unevictable"
  518. per-node page counts including "hierarchical_<counter>" which sums up all
  519. hierarchical children's values in addition to the memcg's own value.
  520. The output format of memory.numa_stat is::
  521. total=<total pages> N0=<node 0 pages> N1=<node 1 pages> ...
  522. file=<total file pages> N0=<node 0 pages> N1=<node 1 pages> ...
  523. anon=<total anon pages> N0=<node 0 pages> N1=<node 1 pages> ...
  524. unevictable=<total anon pages> N0=<node 0 pages> N1=<node 1 pages> ...
  525. hierarchical_<counter>=<counter pages> N0=<node 0 pages> N1=<node 1 pages> ...
  526. The "total" count is sum of file + anon + unevictable.
  527. 6. Hierarchy support
  528. ====================
  529. The memory controller supports a deep hierarchy and hierarchical accounting.
  530. The hierarchy is created by creating the appropriate cgroups in the
  531. cgroup filesystem. Consider for example, the following cgroup filesystem
  532. hierarchy::
  533. root
  534. / | \
  535. / | \
  536. a b c
  537. | \
  538. | \
  539. d e
  540. In the diagram above, with hierarchical accounting enabled, all memory
  541. usage of e, is accounted to its ancestors up until the root (i.e, c and root).
  542. If one of the ancestors goes over its limit, the reclaim algorithm reclaims
  543. from the tasks in the ancestor and the children of the ancestor.
  544. 6.1 Hierarchical accounting and reclaim
  545. ---------------------------------------
  546. Hierarchical accounting is enabled by default. Disabling the hierarchical
  547. accounting is deprecated. An attempt to do it will result in a failure
  548. and a warning printed to dmesg.
  549. For compatibility reasons writing 1 to memory.use_hierarchy will always pass::
  550. # echo 1 > memory.use_hierarchy
  551. 7. Soft limits (DEPRECATED)
  552. ===========================
  553. THIS IS DEPRECATED!
  554. Soft limits allow for greater sharing of memory. The idea behind soft limits
  555. is to allow control groups to use as much of the memory as needed, provided
  556. a. There is no memory contention
  557. b. They do not exceed their hard limit
  558. When the system detects memory contention or low memory, control groups
  559. are pushed back to their soft limits. If the soft limit of each control
  560. group is very high, they are pushed back as much as possible to make
  561. sure that one control group does not starve the others of memory.
  562. Please note that soft limits is a best-effort feature; it comes with
  563. no guarantees, but it does its best to make sure that when memory is
  564. heavily contended for, memory is allocated based on the soft limit
  565. hints/setup. Currently soft limit based reclaim is set up such that
  566. it gets invoked from balance_pgdat (kswapd).
  567. 7.1 Interface
  568. -------------
  569. Soft limits can be setup by using the following commands (in this example we
  570. assume a soft limit of 256 MiB)::
  571. # echo 256M > memory.soft_limit_in_bytes
  572. If we want to change this to 1G, we can at any time use::
  573. # echo 1G > memory.soft_limit_in_bytes
  574. .. note::
  575. Soft limits take effect over a long period of time, since they involve
  576. reclaiming memory for balancing between memory cgroups
  577. .. note::
  578. It is recommended to set the soft limit always below the hard limit,
  579. otherwise the hard limit will take precedence.
  580. .. _cgroup-v1-memory-move-charges:
  581. 8. Move charges at task migration (DEPRECATED!)
  582. ===============================================
  583. THIS IS DEPRECATED!
  584. It's expensive and unreliable! It's better practice to launch workload
  585. tasks directly from inside their target cgroup. Use dedicated workload
  586. cgroups to allow fine-grained policy adjustments without having to
  587. move physical pages between control domains.
  588. Users can move charges associated with a task along with task migration, that
  589. is, uncharge task's pages from the old cgroup and charge them to the new cgroup.
  590. This feature is not supported in !CONFIG_MMU environments because of lack of
  591. page tables.
  592. 8.1 Interface
  593. -------------
  594. This feature is disabled by default. It can be enabled (and disabled again) by
  595. writing to memory.move_charge_at_immigrate of the destination cgroup.
  596. If you want to enable it::
  597. # echo (some positive value) > memory.move_charge_at_immigrate
  598. .. note::
  599. Each bits of move_charge_at_immigrate has its own meaning about what type
  600. of charges should be moved. See :ref:`section 8.2
  601. <cgroup-v1-memory-movable-charges>` for details.
  602. .. note::
  603. Charges are moved only when you move mm->owner, in other words,
  604. a leader of a thread group.
  605. .. note::
  606. If we cannot find enough space for the task in the destination cgroup, we
  607. try to make space by reclaiming memory. Task migration may fail if we
  608. cannot make enough space.
  609. .. note::
  610. It can take several seconds if you move charges much.
  611. And if you want disable it again::
  612. # echo 0 > memory.move_charge_at_immigrate
  613. .. _cgroup-v1-memory-movable-charges:
  614. 8.2 Type of charges which can be moved
  615. --------------------------------------
  616. Each bit in move_charge_at_immigrate has its own meaning about what type of
  617. charges should be moved. But in any case, it must be noted that an account of
  618. a page or a swap can be moved only when it is charged to the task's current
  619. (old) memory cgroup.
  620. +---+--------------------------------------------------------------------------+
  621. |bit| what type of charges would be moved ? |
  622. +===+==========================================================================+
  623. | 0 | A charge of an anonymous page (or swap of it) used by the target task. |
  624. | | You must enable Swap Extension (see 2.4) to enable move of swap charges. |
  625. +---+--------------------------------------------------------------------------+
  626. | 1 | A charge of file pages (normal file, tmpfs file (e.g. ipc shared memory) |
  627. | | and swaps of tmpfs file) mmapped by the target task. Unlike the case of |
  628. | | anonymous pages, file pages (and swaps) in the range mmapped by the task |
  629. | | will be moved even if the task hasn't done page fault, i.e. they might |
  630. | | not be the task's "RSS", but other task's "RSS" that maps the same file. |
  631. | | The mapcount of the page is ignored (the page can be moved independent |
  632. | | of the mapcount). You must enable Swap Extension (see 2.4) to |
  633. | | enable move of swap charges. |
  634. +---+--------------------------------------------------------------------------+
  635. 8.3 TODO
  636. --------
  637. - All of moving charge operations are done under cgroup_mutex. It's not good
  638. behavior to hold the mutex too long, so we may need some trick.
  639. 9. Memory thresholds
  640. ====================
  641. Memory cgroup implements memory thresholds using the cgroups notification
  642. API (see cgroups.txt). It allows to register multiple memory and memsw
  643. thresholds and gets notifications when it crosses.
  644. To register a threshold, an application must:
  645. - create an eventfd using eventfd(2);
  646. - open memory.usage_in_bytes or memory.memsw.usage_in_bytes;
  647. - write string like "<event_fd> <fd of memory.usage_in_bytes> <threshold>" to
  648. cgroup.event_control.
  649. Application will be notified through eventfd when memory usage crosses
  650. threshold in any direction.
  651. It's applicable for root and non-root cgroup.
  652. .. _cgroup-v1-memory-oom-control:
  653. 10. OOM Control (DEPRECATED)
  654. ============================
  655. THIS IS DEPRECATED!
  656. memory.oom_control file is for OOM notification and other controls.
  657. Memory cgroup implements OOM notifier using the cgroup notification
  658. API (See cgroups.txt). It allows to register multiple OOM notification
  659. delivery and gets notification when OOM happens.
  660. To register a notifier, an application must:
  661. - create an eventfd using eventfd(2)
  662. - open memory.oom_control file
  663. - write string like "<event_fd> <fd of memory.oom_control>" to
  664. cgroup.event_control
  665. The application will be notified through eventfd when OOM happens.
  666. OOM notification doesn't work for the root cgroup.
  667. You can disable the OOM-killer by writing "1" to memory.oom_control file, as:
  668. #echo 1 > memory.oom_control
  669. If OOM-killer is disabled, tasks under cgroup will hang/sleep
  670. in memory cgroup's OOM-waitqueue when they request accountable memory.
  671. For running them, you have to relax the memory cgroup's OOM status by
  672. * enlarge limit or reduce usage.
  673. To reduce usage,
  674. * kill some tasks.
  675. * move some tasks to other group with account migration.
  676. * remove some files (on tmpfs?)
  677. Then, stopped tasks will work again.
  678. At reading, current status of OOM is shown.
  679. - oom_kill_disable 0 or 1
  680. (if 1, oom-killer is disabled)
  681. - under_oom 0 or 1
  682. (if 1, the memory cgroup is under OOM, tasks may be stopped.)
  683. - oom_kill integer counter
  684. The number of processes belonging to this cgroup killed by any
  685. kind of OOM killer.
  686. 11. Memory Pressure (DEPRECATED)
  687. ================================
  688. THIS IS DEPRECATED!
  689. The pressure level notifications can be used to monitor the memory
  690. allocation cost; based on the pressure, applications can implement
  691. different strategies of managing their memory resources. The pressure
  692. levels are defined as following:
  693. The "low" level means that the system is reclaiming memory for new
  694. allocations. Monitoring this reclaiming activity might be useful for
  695. maintaining cache level. Upon notification, the program (typically
  696. "Activity Manager") might analyze vmstat and act in advance (i.e.
  697. prematurely shutdown unimportant services).
  698. The "medium" level means that the system is experiencing medium memory
  699. pressure, the system might be making swap, paging out active file caches,
  700. etc. Upon this event applications may decide to further analyze
  701. vmstat/zoneinfo/memcg or internal memory usage statistics and free any
  702. resources that can be easily reconstructed or re-read from a disk.
  703. The "critical" level means that the system is actively thrashing, it is
  704. about to out of memory (OOM) or even the in-kernel OOM killer is on its
  705. way to trigger. Applications should do whatever they can to help the
  706. system. It might be too late to consult with vmstat or any other
  707. statistics, so it's advisable to take an immediate action.
  708. By default, events are propagated upward until the event is handled, i.e. the
  709. events are not pass-through. For example, you have three cgroups: A->B->C. Now
  710. you set up an event listener on cgroups A, B and C, and suppose group C
  711. experiences some pressure. In this situation, only group C will receive the
  712. notification, i.e. groups A and B will not receive it. This is done to avoid
  713. excessive "broadcasting" of messages, which disturbs the system and which is
  714. especially bad if we are low on memory or thrashing. Group B, will receive
  715. notification only if there are no event listeners for group C.
  716. There are three optional modes that specify different propagation behavior:
  717. - "default": this is the default behavior specified above. This mode is the
  718. same as omitting the optional mode parameter, preserved by backwards
  719. compatibility.
  720. - "hierarchy": events always propagate up to the root, similar to the default
  721. behavior, except that propagation continues regardless of whether there are
  722. event listeners at each level, with the "hierarchy" mode. In the above
  723. example, groups A, B, and C will receive notification of memory pressure.
  724. - "local": events are pass-through, i.e. they only receive notifications when
  725. memory pressure is experienced in the memcg for which the notification is
  726. registered. In the above example, group C will receive notification if
  727. registered for "local" notification and the group experiences memory
  728. pressure. However, group B will never receive notification, regardless if
  729. there is an event listener for group C or not, if group B is registered for
  730. local notification.
  731. The level and event notification mode ("hierarchy" or "local", if necessary) are
  732. specified by a comma-delimited string, i.e. "low,hierarchy" specifies
  733. hierarchical, pass-through, notification for all ancestor memcgs. Notification
  734. that is the default, non pass-through behavior, does not specify a mode.
  735. "medium,local" specifies pass-through notification for the medium level.
  736. The file memory.pressure_level is only used to setup an eventfd. To
  737. register a notification, an application must:
  738. - create an eventfd using eventfd(2);
  739. - open memory.pressure_level;
  740. - write string as "<event_fd> <fd of memory.pressure_level> <level[,mode]>"
  741. to cgroup.event_control.
  742. Application will be notified through eventfd when memory pressure is at
  743. the specific level (or higher). Read/write operations to
  744. memory.pressure_level are no implemented.
  745. Test:
  746. Here is a small script example that makes a new cgroup, sets up a
  747. memory limit, sets up a notification in the cgroup and then makes child
  748. cgroup experience a critical pressure::
  749. # cd /sys/fs/cgroup/memory/
  750. # mkdir foo
  751. # cd foo
  752. # cgroup_event_listener memory.pressure_level low,hierarchy &
  753. # echo 8000000 > memory.limit_in_bytes
  754. # echo 8000000 > memory.memsw.limit_in_bytes
  755. # echo $$ > tasks
  756. # dd if=/dev/zero | read x
  757. (Expect a bunch of notifications, and eventually, the oom-killer will
  758. trigger.)
  759. 12. TODO
  760. ========
  761. 1. Make per-cgroup scanner reclaim not-shared pages first
  762. 2. Teach controller to account for shared-pages
  763. 3. Start reclamation in the background when the limit is
  764. not yet hit but the usage is getting closer
  765. Summary
  766. =======
  767. Overall, the memory controller has been a stable controller and has been
  768. commented and discussed quite extensively in the community.
  769. References
  770. ==========
  771. .. [1] Singh, Balbir. RFC: Memory Controller, http://lwn.net/Articles/206697/
  772. .. [2] Singh, Balbir. Memory Controller (RSS Control),
  773. http://lwn.net/Articles/222762/
  774. .. [3] Emelianov, Pavel. Resource controllers based on process cgroups
  775. https://lore.kernel.org/r/45ED7DEC.7010403@sw.ru
  776. .. [4] Emelianov, Pavel. RSS controller based on process cgroups (v2)
  777. https://lore.kernel.org/r/461A3010.90403@sw.ru
  778. .. [5] Emelianov, Pavel. RSS controller based on process cgroups (v3)
  779. https://lore.kernel.org/r/465D9739.8070209@openvz.org
  780. 6. Menage, Paul. Control Groups v10, http://lwn.net/Articles/236032/
  781. 7. Vaidyanathan, Srinivasan, Control Groups: Pagecache accounting and control
  782. subsystem (v3), http://lwn.net/Articles/235534/
  783. 8. Singh, Balbir. RSS controller v2 test results (lmbench),
  784. https://lore.kernel.org/r/464C95D4.7070806@linux.vnet.ibm.com
  785. 9. Singh, Balbir. RSS controller v2 AIM9 results
  786. https://lore.kernel.org/r/464D267A.50107@linux.vnet.ibm.com
  787. 10. Singh, Balbir. Memory controller v6 test results,
  788. https://lore.kernel.org/r/20070819094658.654.84837.sendpatchset@balbir-laptop
  789. .. [11] Singh, Balbir. Memory controller introduction (v6),
  790. https://lore.kernel.org/r/20070817084228.26003.12568.sendpatchset@balbir-laptop
  791. .. [12] Corbet, Jonathan, Controlling memory use in cgroups,
  792. http://lwn.net/Articles/243795/