memory.txt 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. Memory Resource Controller
  2. NOTE: The Memory Resource Controller has been generically been referred
  3. to as the memory controller in this document. Do not confuse memory controller
  4. used here with the memory controller that is used in hardware.
  5. Salient features
  6. a. Enable control of Anonymous, Page Cache (mapped and unmapped) and
  7. Swap Cache memory pages.
  8. b. The infrastructure allows easy addition of other types of memory to control
  9. c. Provides *zero overhead* for non memory controller users
  10. d. Provides a double LRU: global memory pressure causes reclaim from the
  11. global LRU; a cgroup on hitting a limit, reclaims from the per
  12. cgroup LRU
  13. Benefits and Purpose of the memory controller
  14. The memory controller isolates the memory behaviour of a group of tasks
  15. from the rest of the system. The article on LWN [12] mentions some probable
  16. uses of the memory controller. The memory controller can be used to
  17. a. Isolate an application or a group of applications
  18. Memory hungry applications can be isolated and limited to a smaller
  19. amount of memory.
  20. b. Create a cgroup with limited amount of memory, this can be used
  21. as a good alternative to booting with mem=XXXX.
  22. c. Virtualization solutions can control the amount of memory they want
  23. to assign to a virtual machine instance.
  24. d. A CD/DVD burner could control the amount of memory used by the
  25. rest of the system to ensure that burning does not fail due to lack
  26. of available memory.
  27. e. There are several other use cases, find one or use the controller just
  28. for fun (to learn and hack on the VM subsystem).
  29. 1. History
  30. The memory controller has a long history. A request for comments for the memory
  31. controller was posted by Balbir Singh [1]. At the time the RFC was posted
  32. there were several implementations for memory control. The goal of the
  33. RFC was to build consensus and agreement for the minimal features required
  34. for memory control. The first RSS controller was posted by Balbir Singh[2]
  35. in Feb 2007. Pavel Emelianov [3][4][5] has since posted three versions of the
  36. RSS controller. At OLS, at the resource management BoF, everyone suggested
  37. that we handle both page cache and RSS together. Another request was raised
  38. to allow user space handling of OOM. The current memory controller is
  39. at version 6; it combines both mapped (RSS) and unmapped Page
  40. Cache Control [11].
  41. 2. Memory Control
  42. Memory is a unique resource in the sense that it is present in a limited
  43. amount. If a task requires a lot of CPU processing, the task can spread
  44. its processing over a period of hours, days, months or years, but with
  45. memory, the same physical memory needs to be reused to accomplish the task.
  46. The memory controller implementation has been divided into phases. These
  47. are:
  48. 1. Memory controller
  49. 2. mlock(2) controller
  50. 3. Kernel user memory accounting and slab control
  51. 4. user mappings length controller
  52. The memory controller is the first controller developed.
  53. 2.1. Design
  54. The core of the design is a counter called the res_counter. The res_counter
  55. tracks the current memory usage and limit of the group of processes associated
  56. with the controller. Each cgroup has a memory controller specific data
  57. structure (mem_cgroup) associated with it.
  58. 2.2. Accounting
  59. +--------------------+
  60. | mem_cgroup |
  61. | (res_counter) |
  62. +--------------------+
  63. / ^ \
  64. / | \
  65. +---------------+ | +---------------+
  66. | mm_struct | |.... | mm_struct |
  67. | | | | |
  68. +---------------+ | +---------------+
  69. |
  70. + --------------+
  71. |
  72. +---------------+ +------+--------+
  73. | page +----------> page_cgroup|
  74. | | | |
  75. +---------------+ +---------------+
  76. (Figure 1: Hierarchy of Accounting)
  77. Figure 1 shows the important aspects of the controller
  78. 1. Accounting happens per cgroup
  79. 2. Each mm_struct knows about which cgroup it belongs to
  80. 3. Each page has a pointer to the page_cgroup, which in turn knows the
  81. cgroup it belongs to
  82. The accounting is done as follows: mem_cgroup_charge() is invoked to setup
  83. the necessary data structures and check if the cgroup that is being charged
  84. is over its limit. If it is then reclaim is invoked on the cgroup.
  85. More details can be found in the reclaim section of this document.
  86. If everything goes well, a page meta-data-structure called page_cgroup is
  87. allocated and associated with the page. This routine also adds the page to
  88. the per cgroup LRU.
  89. 2.2.1 Accounting details
  90. All mapped anon pages (RSS) and cache pages (Page Cache) are accounted.
  91. (some pages which never be reclaimable and will not be on global LRU
  92. are not accounted. we just accounts pages under usual vm management.)
  93. RSS pages are accounted at page_fault unless they've already been accounted
  94. for earlier. A file page will be accounted for as Page Cache when it's
  95. inserted into inode (radix-tree). While it's mapped into the page tables of
  96. processes, duplicate accounting is carefully avoided.
  97. A RSS page is unaccounted when it's fully unmapped. A PageCache page is
  98. unaccounted when it's removed from radix-tree.
  99. At page migration, accounting information is kept.
  100. Note: we just account pages-on-lru because our purpose is to control amount
  101. of used pages. not-on-lru pages are tend to be out-of-control from vm view.
  102. 2.3 Shared Page Accounting
  103. Shared pages are accounted on the basis of the first touch approach. The
  104. cgroup that first touches a page is accounted for the page. The principle
  105. behind this approach is that a cgroup that aggressively uses a shared
  106. page will eventually get charged for it (once it is uncharged from
  107. the cgroup that brought it in -- this will happen on memory pressure).
  108. Exception: If CONFIG_CGROUP_CGROUP_MEM_RES_CTLR_SWAP is not used..
  109. When you do swapoff and make swapped-out pages of shmem(tmpfs) to
  110. be backed into memory in force, charges for pages are accounted against the
  111. caller of swapoff rather than the users of shmem.
  112. 2.4 Swap Extension (CONFIG_CGROUP_MEM_RES_CTLR_SWAP)
  113. Swap Extension allows you to record charge for swap. A swapped-in page is
  114. charged back to original page allocator if possible.
  115. When swap is accounted, following files are added.
  116. - memory.memsw.usage_in_bytes.
  117. - memory.memsw.limit_in_bytes.
  118. usage of mem+swap is limited by memsw.limit_in_bytes.
  119. * why 'mem+swap' rather than swap.
  120. The global LRU(kswapd) can swap out arbitrary pages. Swap-out means
  121. to move account from memory to swap...there is no change in usage of
  122. mem+swap. In other words, when we want to limit the usage of swap without
  123. affecting global LRU, mem+swap limit is better than just limiting swap from
  124. OS point of view.
  125. * What happens when a cgroup hits memory.memsw.limit_in_bytes
  126. When a cgroup his memory.memsw.limit_in_bytes, it's useless to do swap-out
  127. in this cgroup. Then, swap-out will not be done by cgroup routine and file
  128. caches are dropped. But as mentioned above, global LRU can do swapout memory
  129. from it for sanity of the system's memory management state. You can't forbid
  130. it by cgroup.
  131. 2.5 Reclaim
  132. Each cgroup maintains a per cgroup LRU that consists of an active
  133. and inactive list. When a cgroup goes over its limit, we first try
  134. to reclaim memory from the cgroup so as to make space for the new
  135. pages that the cgroup has touched. If the reclaim is unsuccessful,
  136. an OOM routine is invoked to select and kill the bulkiest task in the
  137. cgroup.
  138. The reclaim algorithm has not been modified for cgroups, except that
  139. pages that are selected for reclaiming come from the per cgroup LRU
  140. list.
  141. NOTE: Reclaim does not work for the root cgroup, since we cannot set any
  142. limits on the root cgroup.
  143. Note2: When panic_on_oom is set to "2", the whole system will panic.
  144. When oom event notifier is registered, event will be delivered.
  145. (See oom_control section)
  146. 2. Locking
  147. The memory controller uses the following hierarchy
  148. 1. zone->lru_lock is used for selecting pages to be isolated
  149. 2. mem->per_zone->lru_lock protects the per cgroup LRU (per zone)
  150. 3. lock_page_cgroup() is used to protect page->page_cgroup
  151. 3. User Interface
  152. 0. Configuration
  153. a. Enable CONFIG_CGROUPS
  154. b. Enable CONFIG_RESOURCE_COUNTERS
  155. c. Enable CONFIG_CGROUP_MEM_RES_CTLR
  156. 1. Prepare the cgroups
  157. # mkdir -p /cgroups
  158. # mount -t cgroup none /cgroups -o memory
  159. 2. Make the new group and move bash into it
  160. # mkdir /cgroups/0
  161. # echo $$ > /cgroups/0/tasks
  162. Since now we're in the 0 cgroup,
  163. We can alter the memory limit:
  164. # echo 4M > /cgroups/0/memory.limit_in_bytes
  165. NOTE: We can use a suffix (k, K, m, M, g or G) to indicate values in kilo,
  166. mega or gigabytes.
  167. NOTE: We can write "-1" to reset the *.limit_in_bytes(unlimited).
  168. NOTE: We cannot set limits on the root cgroup any more.
  169. # cat /cgroups/0/memory.limit_in_bytes
  170. 4194304
  171. NOTE: The interface has now changed to display the usage in bytes
  172. instead of pages
  173. We can check the usage:
  174. # cat /cgroups/0/memory.usage_in_bytes
  175. 1216512
  176. A successful write to this file does not guarantee a successful set of
  177. this limit to the value written into the file. This can be due to a
  178. number of factors, such as rounding up to page boundaries or the total
  179. availability of memory on the system. The user is required to re-read
  180. this file after a write to guarantee the value committed by the kernel.
  181. # echo 1 > memory.limit_in_bytes
  182. # cat memory.limit_in_bytes
  183. 4096
  184. The memory.failcnt field gives the number of times that the cgroup limit was
  185. exceeded.
  186. The memory.stat file gives accounting information. Now, the number of
  187. caches, RSS and Active pages/Inactive pages are shown.
  188. 4. Testing
  189. Balbir posted lmbench, AIM9, LTP and vmmstress results [10] and [11].
  190. Apart from that v6 has been tested with several applications and regular
  191. daily use. The controller has also been tested on the PPC64, x86_64 and
  192. UML platforms.
  193. 4.1 Troubleshooting
  194. Sometimes a user might find that the application under a cgroup is
  195. terminated. There are several causes for this:
  196. 1. The cgroup limit is too low (just too low to do anything useful)
  197. 2. The user is using anonymous memory and swap is turned off or too low
  198. A sync followed by echo 1 > /proc/sys/vm/drop_caches will help get rid of
  199. some of the pages cached in the cgroup (page cache pages).
  200. 4.2 Task migration
  201. When a task migrates from one cgroup to another, its charge is not
  202. carried forward by default. The pages allocated from the original cgroup still
  203. remain charged to it, the charge is dropped when the page is freed or
  204. reclaimed.
  205. Note: You can move charges of a task along with task migration. See 8.
  206. 4.3 Removing a cgroup
  207. A cgroup can be removed by rmdir, but as discussed in sections 4.1 and 4.2, a
  208. cgroup might have some charge associated with it, even though all
  209. tasks have migrated away from it.
  210. Such charges are freed(at default) or moved to its parent. When moved,
  211. both of RSS and CACHES are moved to parent.
  212. If both of them are busy, rmdir() returns -EBUSY. See 5.1 Also.
  213. Charges recorded in swap information is not updated at removal of cgroup.
  214. Recorded information is discarded and a cgroup which uses swap (swapcache)
  215. will be charged as a new owner of it.
  216. 5. Misc. interfaces.
  217. 5.1 force_empty
  218. memory.force_empty interface is provided to make cgroup's memory usage empty.
  219. You can use this interface only when the cgroup has no tasks.
  220. When writing anything to this
  221. # echo 0 > memory.force_empty
  222. Almost all pages tracked by this memcg will be unmapped and freed. Some of
  223. pages cannot be freed because it's locked or in-use. Such pages are moved
  224. to parent and this cgroup will be empty. But this may return -EBUSY in
  225. some too busy case.
  226. Typical use case of this interface is that calling this before rmdir().
  227. Because rmdir() moves all pages to parent, some out-of-use page caches can be
  228. moved to the parent. If you want to avoid that, force_empty will be useful.
  229. 5.2 stat file
  230. memory.stat file includes following statistics
  231. cache - # of bytes of page cache memory.
  232. rss - # of bytes of anonymous and swap cache memory.
  233. pgpgin - # of pages paged in (equivalent to # of charging events).
  234. pgpgout - # of pages paged out (equivalent to # of uncharging events).
  235. active_anon - # of bytes of anonymous and swap cache memory on active
  236. lru list.
  237. inactive_anon - # of bytes of anonymous memory and swap cache memory on
  238. inactive lru list.
  239. active_file - # of bytes of file-backed memory on active lru list.
  240. inactive_file - # of bytes of file-backed memory on inactive lru list.
  241. unevictable - # of bytes of memory that cannot be reclaimed (mlocked etc).
  242. The following additional stats are dependent on CONFIG_DEBUG_VM.
  243. inactive_ratio - VM internal parameter. (see mm/page_alloc.c)
  244. recent_rotated_anon - VM internal parameter. (see mm/vmscan.c)
  245. recent_rotated_file - VM internal parameter. (see mm/vmscan.c)
  246. recent_scanned_anon - VM internal parameter. (see mm/vmscan.c)
  247. recent_scanned_file - VM internal parameter. (see mm/vmscan.c)
  248. Memo:
  249. recent_rotated means recent frequency of lru rotation.
  250. recent_scanned means recent # of scans to lru.
  251. showing for better debug please see the code for meanings.
  252. Note:
  253. Only anonymous and swap cache memory is listed as part of 'rss' stat.
  254. This should not be confused with the true 'resident set size' or the
  255. amount of physical memory used by the cgroup. Per-cgroup rss
  256. accounting is not done yet.
  257. 5.3 swappiness
  258. Similar to /proc/sys/vm/swappiness, but affecting a hierarchy of groups only.
  259. Following cgroups' swappiness can't be changed.
  260. - root cgroup (uses /proc/sys/vm/swappiness).
  261. - a cgroup which uses hierarchy and it has child cgroup.
  262. - a cgroup which uses hierarchy and not the root of hierarchy.
  263. 6. Hierarchy support
  264. The memory controller supports a deep hierarchy and hierarchical accounting.
  265. The hierarchy is created by creating the appropriate cgroups in the
  266. cgroup filesystem. Consider for example, the following cgroup filesystem
  267. hierarchy
  268. root
  269. / | \
  270. / | \
  271. a b c
  272. | \
  273. | \
  274. d e
  275. In the diagram above, with hierarchical accounting enabled, all memory
  276. usage of e, is accounted to its ancestors up until the root (i.e, c and root),
  277. that has memory.use_hierarchy enabled. If one of the ancestors goes over its
  278. limit, the reclaim algorithm reclaims from the tasks in the ancestor and the
  279. children of the ancestor.
  280. 6.1 Enabling hierarchical accounting and reclaim
  281. The memory controller by default disables the hierarchy feature. Support
  282. can be enabled by writing 1 to memory.use_hierarchy file of the root cgroup
  283. # echo 1 > memory.use_hierarchy
  284. The feature can be disabled by
  285. # echo 0 > memory.use_hierarchy
  286. NOTE1: Enabling/disabling will fail if the cgroup already has other
  287. cgroups created below it.
  288. NOTE2: When panic_on_oom is set to "2", the whole system will panic in
  289. case of an oom event in any cgroup.
  290. 7. Soft limits
  291. Soft limits allow for greater sharing of memory. The idea behind soft limits
  292. is to allow control groups to use as much of the memory as needed, provided
  293. a. There is no memory contention
  294. b. They do not exceed their hard limit
  295. When the system detects memory contention or low memory control groups
  296. are pushed back to their soft limits. If the soft limit of each control
  297. group is very high, they are pushed back as much as possible to make
  298. sure that one control group does not starve the others of memory.
  299. Please note that soft limits is a best effort feature, it comes with
  300. no guarantees, but it does its best to make sure that when memory is
  301. heavily contended for, memory is allocated based on the soft limit
  302. hints/setup. Currently soft limit based reclaim is setup such that
  303. it gets invoked from balance_pgdat (kswapd).
  304. 7.1 Interface
  305. Soft limits can be setup by using the following commands (in this example we
  306. assume a soft limit of 256 megabytes)
  307. # echo 256M > memory.soft_limit_in_bytes
  308. If we want to change this to 1G, we can at any time use
  309. # echo 1G > memory.soft_limit_in_bytes
  310. NOTE1: Soft limits take effect over a long period of time, since they involve
  311. reclaiming memory for balancing between memory cgroups
  312. NOTE2: It is recommended to set the soft limit always below the hard limit,
  313. otherwise the hard limit will take precedence.
  314. 8. Move charges at task migration
  315. Users can move charges associated with a task along with task migration, that
  316. is, uncharge task's pages from the old cgroup and charge them to the new cgroup.
  317. This feature is not supported in !CONFIG_MMU environments because of lack of
  318. page tables.
  319. 8.1 Interface
  320. This feature is disabled by default. It can be enabled(and disabled again) by
  321. writing to memory.move_charge_at_immigrate of the destination cgroup.
  322. If you want to enable it:
  323. # echo (some positive value) > memory.move_charge_at_immigrate
  324. Note: Each bits of move_charge_at_immigrate has its own meaning about what type
  325. of charges should be moved. See 8.2 for details.
  326. Note: Charges are moved only when you move mm->owner, IOW, a leader of a thread
  327. group.
  328. Note: If we cannot find enough space for the task in the destination cgroup, we
  329. try to make space by reclaiming memory. Task migration may fail if we
  330. cannot make enough space.
  331. Note: It can take several seconds if you move charges in giga bytes order.
  332. And if you want disable it again:
  333. # echo 0 > memory.move_charge_at_immigrate
  334. 8.2 Type of charges which can be move
  335. Each bits of move_charge_at_immigrate has its own meaning about what type of
  336. charges should be moved.
  337. bit | what type of charges would be moved ?
  338. -----+------------------------------------------------------------------------
  339. 0 | A charge of an anonymous page(or swap of it) used by the target task.
  340. | Those pages and swaps must be used only by the target task. You must
  341. | enable Swap Extension(see 2.4) to enable move of swap charges.
  342. Note: Those pages and swaps must be charged to the old cgroup.
  343. Note: More type of pages(e.g. file cache, shmem,) will be supported by other
  344. bits in future.
  345. 8.3 TODO
  346. - Add support for other types of pages(e.g. file cache, shmem, etc.).
  347. - Implement madvise(2) to let users decide the vma to be moved or not to be
  348. moved.
  349. - All of moving charge operations are done under cgroup_mutex. It's not good
  350. behavior to hold the mutex too long, so we may need some trick.
  351. 9. Memory thresholds
  352. Memory controler implements memory thresholds using cgroups notification
  353. API (see cgroups.txt). It allows to register multiple memory and memsw
  354. thresholds and gets notifications when it crosses.
  355. To register a threshold application need:
  356. - create an eventfd using eventfd(2);
  357. - open memory.usage_in_bytes or memory.memsw.usage_in_bytes;
  358. - write string like "<event_fd> <memory.usage_in_bytes> <threshold>" to
  359. cgroup.event_control.
  360. Application will be notified through eventfd when memory usage crosses
  361. threshold in any direction.
  362. It's applicable for root and non-root cgroup.
  363. 10. OOM Control
  364. Memory controler implements oom notifier using cgroup notification
  365. API (See cgroups.txt). It allows to register multiple oom notification
  366. delivery and gets notification when oom happens.
  367. To register a notifier, application need:
  368. - create an eventfd using eventfd(2)
  369. - open memory.oom_control file
  370. - write string like "<event_fd> <memory.oom_control>" to cgroup.event_control
  371. Application will be notifier through eventfd when oom happens.
  372. OOM notification doesn't work for root cgroup.
  373. 11. TODO
  374. 1. Add support for accounting huge pages (as a separate controller)
  375. 2. Make per-cgroup scanner reclaim not-shared pages first
  376. 3. Teach controller to account for shared-pages
  377. 4. Start reclamation in the background when the limit is
  378. not yet hit but the usage is getting closer
  379. Summary
  380. Overall, the memory controller has been a stable controller and has been
  381. commented and discussed quite extensively in the community.
  382. References
  383. 1. Singh, Balbir. RFC: Memory Controller, http://lwn.net/Articles/206697/
  384. 2. Singh, Balbir. Memory Controller (RSS Control),
  385. http://lwn.net/Articles/222762/
  386. 3. Emelianov, Pavel. Resource controllers based on process cgroups
  387. http://lkml.org/lkml/2007/3/6/198
  388. 4. Emelianov, Pavel. RSS controller based on process cgroups (v2)
  389. http://lkml.org/lkml/2007/4/9/78
  390. 5. Emelianov, Pavel. RSS controller based on process cgroups (v3)
  391. http://lkml.org/lkml/2007/5/30/244
  392. 6. Menage, Paul. Control Groups v10, http://lwn.net/Articles/236032/
  393. 7. Vaidyanathan, Srinivasan, Control Groups: Pagecache accounting and control
  394. subsystem (v3), http://lwn.net/Articles/235534/
  395. 8. Singh, Balbir. RSS controller v2 test results (lmbench),
  396. http://lkml.org/lkml/2007/5/17/232
  397. 9. Singh, Balbir. RSS controller v2 AIM9 results
  398. http://lkml.org/lkml/2007/5/18/1
  399. 10. Singh, Balbir. Memory controller v6 test results,
  400. http://lkml.org/lkml/2007/8/19/36
  401. 11. Singh, Balbir. Memory controller introduction (v6),
  402. http://lkml.org/lkml/2007/8/17/69
  403. 12. Corbet, Jonathan, Controlling memory use in cgroups,
  404. http://lwn.net/Articles/243795/