memcontrol.c 118 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657
  1. /* memcontrol.c - Memory Controller
  2. *
  3. * Copyright IBM Corporation, 2007
  4. * Author Balbir Singh <balbir@linux.vnet.ibm.com>
  5. *
  6. * Copyright 2007 OpenVZ SWsoft Inc
  7. * Author: Pavel Emelianov <xemul@openvz.org>
  8. *
  9. * Memory thresholds
  10. * Copyright (C) 2009 Nokia Corporation
  11. * Author: Kirill A. Shutemov
  12. *
  13. * This program is free software; you can redistribute it and/or modify
  14. * it under the terms of the GNU General Public License as published by
  15. * the Free Software Foundation; either version 2 of the License, or
  16. * (at your option) any later version.
  17. *
  18. * This program is distributed in the hope that it will be useful,
  19. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  21. * GNU General Public License for more details.
  22. */
  23. #include <linux/res_counter.h>
  24. #include <linux/memcontrol.h>
  25. #include <linux/cgroup.h>
  26. #include <linux/mm.h>
  27. #include <linux/hugetlb.h>
  28. #include <linux/pagemap.h>
  29. #include <linux/smp.h>
  30. #include <linux/page-flags.h>
  31. #include <linux/backing-dev.h>
  32. #include <linux/bit_spinlock.h>
  33. #include <linux/rcupdate.h>
  34. #include <linux/limits.h>
  35. #include <linux/mutex.h>
  36. #include <linux/rbtree.h>
  37. #include <linux/slab.h>
  38. #include <linux/swap.h>
  39. #include <linux/swapops.h>
  40. #include <linux/spinlock.h>
  41. #include <linux/eventfd.h>
  42. #include <linux/sort.h>
  43. #include <linux/fs.h>
  44. #include <linux/seq_file.h>
  45. #include <linux/vmalloc.h>
  46. #include <linux/mm_inline.h>
  47. #include <linux/page_cgroup.h>
  48. #include <linux/cpu.h>
  49. #include "internal.h"
  50. #include <asm/uaccess.h>
  51. struct cgroup_subsys mem_cgroup_subsys __read_mostly;
  52. #define MEM_CGROUP_RECLAIM_RETRIES 5
  53. struct mem_cgroup *root_mem_cgroup __read_mostly;
  54. #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
  55. /* Turned on only when memory cgroup is enabled && really_do_swap_account = 1 */
  56. int do_swap_account __read_mostly;
  57. static int really_do_swap_account __initdata = 1; /* for remember boot option*/
  58. #else
  59. #define do_swap_account (0)
  60. #endif
  61. /*
  62. * Per memcg event counter is incremented at every pagein/pageout. This counter
  63. * is used for trigger some periodic events. This is straightforward and better
  64. * than using jiffies etc. to handle periodic memcg event.
  65. *
  66. * These values will be used as !((event) & ((1 <<(thresh)) - 1))
  67. */
  68. #define THRESHOLDS_EVENTS_THRESH (7) /* once in 128 */
  69. #define SOFTLIMIT_EVENTS_THRESH (10) /* once in 1024 */
  70. /*
  71. * Statistics for memory cgroup.
  72. */
  73. enum mem_cgroup_stat_index {
  74. /*
  75. * For MEM_CONTAINER_TYPE_ALL, usage = pagecache + rss.
  76. */
  77. MEM_CGROUP_STAT_CACHE, /* # of pages charged as cache */
  78. MEM_CGROUP_STAT_RSS, /* # of pages charged as anon rss */
  79. MEM_CGROUP_STAT_FILE_MAPPED, /* # of pages charged as file rss */
  80. MEM_CGROUP_STAT_PGPGIN_COUNT, /* # of pages paged in */
  81. MEM_CGROUP_STAT_PGPGOUT_COUNT, /* # of pages paged out */
  82. MEM_CGROUP_STAT_SWAPOUT, /* # of pages, swapped out */
  83. MEM_CGROUP_EVENTS, /* incremented at every pagein/pageout */
  84. MEM_CGROUP_STAT_NSTATS,
  85. };
  86. struct mem_cgroup_stat_cpu {
  87. s64 count[MEM_CGROUP_STAT_NSTATS];
  88. };
  89. /*
  90. * per-zone information in memory controller.
  91. */
  92. struct mem_cgroup_per_zone {
  93. /*
  94. * spin_lock to protect the per cgroup LRU
  95. */
  96. struct list_head lists[NR_LRU_LISTS];
  97. unsigned long count[NR_LRU_LISTS];
  98. struct zone_reclaim_stat reclaim_stat;
  99. struct rb_node tree_node; /* RB tree node */
  100. unsigned long long usage_in_excess;/* Set to the value by which */
  101. /* the soft limit is exceeded*/
  102. bool on_tree;
  103. struct mem_cgroup *mem; /* Back pointer, we cannot */
  104. /* use container_of */
  105. };
  106. /* Macro for accessing counter */
  107. #define MEM_CGROUP_ZSTAT(mz, idx) ((mz)->count[(idx)])
  108. struct mem_cgroup_per_node {
  109. struct mem_cgroup_per_zone zoneinfo[MAX_NR_ZONES];
  110. };
  111. struct mem_cgroup_lru_info {
  112. struct mem_cgroup_per_node *nodeinfo[MAX_NUMNODES];
  113. };
  114. /*
  115. * Cgroups above their limits are maintained in a RB-Tree, independent of
  116. * their hierarchy representation
  117. */
  118. struct mem_cgroup_tree_per_zone {
  119. struct rb_root rb_root;
  120. spinlock_t lock;
  121. };
  122. struct mem_cgroup_tree_per_node {
  123. struct mem_cgroup_tree_per_zone rb_tree_per_zone[MAX_NR_ZONES];
  124. };
  125. struct mem_cgroup_tree {
  126. struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
  127. };
  128. static struct mem_cgroup_tree soft_limit_tree __read_mostly;
  129. struct mem_cgroup_threshold {
  130. struct eventfd_ctx *eventfd;
  131. u64 threshold;
  132. };
  133. /* For threshold */
  134. struct mem_cgroup_threshold_ary {
  135. /* An array index points to threshold just below usage. */
  136. int current_threshold;
  137. /* Size of entries[] */
  138. unsigned int size;
  139. /* Array of thresholds */
  140. struct mem_cgroup_threshold entries[0];
  141. };
  142. struct mem_cgroup_thresholds {
  143. /* Primary thresholds array */
  144. struct mem_cgroup_threshold_ary *primary;
  145. /*
  146. * Spare threshold array.
  147. * This is needed to make mem_cgroup_unregister_event() "never fail".
  148. * It must be able to store at least primary->size - 1 entries.
  149. */
  150. struct mem_cgroup_threshold_ary *spare;
  151. };
  152. /* for OOM */
  153. struct mem_cgroup_eventfd_list {
  154. struct list_head list;
  155. struct eventfd_ctx *eventfd;
  156. };
  157. static void mem_cgroup_threshold(struct mem_cgroup *mem);
  158. static void mem_cgroup_oom_notify(struct mem_cgroup *mem);
  159. /*
  160. * The memory controller data structure. The memory controller controls both
  161. * page cache and RSS per cgroup. We would eventually like to provide
  162. * statistics based on the statistics developed by Rik Van Riel for clock-pro,
  163. * to help the administrator determine what knobs to tune.
  164. *
  165. * TODO: Add a water mark for the memory controller. Reclaim will begin when
  166. * we hit the water mark. May be even add a low water mark, such that
  167. * no reclaim occurs from a cgroup at it's low water mark, this is
  168. * a feature that will be implemented much later in the future.
  169. */
  170. struct mem_cgroup {
  171. struct cgroup_subsys_state css;
  172. /*
  173. * the counter to account for memory usage
  174. */
  175. struct res_counter res;
  176. /*
  177. * the counter to account for mem+swap usage.
  178. */
  179. struct res_counter memsw;
  180. /*
  181. * Per cgroup active and inactive list, similar to the
  182. * per zone LRU lists.
  183. */
  184. struct mem_cgroup_lru_info info;
  185. /*
  186. protect against reclaim related member.
  187. */
  188. spinlock_t reclaim_param_lock;
  189. int prev_priority; /* for recording reclaim priority */
  190. /*
  191. * While reclaiming in a hierarchy, we cache the last child we
  192. * reclaimed from.
  193. */
  194. int last_scanned_child;
  195. /*
  196. * Should the accounting and control be hierarchical, per subtree?
  197. */
  198. bool use_hierarchy;
  199. atomic_t oom_lock;
  200. atomic_t refcnt;
  201. unsigned int swappiness;
  202. /* OOM-Killer disable */
  203. int oom_kill_disable;
  204. /* set when res.limit == memsw.limit */
  205. bool memsw_is_minimum;
  206. /* protect arrays of thresholds */
  207. struct mutex thresholds_lock;
  208. /* thresholds for memory usage. RCU-protected */
  209. struct mem_cgroup_thresholds thresholds;
  210. /* thresholds for mem+swap usage. RCU-protected */
  211. struct mem_cgroup_thresholds memsw_thresholds;
  212. /* For oom notifier event fd */
  213. struct list_head oom_notify;
  214. /*
  215. * Should we move charges of a task when a task is moved into this
  216. * mem_cgroup ? And what type of charges should we move ?
  217. */
  218. unsigned long move_charge_at_immigrate;
  219. /*
  220. * percpu counter.
  221. */
  222. struct mem_cgroup_stat_cpu *stat;
  223. };
  224. /* Stuffs for move charges at task migration. */
  225. /*
  226. * Types of charges to be moved. "move_charge_at_immitgrate" is treated as a
  227. * left-shifted bitmap of these types.
  228. */
  229. enum move_type {
  230. MOVE_CHARGE_TYPE_ANON, /* private anonymous page and swap of it */
  231. MOVE_CHARGE_TYPE_FILE, /* file page(including tmpfs) and swap of it */
  232. NR_MOVE_TYPE,
  233. };
  234. /* "mc" and its members are protected by cgroup_mutex */
  235. static struct move_charge_struct {
  236. struct mem_cgroup *from;
  237. struct mem_cgroup *to;
  238. unsigned long precharge;
  239. unsigned long moved_charge;
  240. unsigned long moved_swap;
  241. struct task_struct *moving_task; /* a task moving charges */
  242. wait_queue_head_t waitq; /* a waitq for other context */
  243. } mc = {
  244. .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
  245. };
  246. static bool move_anon(void)
  247. {
  248. return test_bit(MOVE_CHARGE_TYPE_ANON,
  249. &mc.to->move_charge_at_immigrate);
  250. }
  251. static bool move_file(void)
  252. {
  253. return test_bit(MOVE_CHARGE_TYPE_FILE,
  254. &mc.to->move_charge_at_immigrate);
  255. }
  256. /*
  257. * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
  258. * limit reclaim to prevent infinite loops, if they ever occur.
  259. */
  260. #define MEM_CGROUP_MAX_RECLAIM_LOOPS (100)
  261. #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS (2)
  262. enum charge_type {
  263. MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
  264. MEM_CGROUP_CHARGE_TYPE_MAPPED,
  265. MEM_CGROUP_CHARGE_TYPE_SHMEM, /* used by page migration of shmem */
  266. MEM_CGROUP_CHARGE_TYPE_FORCE, /* used by force_empty */
  267. MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
  268. MEM_CGROUP_CHARGE_TYPE_DROP, /* a page was unused swap cache */
  269. NR_CHARGE_TYPE,
  270. };
  271. /* only for here (for easy reading.) */
  272. #define PCGF_CACHE (1UL << PCG_CACHE)
  273. #define PCGF_USED (1UL << PCG_USED)
  274. #define PCGF_LOCK (1UL << PCG_LOCK)
  275. /* Not used, but added here for completeness */
  276. #define PCGF_ACCT (1UL << PCG_ACCT)
  277. /* for encoding cft->private value on file */
  278. #define _MEM (0)
  279. #define _MEMSWAP (1)
  280. #define _OOM_TYPE (2)
  281. #define MEMFILE_PRIVATE(x, val) (((x) << 16) | (val))
  282. #define MEMFILE_TYPE(val) (((val) >> 16) & 0xffff)
  283. #define MEMFILE_ATTR(val) ((val) & 0xffff)
  284. /* Used for OOM nofiier */
  285. #define OOM_CONTROL (0)
  286. /*
  287. * Reclaim flags for mem_cgroup_hierarchical_reclaim
  288. */
  289. #define MEM_CGROUP_RECLAIM_NOSWAP_BIT 0x0
  290. #define MEM_CGROUP_RECLAIM_NOSWAP (1 << MEM_CGROUP_RECLAIM_NOSWAP_BIT)
  291. #define MEM_CGROUP_RECLAIM_SHRINK_BIT 0x1
  292. #define MEM_CGROUP_RECLAIM_SHRINK (1 << MEM_CGROUP_RECLAIM_SHRINK_BIT)
  293. #define MEM_CGROUP_RECLAIM_SOFT_BIT 0x2
  294. #define MEM_CGROUP_RECLAIM_SOFT (1 << MEM_CGROUP_RECLAIM_SOFT_BIT)
  295. static void mem_cgroup_get(struct mem_cgroup *mem);
  296. static void mem_cgroup_put(struct mem_cgroup *mem);
  297. static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *mem);
  298. static void drain_all_stock_async(void);
  299. static struct mem_cgroup_per_zone *
  300. mem_cgroup_zoneinfo(struct mem_cgroup *mem, int nid, int zid)
  301. {
  302. return &mem->info.nodeinfo[nid]->zoneinfo[zid];
  303. }
  304. struct cgroup_subsys_state *mem_cgroup_css(struct mem_cgroup *mem)
  305. {
  306. return &mem->css;
  307. }
  308. static struct mem_cgroup_per_zone *
  309. page_cgroup_zoneinfo(struct page_cgroup *pc)
  310. {
  311. struct mem_cgroup *mem = pc->mem_cgroup;
  312. int nid = page_cgroup_nid(pc);
  313. int zid = page_cgroup_zid(pc);
  314. if (!mem)
  315. return NULL;
  316. return mem_cgroup_zoneinfo(mem, nid, zid);
  317. }
  318. static struct mem_cgroup_tree_per_zone *
  319. soft_limit_tree_node_zone(int nid, int zid)
  320. {
  321. return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
  322. }
  323. static struct mem_cgroup_tree_per_zone *
  324. soft_limit_tree_from_page(struct page *page)
  325. {
  326. int nid = page_to_nid(page);
  327. int zid = page_zonenum(page);
  328. return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
  329. }
  330. static void
  331. __mem_cgroup_insert_exceeded(struct mem_cgroup *mem,
  332. struct mem_cgroup_per_zone *mz,
  333. struct mem_cgroup_tree_per_zone *mctz,
  334. unsigned long long new_usage_in_excess)
  335. {
  336. struct rb_node **p = &mctz->rb_root.rb_node;
  337. struct rb_node *parent = NULL;
  338. struct mem_cgroup_per_zone *mz_node;
  339. if (mz->on_tree)
  340. return;
  341. mz->usage_in_excess = new_usage_in_excess;
  342. if (!mz->usage_in_excess)
  343. return;
  344. while (*p) {
  345. parent = *p;
  346. mz_node = rb_entry(parent, struct mem_cgroup_per_zone,
  347. tree_node);
  348. if (mz->usage_in_excess < mz_node->usage_in_excess)
  349. p = &(*p)->rb_left;
  350. /*
  351. * We can't avoid mem cgroups that are over their soft
  352. * limit by the same amount
  353. */
  354. else if (mz->usage_in_excess >= mz_node->usage_in_excess)
  355. p = &(*p)->rb_right;
  356. }
  357. rb_link_node(&mz->tree_node, parent, p);
  358. rb_insert_color(&mz->tree_node, &mctz->rb_root);
  359. mz->on_tree = true;
  360. }
  361. static void
  362. __mem_cgroup_remove_exceeded(struct mem_cgroup *mem,
  363. struct mem_cgroup_per_zone *mz,
  364. struct mem_cgroup_tree_per_zone *mctz)
  365. {
  366. if (!mz->on_tree)
  367. return;
  368. rb_erase(&mz->tree_node, &mctz->rb_root);
  369. mz->on_tree = false;
  370. }
  371. static void
  372. mem_cgroup_remove_exceeded(struct mem_cgroup *mem,
  373. struct mem_cgroup_per_zone *mz,
  374. struct mem_cgroup_tree_per_zone *mctz)
  375. {
  376. spin_lock(&mctz->lock);
  377. __mem_cgroup_remove_exceeded(mem, mz, mctz);
  378. spin_unlock(&mctz->lock);
  379. }
  380. static void mem_cgroup_update_tree(struct mem_cgroup *mem, struct page *page)
  381. {
  382. unsigned long long excess;
  383. struct mem_cgroup_per_zone *mz;
  384. struct mem_cgroup_tree_per_zone *mctz;
  385. int nid = page_to_nid(page);
  386. int zid = page_zonenum(page);
  387. mctz = soft_limit_tree_from_page(page);
  388. /*
  389. * Necessary to update all ancestors when hierarchy is used.
  390. * because their event counter is not touched.
  391. */
  392. for (; mem; mem = parent_mem_cgroup(mem)) {
  393. mz = mem_cgroup_zoneinfo(mem, nid, zid);
  394. excess = res_counter_soft_limit_excess(&mem->res);
  395. /*
  396. * We have to update the tree if mz is on RB-tree or
  397. * mem is over its softlimit.
  398. */
  399. if (excess || mz->on_tree) {
  400. spin_lock(&mctz->lock);
  401. /* if on-tree, remove it */
  402. if (mz->on_tree)
  403. __mem_cgroup_remove_exceeded(mem, mz, mctz);
  404. /*
  405. * Insert again. mz->usage_in_excess will be updated.
  406. * If excess is 0, no tree ops.
  407. */
  408. __mem_cgroup_insert_exceeded(mem, mz, mctz, excess);
  409. spin_unlock(&mctz->lock);
  410. }
  411. }
  412. }
  413. static void mem_cgroup_remove_from_trees(struct mem_cgroup *mem)
  414. {
  415. int node, zone;
  416. struct mem_cgroup_per_zone *mz;
  417. struct mem_cgroup_tree_per_zone *mctz;
  418. for_each_node_state(node, N_POSSIBLE) {
  419. for (zone = 0; zone < MAX_NR_ZONES; zone++) {
  420. mz = mem_cgroup_zoneinfo(mem, node, zone);
  421. mctz = soft_limit_tree_node_zone(node, zone);
  422. mem_cgroup_remove_exceeded(mem, mz, mctz);
  423. }
  424. }
  425. }
  426. static inline unsigned long mem_cgroup_get_excess(struct mem_cgroup *mem)
  427. {
  428. return res_counter_soft_limit_excess(&mem->res) >> PAGE_SHIFT;
  429. }
  430. static struct mem_cgroup_per_zone *
  431. __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
  432. {
  433. struct rb_node *rightmost = NULL;
  434. struct mem_cgroup_per_zone *mz;
  435. retry:
  436. mz = NULL;
  437. rightmost = rb_last(&mctz->rb_root);
  438. if (!rightmost)
  439. goto done; /* Nothing to reclaim from */
  440. mz = rb_entry(rightmost, struct mem_cgroup_per_zone, tree_node);
  441. /*
  442. * Remove the node now but someone else can add it back,
  443. * we will to add it back at the end of reclaim to its correct
  444. * position in the tree.
  445. */
  446. __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
  447. if (!res_counter_soft_limit_excess(&mz->mem->res) ||
  448. !css_tryget(&mz->mem->css))
  449. goto retry;
  450. done:
  451. return mz;
  452. }
  453. static struct mem_cgroup_per_zone *
  454. mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
  455. {
  456. struct mem_cgroup_per_zone *mz;
  457. spin_lock(&mctz->lock);
  458. mz = __mem_cgroup_largest_soft_limit_node(mctz);
  459. spin_unlock(&mctz->lock);
  460. return mz;
  461. }
  462. static s64 mem_cgroup_read_stat(struct mem_cgroup *mem,
  463. enum mem_cgroup_stat_index idx)
  464. {
  465. int cpu;
  466. s64 val = 0;
  467. for_each_possible_cpu(cpu)
  468. val += per_cpu(mem->stat->count[idx], cpu);
  469. return val;
  470. }
  471. static s64 mem_cgroup_local_usage(struct mem_cgroup *mem)
  472. {
  473. s64 ret;
  474. ret = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_RSS);
  475. ret += mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_CACHE);
  476. return ret;
  477. }
  478. static void mem_cgroup_swap_statistics(struct mem_cgroup *mem,
  479. bool charge)
  480. {
  481. int val = (charge) ? 1 : -1;
  482. this_cpu_add(mem->stat->count[MEM_CGROUP_STAT_SWAPOUT], val);
  483. }
  484. static void mem_cgroup_charge_statistics(struct mem_cgroup *mem,
  485. struct page_cgroup *pc,
  486. bool charge)
  487. {
  488. int val = (charge) ? 1 : -1;
  489. preempt_disable();
  490. if (PageCgroupCache(pc))
  491. __this_cpu_add(mem->stat->count[MEM_CGROUP_STAT_CACHE], val);
  492. else
  493. __this_cpu_add(mem->stat->count[MEM_CGROUP_STAT_RSS], val);
  494. if (charge)
  495. __this_cpu_inc(mem->stat->count[MEM_CGROUP_STAT_PGPGIN_COUNT]);
  496. else
  497. __this_cpu_inc(mem->stat->count[MEM_CGROUP_STAT_PGPGOUT_COUNT]);
  498. __this_cpu_inc(mem->stat->count[MEM_CGROUP_EVENTS]);
  499. preempt_enable();
  500. }
  501. static unsigned long mem_cgroup_get_local_zonestat(struct mem_cgroup *mem,
  502. enum lru_list idx)
  503. {
  504. int nid, zid;
  505. struct mem_cgroup_per_zone *mz;
  506. u64 total = 0;
  507. for_each_online_node(nid)
  508. for (zid = 0; zid < MAX_NR_ZONES; zid++) {
  509. mz = mem_cgroup_zoneinfo(mem, nid, zid);
  510. total += MEM_CGROUP_ZSTAT(mz, idx);
  511. }
  512. return total;
  513. }
  514. static bool __memcg_event_check(struct mem_cgroup *mem, int event_mask_shift)
  515. {
  516. s64 val;
  517. val = this_cpu_read(mem->stat->count[MEM_CGROUP_EVENTS]);
  518. return !(val & ((1 << event_mask_shift) - 1));
  519. }
  520. /*
  521. * Check events in order.
  522. *
  523. */
  524. static void memcg_check_events(struct mem_cgroup *mem, struct page *page)
  525. {
  526. /* threshold event is triggered in finer grain than soft limit */
  527. if (unlikely(__memcg_event_check(mem, THRESHOLDS_EVENTS_THRESH))) {
  528. mem_cgroup_threshold(mem);
  529. if (unlikely(__memcg_event_check(mem, SOFTLIMIT_EVENTS_THRESH)))
  530. mem_cgroup_update_tree(mem, page);
  531. }
  532. }
  533. static struct mem_cgroup *mem_cgroup_from_cont(struct cgroup *cont)
  534. {
  535. return container_of(cgroup_subsys_state(cont,
  536. mem_cgroup_subsys_id), struct mem_cgroup,
  537. css);
  538. }
  539. struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
  540. {
  541. /*
  542. * mm_update_next_owner() may clear mm->owner to NULL
  543. * if it races with swapoff, page migration, etc.
  544. * So this can be called with p == NULL.
  545. */
  546. if (unlikely(!p))
  547. return NULL;
  548. return container_of(task_subsys_state(p, mem_cgroup_subsys_id),
  549. struct mem_cgroup, css);
  550. }
  551. static struct mem_cgroup *try_get_mem_cgroup_from_mm(struct mm_struct *mm)
  552. {
  553. struct mem_cgroup *mem = NULL;
  554. if (!mm)
  555. return NULL;
  556. /*
  557. * Because we have no locks, mm->owner's may be being moved to other
  558. * cgroup. We use css_tryget() here even if this looks
  559. * pessimistic (rather than adding locks here).
  560. */
  561. rcu_read_lock();
  562. do {
  563. mem = mem_cgroup_from_task(rcu_dereference(mm->owner));
  564. if (unlikely(!mem))
  565. break;
  566. } while (!css_tryget(&mem->css));
  567. rcu_read_unlock();
  568. return mem;
  569. }
  570. /*
  571. * Call callback function against all cgroup under hierarchy tree.
  572. */
  573. static int mem_cgroup_walk_tree(struct mem_cgroup *root, void *data,
  574. int (*func)(struct mem_cgroup *, void *))
  575. {
  576. int found, ret, nextid;
  577. struct cgroup_subsys_state *css;
  578. struct mem_cgroup *mem;
  579. if (!root->use_hierarchy)
  580. return (*func)(root, data);
  581. nextid = 1;
  582. do {
  583. ret = 0;
  584. mem = NULL;
  585. rcu_read_lock();
  586. css = css_get_next(&mem_cgroup_subsys, nextid, &root->css,
  587. &found);
  588. if (css && css_tryget(css))
  589. mem = container_of(css, struct mem_cgroup, css);
  590. rcu_read_unlock();
  591. if (mem) {
  592. ret = (*func)(mem, data);
  593. css_put(&mem->css);
  594. }
  595. nextid = found + 1;
  596. } while (!ret && css);
  597. return ret;
  598. }
  599. static inline bool mem_cgroup_is_root(struct mem_cgroup *mem)
  600. {
  601. return (mem == root_mem_cgroup);
  602. }
  603. /*
  604. * Following LRU functions are allowed to be used without PCG_LOCK.
  605. * Operations are called by routine of global LRU independently from memcg.
  606. * What we have to take care of here is validness of pc->mem_cgroup.
  607. *
  608. * Changes to pc->mem_cgroup happens when
  609. * 1. charge
  610. * 2. moving account
  611. * In typical case, "charge" is done before add-to-lru. Exception is SwapCache.
  612. * It is added to LRU before charge.
  613. * If PCG_USED bit is not set, page_cgroup is not added to this private LRU.
  614. * When moving account, the page is not on LRU. It's isolated.
  615. */
  616. void mem_cgroup_del_lru_list(struct page *page, enum lru_list lru)
  617. {
  618. struct page_cgroup *pc;
  619. struct mem_cgroup_per_zone *mz;
  620. if (mem_cgroup_disabled())
  621. return;
  622. pc = lookup_page_cgroup(page);
  623. /* can happen while we handle swapcache. */
  624. if (!TestClearPageCgroupAcctLRU(pc))
  625. return;
  626. VM_BUG_ON(!pc->mem_cgroup);
  627. /*
  628. * We don't check PCG_USED bit. It's cleared when the "page" is finally
  629. * removed from global LRU.
  630. */
  631. mz = page_cgroup_zoneinfo(pc);
  632. MEM_CGROUP_ZSTAT(mz, lru) -= 1;
  633. if (mem_cgroup_is_root(pc->mem_cgroup))
  634. return;
  635. VM_BUG_ON(list_empty(&pc->lru));
  636. list_del_init(&pc->lru);
  637. return;
  638. }
  639. void mem_cgroup_del_lru(struct page *page)
  640. {
  641. mem_cgroup_del_lru_list(page, page_lru(page));
  642. }
  643. void mem_cgroup_rotate_lru_list(struct page *page, enum lru_list lru)
  644. {
  645. struct mem_cgroup_per_zone *mz;
  646. struct page_cgroup *pc;
  647. if (mem_cgroup_disabled())
  648. return;
  649. pc = lookup_page_cgroup(page);
  650. /*
  651. * Used bit is set without atomic ops but after smp_wmb().
  652. * For making pc->mem_cgroup visible, insert smp_rmb() here.
  653. */
  654. smp_rmb();
  655. /* unused or root page is not rotated. */
  656. if (!PageCgroupUsed(pc) || mem_cgroup_is_root(pc->mem_cgroup))
  657. return;
  658. mz = page_cgroup_zoneinfo(pc);
  659. list_move(&pc->lru, &mz->lists[lru]);
  660. }
  661. void mem_cgroup_add_lru_list(struct page *page, enum lru_list lru)
  662. {
  663. struct page_cgroup *pc;
  664. struct mem_cgroup_per_zone *mz;
  665. if (mem_cgroup_disabled())
  666. return;
  667. pc = lookup_page_cgroup(page);
  668. VM_BUG_ON(PageCgroupAcctLRU(pc));
  669. /*
  670. * Used bit is set without atomic ops but after smp_wmb().
  671. * For making pc->mem_cgroup visible, insert smp_rmb() here.
  672. */
  673. smp_rmb();
  674. if (!PageCgroupUsed(pc))
  675. return;
  676. mz = page_cgroup_zoneinfo(pc);
  677. MEM_CGROUP_ZSTAT(mz, lru) += 1;
  678. SetPageCgroupAcctLRU(pc);
  679. if (mem_cgroup_is_root(pc->mem_cgroup))
  680. return;
  681. list_add(&pc->lru, &mz->lists[lru]);
  682. }
  683. /*
  684. * At handling SwapCache, pc->mem_cgroup may be changed while it's linked to
  685. * lru because the page may.be reused after it's fully uncharged (because of
  686. * SwapCache behavior).To handle that, unlink page_cgroup from LRU when charge
  687. * it again. This function is only used to charge SwapCache. It's done under
  688. * lock_page and expected that zone->lru_lock is never held.
  689. */
  690. static void mem_cgroup_lru_del_before_commit_swapcache(struct page *page)
  691. {
  692. unsigned long flags;
  693. struct zone *zone = page_zone(page);
  694. struct page_cgroup *pc = lookup_page_cgroup(page);
  695. spin_lock_irqsave(&zone->lru_lock, flags);
  696. /*
  697. * Forget old LRU when this page_cgroup is *not* used. This Used bit
  698. * is guarded by lock_page() because the page is SwapCache.
  699. */
  700. if (!PageCgroupUsed(pc))
  701. mem_cgroup_del_lru_list(page, page_lru(page));
  702. spin_unlock_irqrestore(&zone->lru_lock, flags);
  703. }
  704. static void mem_cgroup_lru_add_after_commit_swapcache(struct page *page)
  705. {
  706. unsigned long flags;
  707. struct zone *zone = page_zone(page);
  708. struct page_cgroup *pc = lookup_page_cgroup(page);
  709. spin_lock_irqsave(&zone->lru_lock, flags);
  710. /* link when the page is linked to LRU but page_cgroup isn't */
  711. if (PageLRU(page) && !PageCgroupAcctLRU(pc))
  712. mem_cgroup_add_lru_list(page, page_lru(page));
  713. spin_unlock_irqrestore(&zone->lru_lock, flags);
  714. }
  715. void mem_cgroup_move_lists(struct page *page,
  716. enum lru_list from, enum lru_list to)
  717. {
  718. if (mem_cgroup_disabled())
  719. return;
  720. mem_cgroup_del_lru_list(page, from);
  721. mem_cgroup_add_lru_list(page, to);
  722. }
  723. int task_in_mem_cgroup(struct task_struct *task, const struct mem_cgroup *mem)
  724. {
  725. int ret;
  726. struct mem_cgroup *curr = NULL;
  727. task_lock(task);
  728. rcu_read_lock();
  729. curr = try_get_mem_cgroup_from_mm(task->mm);
  730. rcu_read_unlock();
  731. task_unlock(task);
  732. if (!curr)
  733. return 0;
  734. /*
  735. * We should check use_hierarchy of "mem" not "curr". Because checking
  736. * use_hierarchy of "curr" here make this function true if hierarchy is
  737. * enabled in "curr" and "curr" is a child of "mem" in *cgroup*
  738. * hierarchy(even if use_hierarchy is disabled in "mem").
  739. */
  740. if (mem->use_hierarchy)
  741. ret = css_is_ancestor(&curr->css, &mem->css);
  742. else
  743. ret = (curr == mem);
  744. css_put(&curr->css);
  745. return ret;
  746. }
  747. /*
  748. * prev_priority control...this will be used in memory reclaim path.
  749. */
  750. int mem_cgroup_get_reclaim_priority(struct mem_cgroup *mem)
  751. {
  752. int prev_priority;
  753. spin_lock(&mem->reclaim_param_lock);
  754. prev_priority = mem->prev_priority;
  755. spin_unlock(&mem->reclaim_param_lock);
  756. return prev_priority;
  757. }
  758. void mem_cgroup_note_reclaim_priority(struct mem_cgroup *mem, int priority)
  759. {
  760. spin_lock(&mem->reclaim_param_lock);
  761. if (priority < mem->prev_priority)
  762. mem->prev_priority = priority;
  763. spin_unlock(&mem->reclaim_param_lock);
  764. }
  765. void mem_cgroup_record_reclaim_priority(struct mem_cgroup *mem, int priority)
  766. {
  767. spin_lock(&mem->reclaim_param_lock);
  768. mem->prev_priority = priority;
  769. spin_unlock(&mem->reclaim_param_lock);
  770. }
  771. static int calc_inactive_ratio(struct mem_cgroup *memcg, unsigned long *present_pages)
  772. {
  773. unsigned long active;
  774. unsigned long inactive;
  775. unsigned long gb;
  776. unsigned long inactive_ratio;
  777. inactive = mem_cgroup_get_local_zonestat(memcg, LRU_INACTIVE_ANON);
  778. active = mem_cgroup_get_local_zonestat(memcg, LRU_ACTIVE_ANON);
  779. gb = (inactive + active) >> (30 - PAGE_SHIFT);
  780. if (gb)
  781. inactive_ratio = int_sqrt(10 * gb);
  782. else
  783. inactive_ratio = 1;
  784. if (present_pages) {
  785. present_pages[0] = inactive;
  786. present_pages[1] = active;
  787. }
  788. return inactive_ratio;
  789. }
  790. int mem_cgroup_inactive_anon_is_low(struct mem_cgroup *memcg)
  791. {
  792. unsigned long active;
  793. unsigned long inactive;
  794. unsigned long present_pages[2];
  795. unsigned long inactive_ratio;
  796. inactive_ratio = calc_inactive_ratio(memcg, present_pages);
  797. inactive = present_pages[0];
  798. active = present_pages[1];
  799. if (inactive * inactive_ratio < active)
  800. return 1;
  801. return 0;
  802. }
  803. int mem_cgroup_inactive_file_is_low(struct mem_cgroup *memcg)
  804. {
  805. unsigned long active;
  806. unsigned long inactive;
  807. inactive = mem_cgroup_get_local_zonestat(memcg, LRU_INACTIVE_FILE);
  808. active = mem_cgroup_get_local_zonestat(memcg, LRU_ACTIVE_FILE);
  809. return (active > inactive);
  810. }
  811. unsigned long mem_cgroup_zone_nr_pages(struct mem_cgroup *memcg,
  812. struct zone *zone,
  813. enum lru_list lru)
  814. {
  815. int nid = zone->zone_pgdat->node_id;
  816. int zid = zone_idx(zone);
  817. struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(memcg, nid, zid);
  818. return MEM_CGROUP_ZSTAT(mz, lru);
  819. }
  820. struct zone_reclaim_stat *mem_cgroup_get_reclaim_stat(struct mem_cgroup *memcg,
  821. struct zone *zone)
  822. {
  823. int nid = zone->zone_pgdat->node_id;
  824. int zid = zone_idx(zone);
  825. struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(memcg, nid, zid);
  826. return &mz->reclaim_stat;
  827. }
  828. struct zone_reclaim_stat *
  829. mem_cgroup_get_reclaim_stat_from_page(struct page *page)
  830. {
  831. struct page_cgroup *pc;
  832. struct mem_cgroup_per_zone *mz;
  833. if (mem_cgroup_disabled())
  834. return NULL;
  835. pc = lookup_page_cgroup(page);
  836. /*
  837. * Used bit is set without atomic ops but after smp_wmb().
  838. * For making pc->mem_cgroup visible, insert smp_rmb() here.
  839. */
  840. smp_rmb();
  841. if (!PageCgroupUsed(pc))
  842. return NULL;
  843. mz = page_cgroup_zoneinfo(pc);
  844. if (!mz)
  845. return NULL;
  846. return &mz->reclaim_stat;
  847. }
  848. unsigned long mem_cgroup_isolate_pages(unsigned long nr_to_scan,
  849. struct list_head *dst,
  850. unsigned long *scanned, int order,
  851. int mode, struct zone *z,
  852. struct mem_cgroup *mem_cont,
  853. int active, int file)
  854. {
  855. unsigned long nr_taken = 0;
  856. struct page *page;
  857. unsigned long scan;
  858. LIST_HEAD(pc_list);
  859. struct list_head *src;
  860. struct page_cgroup *pc, *tmp;
  861. int nid = z->zone_pgdat->node_id;
  862. int zid = zone_idx(z);
  863. struct mem_cgroup_per_zone *mz;
  864. int lru = LRU_FILE * file + active;
  865. int ret;
  866. BUG_ON(!mem_cont);
  867. mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
  868. src = &mz->lists[lru];
  869. scan = 0;
  870. list_for_each_entry_safe_reverse(pc, tmp, src, lru) {
  871. if (scan >= nr_to_scan)
  872. break;
  873. page = pc->page;
  874. if (unlikely(!PageCgroupUsed(pc)))
  875. continue;
  876. if (unlikely(!PageLRU(page)))
  877. continue;
  878. scan++;
  879. ret = __isolate_lru_page(page, mode, file);
  880. switch (ret) {
  881. case 0:
  882. list_move(&page->lru, dst);
  883. mem_cgroup_del_lru(page);
  884. nr_taken++;
  885. break;
  886. case -EBUSY:
  887. /* we don't affect global LRU but rotate in our LRU */
  888. mem_cgroup_rotate_lru_list(page, page_lru(page));
  889. break;
  890. default:
  891. break;
  892. }
  893. }
  894. *scanned = scan;
  895. return nr_taken;
  896. }
  897. #define mem_cgroup_from_res_counter(counter, member) \
  898. container_of(counter, struct mem_cgroup, member)
  899. static bool mem_cgroup_check_under_limit(struct mem_cgroup *mem)
  900. {
  901. if (do_swap_account) {
  902. if (res_counter_check_under_limit(&mem->res) &&
  903. res_counter_check_under_limit(&mem->memsw))
  904. return true;
  905. } else
  906. if (res_counter_check_under_limit(&mem->res))
  907. return true;
  908. return false;
  909. }
  910. static unsigned int get_swappiness(struct mem_cgroup *memcg)
  911. {
  912. struct cgroup *cgrp = memcg->css.cgroup;
  913. unsigned int swappiness;
  914. /* root ? */
  915. if (cgrp->parent == NULL)
  916. return vm_swappiness;
  917. spin_lock(&memcg->reclaim_param_lock);
  918. swappiness = memcg->swappiness;
  919. spin_unlock(&memcg->reclaim_param_lock);
  920. return swappiness;
  921. }
  922. static int mem_cgroup_count_children_cb(struct mem_cgroup *mem, void *data)
  923. {
  924. int *val = data;
  925. (*val)++;
  926. return 0;
  927. }
  928. /**
  929. * mem_cgroup_print_oom_info: Called from OOM with tasklist_lock held in read mode.
  930. * @memcg: The memory cgroup that went over limit
  931. * @p: Task that is going to be killed
  932. *
  933. * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
  934. * enabled
  935. */
  936. void mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p)
  937. {
  938. struct cgroup *task_cgrp;
  939. struct cgroup *mem_cgrp;
  940. /*
  941. * Need a buffer in BSS, can't rely on allocations. The code relies
  942. * on the assumption that OOM is serialized for memory controller.
  943. * If this assumption is broken, revisit this code.
  944. */
  945. static char memcg_name[PATH_MAX];
  946. int ret;
  947. if (!memcg || !p)
  948. return;
  949. rcu_read_lock();
  950. mem_cgrp = memcg->css.cgroup;
  951. task_cgrp = task_cgroup(p, mem_cgroup_subsys_id);
  952. ret = cgroup_path(task_cgrp, memcg_name, PATH_MAX);
  953. if (ret < 0) {
  954. /*
  955. * Unfortunately, we are unable to convert to a useful name
  956. * But we'll still print out the usage information
  957. */
  958. rcu_read_unlock();
  959. goto done;
  960. }
  961. rcu_read_unlock();
  962. printk(KERN_INFO "Task in %s killed", memcg_name);
  963. rcu_read_lock();
  964. ret = cgroup_path(mem_cgrp, memcg_name, PATH_MAX);
  965. if (ret < 0) {
  966. rcu_read_unlock();
  967. goto done;
  968. }
  969. rcu_read_unlock();
  970. /*
  971. * Continues from above, so we don't need an KERN_ level
  972. */
  973. printk(KERN_CONT " as a result of limit of %s\n", memcg_name);
  974. done:
  975. printk(KERN_INFO "memory: usage %llukB, limit %llukB, failcnt %llu\n",
  976. res_counter_read_u64(&memcg->res, RES_USAGE) >> 10,
  977. res_counter_read_u64(&memcg->res, RES_LIMIT) >> 10,
  978. res_counter_read_u64(&memcg->res, RES_FAILCNT));
  979. printk(KERN_INFO "memory+swap: usage %llukB, limit %llukB, "
  980. "failcnt %llu\n",
  981. res_counter_read_u64(&memcg->memsw, RES_USAGE) >> 10,
  982. res_counter_read_u64(&memcg->memsw, RES_LIMIT) >> 10,
  983. res_counter_read_u64(&memcg->memsw, RES_FAILCNT));
  984. }
  985. /*
  986. * This function returns the number of memcg under hierarchy tree. Returns
  987. * 1(self count) if no children.
  988. */
  989. static int mem_cgroup_count_children(struct mem_cgroup *mem)
  990. {
  991. int num = 0;
  992. mem_cgroup_walk_tree(mem, &num, mem_cgroup_count_children_cb);
  993. return num;
  994. }
  995. /*
  996. * Visit the first child (need not be the first child as per the ordering
  997. * of the cgroup list, since we track last_scanned_child) of @mem and use
  998. * that to reclaim free pages from.
  999. */
  1000. static struct mem_cgroup *
  1001. mem_cgroup_select_victim(struct mem_cgroup *root_mem)
  1002. {
  1003. struct mem_cgroup *ret = NULL;
  1004. struct cgroup_subsys_state *css;
  1005. int nextid, found;
  1006. if (!root_mem->use_hierarchy) {
  1007. css_get(&root_mem->css);
  1008. ret = root_mem;
  1009. }
  1010. while (!ret) {
  1011. rcu_read_lock();
  1012. nextid = root_mem->last_scanned_child + 1;
  1013. css = css_get_next(&mem_cgroup_subsys, nextid, &root_mem->css,
  1014. &found);
  1015. if (css && css_tryget(css))
  1016. ret = container_of(css, struct mem_cgroup, css);
  1017. rcu_read_unlock();
  1018. /* Updates scanning parameter */
  1019. spin_lock(&root_mem->reclaim_param_lock);
  1020. if (!css) {
  1021. /* this means start scan from ID:1 */
  1022. root_mem->last_scanned_child = 0;
  1023. } else
  1024. root_mem->last_scanned_child = found;
  1025. spin_unlock(&root_mem->reclaim_param_lock);
  1026. }
  1027. return ret;
  1028. }
  1029. /*
  1030. * Scan the hierarchy if needed to reclaim memory. We remember the last child
  1031. * we reclaimed from, so that we don't end up penalizing one child extensively
  1032. * based on its position in the children list.
  1033. *
  1034. * root_mem is the original ancestor that we've been reclaim from.
  1035. *
  1036. * We give up and return to the caller when we visit root_mem twice.
  1037. * (other groups can be removed while we're walking....)
  1038. *
  1039. * If shrink==true, for avoiding to free too much, this returns immedieately.
  1040. */
  1041. static int mem_cgroup_hierarchical_reclaim(struct mem_cgroup *root_mem,
  1042. struct zone *zone,
  1043. gfp_t gfp_mask,
  1044. unsigned long reclaim_options)
  1045. {
  1046. struct mem_cgroup *victim;
  1047. int ret, total = 0;
  1048. int loop = 0;
  1049. bool noswap = reclaim_options & MEM_CGROUP_RECLAIM_NOSWAP;
  1050. bool shrink = reclaim_options & MEM_CGROUP_RECLAIM_SHRINK;
  1051. bool check_soft = reclaim_options & MEM_CGROUP_RECLAIM_SOFT;
  1052. unsigned long excess = mem_cgroup_get_excess(root_mem);
  1053. /* If memsw_is_minimum==1, swap-out is of-no-use. */
  1054. if (root_mem->memsw_is_minimum)
  1055. noswap = true;
  1056. while (1) {
  1057. victim = mem_cgroup_select_victim(root_mem);
  1058. if (victim == root_mem) {
  1059. loop++;
  1060. if (loop >= 1)
  1061. drain_all_stock_async();
  1062. if (loop >= 2) {
  1063. /*
  1064. * If we have not been able to reclaim
  1065. * anything, it might because there are
  1066. * no reclaimable pages under this hierarchy
  1067. */
  1068. if (!check_soft || !total) {
  1069. css_put(&victim->css);
  1070. break;
  1071. }
  1072. /*
  1073. * We want to do more targetted reclaim.
  1074. * excess >> 2 is not to excessive so as to
  1075. * reclaim too much, nor too less that we keep
  1076. * coming back to reclaim from this cgroup
  1077. */
  1078. if (total >= (excess >> 2) ||
  1079. (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS)) {
  1080. css_put(&victim->css);
  1081. break;
  1082. }
  1083. }
  1084. }
  1085. if (!mem_cgroup_local_usage(victim)) {
  1086. /* this cgroup's local usage == 0 */
  1087. css_put(&victim->css);
  1088. continue;
  1089. }
  1090. /* we use swappiness of local cgroup */
  1091. if (check_soft)
  1092. ret = mem_cgroup_shrink_node_zone(victim, gfp_mask,
  1093. noswap, get_swappiness(victim), zone,
  1094. zone->zone_pgdat->node_id);
  1095. else
  1096. ret = try_to_free_mem_cgroup_pages(victim, gfp_mask,
  1097. noswap, get_swappiness(victim));
  1098. css_put(&victim->css);
  1099. /*
  1100. * At shrinking usage, we can't check we should stop here or
  1101. * reclaim more. It's depends on callers. last_scanned_child
  1102. * will work enough for keeping fairness under tree.
  1103. */
  1104. if (shrink)
  1105. return ret;
  1106. total += ret;
  1107. if (check_soft) {
  1108. if (res_counter_check_under_soft_limit(&root_mem->res))
  1109. return total;
  1110. } else if (mem_cgroup_check_under_limit(root_mem))
  1111. return 1 + total;
  1112. }
  1113. return total;
  1114. }
  1115. static int mem_cgroup_oom_lock_cb(struct mem_cgroup *mem, void *data)
  1116. {
  1117. int *val = (int *)data;
  1118. int x;
  1119. /*
  1120. * Logically, we can stop scanning immediately when we find
  1121. * a memcg is already locked. But condidering unlock ops and
  1122. * creation/removal of memcg, scan-all is simple operation.
  1123. */
  1124. x = atomic_inc_return(&mem->oom_lock);
  1125. *val = max(x, *val);
  1126. return 0;
  1127. }
  1128. /*
  1129. * Check OOM-Killer is already running under our hierarchy.
  1130. * If someone is running, return false.
  1131. */
  1132. static bool mem_cgroup_oom_lock(struct mem_cgroup *mem)
  1133. {
  1134. int lock_count = 0;
  1135. mem_cgroup_walk_tree(mem, &lock_count, mem_cgroup_oom_lock_cb);
  1136. if (lock_count == 1)
  1137. return true;
  1138. return false;
  1139. }
  1140. static int mem_cgroup_oom_unlock_cb(struct mem_cgroup *mem, void *data)
  1141. {
  1142. /*
  1143. * When a new child is created while the hierarchy is under oom,
  1144. * mem_cgroup_oom_lock() may not be called. We have to use
  1145. * atomic_add_unless() here.
  1146. */
  1147. atomic_add_unless(&mem->oom_lock, -1, 0);
  1148. return 0;
  1149. }
  1150. static void mem_cgroup_oom_unlock(struct mem_cgroup *mem)
  1151. {
  1152. mem_cgroup_walk_tree(mem, NULL, mem_cgroup_oom_unlock_cb);
  1153. }
  1154. static DEFINE_MUTEX(memcg_oom_mutex);
  1155. static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
  1156. struct oom_wait_info {
  1157. struct mem_cgroup *mem;
  1158. wait_queue_t wait;
  1159. };
  1160. static int memcg_oom_wake_function(wait_queue_t *wait,
  1161. unsigned mode, int sync, void *arg)
  1162. {
  1163. struct mem_cgroup *wake_mem = (struct mem_cgroup *)arg;
  1164. struct oom_wait_info *oom_wait_info;
  1165. oom_wait_info = container_of(wait, struct oom_wait_info, wait);
  1166. if (oom_wait_info->mem == wake_mem)
  1167. goto wakeup;
  1168. /* if no hierarchy, no match */
  1169. if (!oom_wait_info->mem->use_hierarchy || !wake_mem->use_hierarchy)
  1170. return 0;
  1171. /*
  1172. * Both of oom_wait_info->mem and wake_mem are stable under us.
  1173. * Then we can use css_is_ancestor without taking care of RCU.
  1174. */
  1175. if (!css_is_ancestor(&oom_wait_info->mem->css, &wake_mem->css) &&
  1176. !css_is_ancestor(&wake_mem->css, &oom_wait_info->mem->css))
  1177. return 0;
  1178. wakeup:
  1179. return autoremove_wake_function(wait, mode, sync, arg);
  1180. }
  1181. static void memcg_wakeup_oom(struct mem_cgroup *mem)
  1182. {
  1183. /* for filtering, pass "mem" as argument. */
  1184. __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, mem);
  1185. }
  1186. static void memcg_oom_recover(struct mem_cgroup *mem)
  1187. {
  1188. if (atomic_read(&mem->oom_lock))
  1189. memcg_wakeup_oom(mem);
  1190. }
  1191. /*
  1192. * try to call OOM killer. returns false if we should exit memory-reclaim loop.
  1193. */
  1194. bool mem_cgroup_handle_oom(struct mem_cgroup *mem, gfp_t mask)
  1195. {
  1196. struct oom_wait_info owait;
  1197. bool locked, need_to_kill;
  1198. owait.mem = mem;
  1199. owait.wait.flags = 0;
  1200. owait.wait.func = memcg_oom_wake_function;
  1201. owait.wait.private = current;
  1202. INIT_LIST_HEAD(&owait.wait.task_list);
  1203. need_to_kill = true;
  1204. /* At first, try to OOM lock hierarchy under mem.*/
  1205. mutex_lock(&memcg_oom_mutex);
  1206. locked = mem_cgroup_oom_lock(mem);
  1207. /*
  1208. * Even if signal_pending(), we can't quit charge() loop without
  1209. * accounting. So, UNINTERRUPTIBLE is appropriate. But SIGKILL
  1210. * under OOM is always welcomed, use TASK_KILLABLE here.
  1211. */
  1212. prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
  1213. if (!locked || mem->oom_kill_disable)
  1214. need_to_kill = false;
  1215. if (locked)
  1216. mem_cgroup_oom_notify(mem);
  1217. mutex_unlock(&memcg_oom_mutex);
  1218. if (need_to_kill) {
  1219. finish_wait(&memcg_oom_waitq, &owait.wait);
  1220. mem_cgroup_out_of_memory(mem, mask);
  1221. } else {
  1222. schedule();
  1223. finish_wait(&memcg_oom_waitq, &owait.wait);
  1224. }
  1225. mutex_lock(&memcg_oom_mutex);
  1226. mem_cgroup_oom_unlock(mem);
  1227. memcg_wakeup_oom(mem);
  1228. mutex_unlock(&memcg_oom_mutex);
  1229. if (test_thread_flag(TIF_MEMDIE) || fatal_signal_pending(current))
  1230. return false;
  1231. /* Give chance to dying process */
  1232. schedule_timeout(1);
  1233. return true;
  1234. }
  1235. /*
  1236. * Currently used to update mapped file statistics, but the routine can be
  1237. * generalized to update other statistics as well.
  1238. */
  1239. void mem_cgroup_update_file_mapped(struct page *page, int val)
  1240. {
  1241. struct mem_cgroup *mem;
  1242. struct page_cgroup *pc;
  1243. pc = lookup_page_cgroup(page);
  1244. if (unlikely(!pc))
  1245. return;
  1246. lock_page_cgroup(pc);
  1247. mem = pc->mem_cgroup;
  1248. if (!mem || !PageCgroupUsed(pc))
  1249. goto done;
  1250. /*
  1251. * Preemption is already disabled. We can use __this_cpu_xxx
  1252. */
  1253. if (val > 0) {
  1254. __this_cpu_inc(mem->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
  1255. SetPageCgroupFileMapped(pc);
  1256. } else {
  1257. __this_cpu_dec(mem->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
  1258. ClearPageCgroupFileMapped(pc);
  1259. }
  1260. done:
  1261. unlock_page_cgroup(pc);
  1262. }
  1263. /*
  1264. * size of first charge trial. "32" comes from vmscan.c's magic value.
  1265. * TODO: maybe necessary to use big numbers in big irons.
  1266. */
  1267. #define CHARGE_SIZE (32 * PAGE_SIZE)
  1268. struct memcg_stock_pcp {
  1269. struct mem_cgroup *cached; /* this never be root cgroup */
  1270. int charge;
  1271. struct work_struct work;
  1272. };
  1273. static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
  1274. static atomic_t memcg_drain_count;
  1275. /*
  1276. * Try to consume stocked charge on this cpu. If success, PAGE_SIZE is consumed
  1277. * from local stock and true is returned. If the stock is 0 or charges from a
  1278. * cgroup which is not current target, returns false. This stock will be
  1279. * refilled.
  1280. */
  1281. static bool consume_stock(struct mem_cgroup *mem)
  1282. {
  1283. struct memcg_stock_pcp *stock;
  1284. bool ret = true;
  1285. stock = &get_cpu_var(memcg_stock);
  1286. if (mem == stock->cached && stock->charge)
  1287. stock->charge -= PAGE_SIZE;
  1288. else /* need to call res_counter_charge */
  1289. ret = false;
  1290. put_cpu_var(memcg_stock);
  1291. return ret;
  1292. }
  1293. /*
  1294. * Returns stocks cached in percpu to res_counter and reset cached information.
  1295. */
  1296. static void drain_stock(struct memcg_stock_pcp *stock)
  1297. {
  1298. struct mem_cgroup *old = stock->cached;
  1299. if (stock->charge) {
  1300. res_counter_uncharge(&old->res, stock->charge);
  1301. if (do_swap_account)
  1302. res_counter_uncharge(&old->memsw, stock->charge);
  1303. }
  1304. stock->cached = NULL;
  1305. stock->charge = 0;
  1306. }
  1307. /*
  1308. * This must be called under preempt disabled or must be called by
  1309. * a thread which is pinned to local cpu.
  1310. */
  1311. static void drain_local_stock(struct work_struct *dummy)
  1312. {
  1313. struct memcg_stock_pcp *stock = &__get_cpu_var(memcg_stock);
  1314. drain_stock(stock);
  1315. }
  1316. /*
  1317. * Cache charges(val) which is from res_counter, to local per_cpu area.
  1318. * This will be consumed by consume_stock() function, later.
  1319. */
  1320. static void refill_stock(struct mem_cgroup *mem, int val)
  1321. {
  1322. struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock);
  1323. if (stock->cached != mem) { /* reset if necessary */
  1324. drain_stock(stock);
  1325. stock->cached = mem;
  1326. }
  1327. stock->charge += val;
  1328. put_cpu_var(memcg_stock);
  1329. }
  1330. /*
  1331. * Tries to drain stocked charges in other cpus. This function is asynchronous
  1332. * and just put a work per cpu for draining localy on each cpu. Caller can
  1333. * expects some charges will be back to res_counter later but cannot wait for
  1334. * it.
  1335. */
  1336. static void drain_all_stock_async(void)
  1337. {
  1338. int cpu;
  1339. /* This function is for scheduling "drain" in asynchronous way.
  1340. * The result of "drain" is not directly handled by callers. Then,
  1341. * if someone is calling drain, we don't have to call drain more.
  1342. * Anyway, WORK_STRUCT_PENDING check in queue_work_on() will catch if
  1343. * there is a race. We just do loose check here.
  1344. */
  1345. if (atomic_read(&memcg_drain_count))
  1346. return;
  1347. /* Notify other cpus that system-wide "drain" is running */
  1348. atomic_inc(&memcg_drain_count);
  1349. get_online_cpus();
  1350. for_each_online_cpu(cpu) {
  1351. struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
  1352. schedule_work_on(cpu, &stock->work);
  1353. }
  1354. put_online_cpus();
  1355. atomic_dec(&memcg_drain_count);
  1356. /* We don't wait for flush_work */
  1357. }
  1358. /* This is a synchronous drain interface. */
  1359. static void drain_all_stock_sync(void)
  1360. {
  1361. /* called when force_empty is called */
  1362. atomic_inc(&memcg_drain_count);
  1363. schedule_on_each_cpu(drain_local_stock);
  1364. atomic_dec(&memcg_drain_count);
  1365. }
  1366. static int __cpuinit memcg_stock_cpu_callback(struct notifier_block *nb,
  1367. unsigned long action,
  1368. void *hcpu)
  1369. {
  1370. int cpu = (unsigned long)hcpu;
  1371. struct memcg_stock_pcp *stock;
  1372. if (action != CPU_DEAD)
  1373. return NOTIFY_OK;
  1374. stock = &per_cpu(memcg_stock, cpu);
  1375. drain_stock(stock);
  1376. return NOTIFY_OK;
  1377. }
  1378. /*
  1379. * Unlike exported interface, "oom" parameter is added. if oom==true,
  1380. * oom-killer can be invoked.
  1381. */
  1382. static int __mem_cgroup_try_charge(struct mm_struct *mm,
  1383. gfp_t gfp_mask, struct mem_cgroup **memcg, bool oom)
  1384. {
  1385. struct mem_cgroup *mem, *mem_over_limit;
  1386. int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
  1387. struct res_counter *fail_res;
  1388. int csize = CHARGE_SIZE;
  1389. /*
  1390. * Unlike gloval-vm's OOM-kill, we're not in memory shortage
  1391. * in system level. So, allow to go ahead dying process in addition to
  1392. * MEMDIE process.
  1393. */
  1394. if (unlikely(test_thread_flag(TIF_MEMDIE)
  1395. || fatal_signal_pending(current)))
  1396. goto bypass;
  1397. /*
  1398. * We always charge the cgroup the mm_struct belongs to.
  1399. * The mm_struct's mem_cgroup changes on task migration if the
  1400. * thread group leader migrates. It's possible that mm is not
  1401. * set, if so charge the init_mm (happens for pagecache usage).
  1402. */
  1403. mem = *memcg;
  1404. if (likely(!mem)) {
  1405. mem = try_get_mem_cgroup_from_mm(mm);
  1406. *memcg = mem;
  1407. } else {
  1408. css_get(&mem->css);
  1409. }
  1410. if (unlikely(!mem))
  1411. return 0;
  1412. VM_BUG_ON(css_is_removed(&mem->css));
  1413. if (mem_cgroup_is_root(mem))
  1414. goto done;
  1415. while (1) {
  1416. int ret = 0;
  1417. unsigned long flags = 0;
  1418. if (consume_stock(mem))
  1419. goto done;
  1420. ret = res_counter_charge(&mem->res, csize, &fail_res);
  1421. if (likely(!ret)) {
  1422. if (!do_swap_account)
  1423. break;
  1424. ret = res_counter_charge(&mem->memsw, csize, &fail_res);
  1425. if (likely(!ret))
  1426. break;
  1427. /* mem+swap counter fails */
  1428. res_counter_uncharge(&mem->res, csize);
  1429. flags |= MEM_CGROUP_RECLAIM_NOSWAP;
  1430. mem_over_limit = mem_cgroup_from_res_counter(fail_res,
  1431. memsw);
  1432. } else
  1433. /* mem counter fails */
  1434. mem_over_limit = mem_cgroup_from_res_counter(fail_res,
  1435. res);
  1436. /* reduce request size and retry */
  1437. if (csize > PAGE_SIZE) {
  1438. csize = PAGE_SIZE;
  1439. continue;
  1440. }
  1441. if (!(gfp_mask & __GFP_WAIT))
  1442. goto nomem;
  1443. ret = mem_cgroup_hierarchical_reclaim(mem_over_limit, NULL,
  1444. gfp_mask, flags);
  1445. if (ret)
  1446. continue;
  1447. /*
  1448. * try_to_free_mem_cgroup_pages() might not give us a full
  1449. * picture of reclaim. Some pages are reclaimed and might be
  1450. * moved to swap cache or just unmapped from the cgroup.
  1451. * Check the limit again to see if the reclaim reduced the
  1452. * current usage of the cgroup before giving up
  1453. *
  1454. */
  1455. if (mem_cgroup_check_under_limit(mem_over_limit))
  1456. continue;
  1457. /* try to avoid oom while someone is moving charge */
  1458. if (mc.moving_task && current != mc.moving_task) {
  1459. struct mem_cgroup *from, *to;
  1460. bool do_continue = false;
  1461. /*
  1462. * There is a small race that "from" or "to" can be
  1463. * freed by rmdir, so we use css_tryget().
  1464. */
  1465. from = mc.from;
  1466. to = mc.to;
  1467. if (from && css_tryget(&from->css)) {
  1468. if (mem_over_limit->use_hierarchy)
  1469. do_continue = css_is_ancestor(
  1470. &from->css,
  1471. &mem_over_limit->css);
  1472. else
  1473. do_continue = (from == mem_over_limit);
  1474. css_put(&from->css);
  1475. }
  1476. if (!do_continue && to && css_tryget(&to->css)) {
  1477. if (mem_over_limit->use_hierarchy)
  1478. do_continue = css_is_ancestor(
  1479. &to->css,
  1480. &mem_over_limit->css);
  1481. else
  1482. do_continue = (to == mem_over_limit);
  1483. css_put(&to->css);
  1484. }
  1485. if (do_continue) {
  1486. DEFINE_WAIT(wait);
  1487. prepare_to_wait(&mc.waitq, &wait,
  1488. TASK_INTERRUPTIBLE);
  1489. /* moving charge context might have finished. */
  1490. if (mc.moving_task)
  1491. schedule();
  1492. finish_wait(&mc.waitq, &wait);
  1493. continue;
  1494. }
  1495. }
  1496. if (!nr_retries--) {
  1497. if (!oom)
  1498. goto nomem;
  1499. if (mem_cgroup_handle_oom(mem_over_limit, gfp_mask)) {
  1500. nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
  1501. continue;
  1502. }
  1503. /* When we reach here, current task is dying .*/
  1504. css_put(&mem->css);
  1505. goto bypass;
  1506. }
  1507. }
  1508. if (csize > PAGE_SIZE)
  1509. refill_stock(mem, csize - PAGE_SIZE);
  1510. done:
  1511. return 0;
  1512. nomem:
  1513. css_put(&mem->css);
  1514. return -ENOMEM;
  1515. bypass:
  1516. *memcg = NULL;
  1517. return 0;
  1518. }
  1519. /*
  1520. * Somemtimes we have to undo a charge we got by try_charge().
  1521. * This function is for that and do uncharge, put css's refcnt.
  1522. * gotten by try_charge().
  1523. */
  1524. static void __mem_cgroup_cancel_charge(struct mem_cgroup *mem,
  1525. unsigned long count)
  1526. {
  1527. if (!mem_cgroup_is_root(mem)) {
  1528. res_counter_uncharge(&mem->res, PAGE_SIZE * count);
  1529. if (do_swap_account)
  1530. res_counter_uncharge(&mem->memsw, PAGE_SIZE * count);
  1531. VM_BUG_ON(test_bit(CSS_ROOT, &mem->css.flags));
  1532. WARN_ON_ONCE(count > INT_MAX);
  1533. __css_put(&mem->css, (int)count);
  1534. }
  1535. /* we don't need css_put for root */
  1536. }
  1537. static void mem_cgroup_cancel_charge(struct mem_cgroup *mem)
  1538. {
  1539. __mem_cgroup_cancel_charge(mem, 1);
  1540. }
  1541. /*
  1542. * A helper function to get mem_cgroup from ID. must be called under
  1543. * rcu_read_lock(). The caller must check css_is_removed() or some if
  1544. * it's concern. (dropping refcnt from swap can be called against removed
  1545. * memcg.)
  1546. */
  1547. static struct mem_cgroup *mem_cgroup_lookup(unsigned short id)
  1548. {
  1549. struct cgroup_subsys_state *css;
  1550. /* ID 0 is unused ID */
  1551. if (!id)
  1552. return NULL;
  1553. css = css_lookup(&mem_cgroup_subsys, id);
  1554. if (!css)
  1555. return NULL;
  1556. return container_of(css, struct mem_cgroup, css);
  1557. }
  1558. struct mem_cgroup *try_get_mem_cgroup_from_page(struct page *page)
  1559. {
  1560. struct mem_cgroup *mem = NULL;
  1561. struct page_cgroup *pc;
  1562. unsigned short id;
  1563. swp_entry_t ent;
  1564. VM_BUG_ON(!PageLocked(page));
  1565. pc = lookup_page_cgroup(page);
  1566. lock_page_cgroup(pc);
  1567. if (PageCgroupUsed(pc)) {
  1568. mem = pc->mem_cgroup;
  1569. if (mem && !css_tryget(&mem->css))
  1570. mem = NULL;
  1571. } else if (PageSwapCache(page)) {
  1572. ent.val = page_private(page);
  1573. id = lookup_swap_cgroup(ent);
  1574. rcu_read_lock();
  1575. mem = mem_cgroup_lookup(id);
  1576. if (mem && !css_tryget(&mem->css))
  1577. mem = NULL;
  1578. rcu_read_unlock();
  1579. }
  1580. unlock_page_cgroup(pc);
  1581. return mem;
  1582. }
  1583. /*
  1584. * commit a charge got by __mem_cgroup_try_charge() and makes page_cgroup to be
  1585. * USED state. If already USED, uncharge and return.
  1586. */
  1587. static void __mem_cgroup_commit_charge(struct mem_cgroup *mem,
  1588. struct page_cgroup *pc,
  1589. enum charge_type ctype)
  1590. {
  1591. /* try_charge() can return NULL to *memcg, taking care of it. */
  1592. if (!mem)
  1593. return;
  1594. lock_page_cgroup(pc);
  1595. if (unlikely(PageCgroupUsed(pc))) {
  1596. unlock_page_cgroup(pc);
  1597. mem_cgroup_cancel_charge(mem);
  1598. return;
  1599. }
  1600. pc->mem_cgroup = mem;
  1601. /*
  1602. * We access a page_cgroup asynchronously without lock_page_cgroup().
  1603. * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
  1604. * is accessed after testing USED bit. To make pc->mem_cgroup visible
  1605. * before USED bit, we need memory barrier here.
  1606. * See mem_cgroup_add_lru_list(), etc.
  1607. */
  1608. smp_wmb();
  1609. switch (ctype) {
  1610. case MEM_CGROUP_CHARGE_TYPE_CACHE:
  1611. case MEM_CGROUP_CHARGE_TYPE_SHMEM:
  1612. SetPageCgroupCache(pc);
  1613. SetPageCgroupUsed(pc);
  1614. break;
  1615. case MEM_CGROUP_CHARGE_TYPE_MAPPED:
  1616. ClearPageCgroupCache(pc);
  1617. SetPageCgroupUsed(pc);
  1618. break;
  1619. default:
  1620. break;
  1621. }
  1622. mem_cgroup_charge_statistics(mem, pc, true);
  1623. unlock_page_cgroup(pc);
  1624. /*
  1625. * "charge_statistics" updated event counter. Then, check it.
  1626. * Insert ancestor (and ancestor's ancestors), to softlimit RB-tree.
  1627. * if they exceeds softlimit.
  1628. */
  1629. memcg_check_events(mem, pc->page);
  1630. }
  1631. /**
  1632. * __mem_cgroup_move_account - move account of the page
  1633. * @pc: page_cgroup of the page.
  1634. * @from: mem_cgroup which the page is moved from.
  1635. * @to: mem_cgroup which the page is moved to. @from != @to.
  1636. * @uncharge: whether we should call uncharge and css_put against @from.
  1637. *
  1638. * The caller must confirm following.
  1639. * - page is not on LRU (isolate_page() is useful.)
  1640. * - the pc is locked, used, and ->mem_cgroup points to @from.
  1641. *
  1642. * This function doesn't do "charge" nor css_get to new cgroup. It should be
  1643. * done by a caller(__mem_cgroup_try_charge would be usefull). If @uncharge is
  1644. * true, this function does "uncharge" from old cgroup, but it doesn't if
  1645. * @uncharge is false, so a caller should do "uncharge".
  1646. */
  1647. static void __mem_cgroup_move_account(struct page_cgroup *pc,
  1648. struct mem_cgroup *from, struct mem_cgroup *to, bool uncharge)
  1649. {
  1650. VM_BUG_ON(from == to);
  1651. VM_BUG_ON(PageLRU(pc->page));
  1652. VM_BUG_ON(!PageCgroupLocked(pc));
  1653. VM_BUG_ON(!PageCgroupUsed(pc));
  1654. VM_BUG_ON(pc->mem_cgroup != from);
  1655. if (PageCgroupFileMapped(pc)) {
  1656. /* Update mapped_file data for mem_cgroup */
  1657. preempt_disable();
  1658. __this_cpu_dec(from->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
  1659. __this_cpu_inc(to->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
  1660. preempt_enable();
  1661. }
  1662. mem_cgroup_charge_statistics(from, pc, false);
  1663. if (uncharge)
  1664. /* This is not "cancel", but cancel_charge does all we need. */
  1665. mem_cgroup_cancel_charge(from);
  1666. /* caller should have done css_get */
  1667. pc->mem_cgroup = to;
  1668. mem_cgroup_charge_statistics(to, pc, true);
  1669. /*
  1670. * We charges against "to" which may not have any tasks. Then, "to"
  1671. * can be under rmdir(). But in current implementation, caller of
  1672. * this function is just force_empty() and move charge, so it's
  1673. * garanteed that "to" is never removed. So, we don't check rmdir
  1674. * status here.
  1675. */
  1676. }
  1677. /*
  1678. * check whether the @pc is valid for moving account and call
  1679. * __mem_cgroup_move_account()
  1680. */
  1681. static int mem_cgroup_move_account(struct page_cgroup *pc,
  1682. struct mem_cgroup *from, struct mem_cgroup *to, bool uncharge)
  1683. {
  1684. int ret = -EINVAL;
  1685. lock_page_cgroup(pc);
  1686. if (PageCgroupUsed(pc) && pc->mem_cgroup == from) {
  1687. __mem_cgroup_move_account(pc, from, to, uncharge);
  1688. ret = 0;
  1689. }
  1690. unlock_page_cgroup(pc);
  1691. /*
  1692. * check events
  1693. */
  1694. memcg_check_events(to, pc->page);
  1695. memcg_check_events(from, pc->page);
  1696. return ret;
  1697. }
  1698. /*
  1699. * move charges to its parent.
  1700. */
  1701. static int mem_cgroup_move_parent(struct page_cgroup *pc,
  1702. struct mem_cgroup *child,
  1703. gfp_t gfp_mask)
  1704. {
  1705. struct page *page = pc->page;
  1706. struct cgroup *cg = child->css.cgroup;
  1707. struct cgroup *pcg = cg->parent;
  1708. struct mem_cgroup *parent;
  1709. int ret;
  1710. /* Is ROOT ? */
  1711. if (!pcg)
  1712. return -EINVAL;
  1713. ret = -EBUSY;
  1714. if (!get_page_unless_zero(page))
  1715. goto out;
  1716. if (isolate_lru_page(page))
  1717. goto put;
  1718. parent = mem_cgroup_from_cont(pcg);
  1719. ret = __mem_cgroup_try_charge(NULL, gfp_mask, &parent, false);
  1720. if (ret || !parent)
  1721. goto put_back;
  1722. ret = mem_cgroup_move_account(pc, child, parent, true);
  1723. if (ret)
  1724. mem_cgroup_cancel_charge(parent);
  1725. put_back:
  1726. putback_lru_page(page);
  1727. put:
  1728. put_page(page);
  1729. out:
  1730. return ret;
  1731. }
  1732. /*
  1733. * Charge the memory controller for page usage.
  1734. * Return
  1735. * 0 if the charge was successful
  1736. * < 0 if the cgroup is over its limit
  1737. */
  1738. static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
  1739. gfp_t gfp_mask, enum charge_type ctype,
  1740. struct mem_cgroup *memcg)
  1741. {
  1742. struct mem_cgroup *mem;
  1743. struct page_cgroup *pc;
  1744. int ret;
  1745. pc = lookup_page_cgroup(page);
  1746. /* can happen at boot */
  1747. if (unlikely(!pc))
  1748. return 0;
  1749. prefetchw(pc);
  1750. mem = memcg;
  1751. ret = __mem_cgroup_try_charge(mm, gfp_mask, &mem, true);
  1752. if (ret || !mem)
  1753. return ret;
  1754. __mem_cgroup_commit_charge(mem, pc, ctype);
  1755. return 0;
  1756. }
  1757. int mem_cgroup_newpage_charge(struct page *page,
  1758. struct mm_struct *mm, gfp_t gfp_mask)
  1759. {
  1760. if (mem_cgroup_disabled())
  1761. return 0;
  1762. if (PageCompound(page))
  1763. return 0;
  1764. /*
  1765. * If already mapped, we don't have to account.
  1766. * If page cache, page->mapping has address_space.
  1767. * But page->mapping may have out-of-use anon_vma pointer,
  1768. * detecit it by PageAnon() check. newly-mapped-anon's page->mapping
  1769. * is NULL.
  1770. */
  1771. if (page_mapped(page) || (page->mapping && !PageAnon(page)))
  1772. return 0;
  1773. if (unlikely(!mm))
  1774. mm = &init_mm;
  1775. return mem_cgroup_charge_common(page, mm, gfp_mask,
  1776. MEM_CGROUP_CHARGE_TYPE_MAPPED, NULL);
  1777. }
  1778. static void
  1779. __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
  1780. enum charge_type ctype);
  1781. int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
  1782. gfp_t gfp_mask)
  1783. {
  1784. struct mem_cgroup *mem = NULL;
  1785. int ret;
  1786. if (mem_cgroup_disabled())
  1787. return 0;
  1788. if (PageCompound(page))
  1789. return 0;
  1790. /*
  1791. * Corner case handling. This is called from add_to_page_cache()
  1792. * in usual. But some FS (shmem) precharges this page before calling it
  1793. * and call add_to_page_cache() with GFP_NOWAIT.
  1794. *
  1795. * For GFP_NOWAIT case, the page may be pre-charged before calling
  1796. * add_to_page_cache(). (See shmem.c) check it here and avoid to call
  1797. * charge twice. (It works but has to pay a bit larger cost.)
  1798. * And when the page is SwapCache, it should take swap information
  1799. * into account. This is under lock_page() now.
  1800. */
  1801. if (!(gfp_mask & __GFP_WAIT)) {
  1802. struct page_cgroup *pc;
  1803. pc = lookup_page_cgroup(page);
  1804. if (!pc)
  1805. return 0;
  1806. lock_page_cgroup(pc);
  1807. if (PageCgroupUsed(pc)) {
  1808. unlock_page_cgroup(pc);
  1809. return 0;
  1810. }
  1811. unlock_page_cgroup(pc);
  1812. }
  1813. if (unlikely(!mm && !mem))
  1814. mm = &init_mm;
  1815. if (page_is_file_cache(page))
  1816. return mem_cgroup_charge_common(page, mm, gfp_mask,
  1817. MEM_CGROUP_CHARGE_TYPE_CACHE, NULL);
  1818. /* shmem */
  1819. if (PageSwapCache(page)) {
  1820. ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &mem);
  1821. if (!ret)
  1822. __mem_cgroup_commit_charge_swapin(page, mem,
  1823. MEM_CGROUP_CHARGE_TYPE_SHMEM);
  1824. } else
  1825. ret = mem_cgroup_charge_common(page, mm, gfp_mask,
  1826. MEM_CGROUP_CHARGE_TYPE_SHMEM, mem);
  1827. return ret;
  1828. }
  1829. /*
  1830. * While swap-in, try_charge -> commit or cancel, the page is locked.
  1831. * And when try_charge() successfully returns, one refcnt to memcg without
  1832. * struct page_cgroup is acquired. This refcnt will be consumed by
  1833. * "commit()" or removed by "cancel()"
  1834. */
  1835. int mem_cgroup_try_charge_swapin(struct mm_struct *mm,
  1836. struct page *page,
  1837. gfp_t mask, struct mem_cgroup **ptr)
  1838. {
  1839. struct mem_cgroup *mem;
  1840. int ret;
  1841. if (mem_cgroup_disabled())
  1842. return 0;
  1843. if (!do_swap_account)
  1844. goto charge_cur_mm;
  1845. /*
  1846. * A racing thread's fault, or swapoff, may have already updated
  1847. * the pte, and even removed page from swap cache: in those cases
  1848. * do_swap_page()'s pte_same() test will fail; but there's also a
  1849. * KSM case which does need to charge the page.
  1850. */
  1851. if (!PageSwapCache(page))
  1852. goto charge_cur_mm;
  1853. mem = try_get_mem_cgroup_from_page(page);
  1854. if (!mem)
  1855. goto charge_cur_mm;
  1856. *ptr = mem;
  1857. ret = __mem_cgroup_try_charge(NULL, mask, ptr, true);
  1858. /* drop extra refcnt from tryget */
  1859. css_put(&mem->css);
  1860. return ret;
  1861. charge_cur_mm:
  1862. if (unlikely(!mm))
  1863. mm = &init_mm;
  1864. return __mem_cgroup_try_charge(mm, mask, ptr, true);
  1865. }
  1866. static void
  1867. __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
  1868. enum charge_type ctype)
  1869. {
  1870. struct page_cgroup *pc;
  1871. if (mem_cgroup_disabled())
  1872. return;
  1873. if (!ptr)
  1874. return;
  1875. cgroup_exclude_rmdir(&ptr->css);
  1876. pc = lookup_page_cgroup(page);
  1877. mem_cgroup_lru_del_before_commit_swapcache(page);
  1878. __mem_cgroup_commit_charge(ptr, pc, ctype);
  1879. mem_cgroup_lru_add_after_commit_swapcache(page);
  1880. /*
  1881. * Now swap is on-memory. This means this page may be
  1882. * counted both as mem and swap....double count.
  1883. * Fix it by uncharging from memsw. Basically, this SwapCache is stable
  1884. * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
  1885. * may call delete_from_swap_cache() before reach here.
  1886. */
  1887. if (do_swap_account && PageSwapCache(page)) {
  1888. swp_entry_t ent = {.val = page_private(page)};
  1889. unsigned short id;
  1890. struct mem_cgroup *memcg;
  1891. id = swap_cgroup_record(ent, 0);
  1892. rcu_read_lock();
  1893. memcg = mem_cgroup_lookup(id);
  1894. if (memcg) {
  1895. /*
  1896. * This recorded memcg can be obsolete one. So, avoid
  1897. * calling css_tryget
  1898. */
  1899. if (!mem_cgroup_is_root(memcg))
  1900. res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
  1901. mem_cgroup_swap_statistics(memcg, false);
  1902. mem_cgroup_put(memcg);
  1903. }
  1904. rcu_read_unlock();
  1905. }
  1906. /*
  1907. * At swapin, we may charge account against cgroup which has no tasks.
  1908. * So, rmdir()->pre_destroy() can be called while we do this charge.
  1909. * In that case, we need to call pre_destroy() again. check it here.
  1910. */
  1911. cgroup_release_and_wakeup_rmdir(&ptr->css);
  1912. }
  1913. void mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr)
  1914. {
  1915. __mem_cgroup_commit_charge_swapin(page, ptr,
  1916. MEM_CGROUP_CHARGE_TYPE_MAPPED);
  1917. }
  1918. void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *mem)
  1919. {
  1920. if (mem_cgroup_disabled())
  1921. return;
  1922. if (!mem)
  1923. return;
  1924. mem_cgroup_cancel_charge(mem);
  1925. }
  1926. static void
  1927. __do_uncharge(struct mem_cgroup *mem, const enum charge_type ctype)
  1928. {
  1929. struct memcg_batch_info *batch = NULL;
  1930. bool uncharge_memsw = true;
  1931. /* If swapout, usage of swap doesn't decrease */
  1932. if (!do_swap_account || ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
  1933. uncharge_memsw = false;
  1934. batch = &current->memcg_batch;
  1935. /*
  1936. * In usual, we do css_get() when we remember memcg pointer.
  1937. * But in this case, we keep res->usage until end of a series of
  1938. * uncharges. Then, it's ok to ignore memcg's refcnt.
  1939. */
  1940. if (!batch->memcg)
  1941. batch->memcg = mem;
  1942. /*
  1943. * do_batch > 0 when unmapping pages or inode invalidate/truncate.
  1944. * In those cases, all pages freed continously can be expected to be in
  1945. * the same cgroup and we have chance to coalesce uncharges.
  1946. * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE)
  1947. * because we want to do uncharge as soon as possible.
  1948. */
  1949. if (!batch->do_batch || test_thread_flag(TIF_MEMDIE))
  1950. goto direct_uncharge;
  1951. /*
  1952. * In typical case, batch->memcg == mem. This means we can
  1953. * merge a series of uncharges to an uncharge of res_counter.
  1954. * If not, we uncharge res_counter ony by one.
  1955. */
  1956. if (batch->memcg != mem)
  1957. goto direct_uncharge;
  1958. /* remember freed charge and uncharge it later */
  1959. batch->bytes += PAGE_SIZE;
  1960. if (uncharge_memsw)
  1961. batch->memsw_bytes += PAGE_SIZE;
  1962. return;
  1963. direct_uncharge:
  1964. res_counter_uncharge(&mem->res, PAGE_SIZE);
  1965. if (uncharge_memsw)
  1966. res_counter_uncharge(&mem->memsw, PAGE_SIZE);
  1967. if (unlikely(batch->memcg != mem))
  1968. memcg_oom_recover(mem);
  1969. return;
  1970. }
  1971. /*
  1972. * uncharge if !page_mapped(page)
  1973. */
  1974. static struct mem_cgroup *
  1975. __mem_cgroup_uncharge_common(struct page *page, enum charge_type ctype)
  1976. {
  1977. struct page_cgroup *pc;
  1978. struct mem_cgroup *mem = NULL;
  1979. struct mem_cgroup_per_zone *mz;
  1980. if (mem_cgroup_disabled())
  1981. return NULL;
  1982. if (PageSwapCache(page))
  1983. return NULL;
  1984. /*
  1985. * Check if our page_cgroup is valid
  1986. */
  1987. pc = lookup_page_cgroup(page);
  1988. if (unlikely(!pc || !PageCgroupUsed(pc)))
  1989. return NULL;
  1990. lock_page_cgroup(pc);
  1991. mem = pc->mem_cgroup;
  1992. if (!PageCgroupUsed(pc))
  1993. goto unlock_out;
  1994. switch (ctype) {
  1995. case MEM_CGROUP_CHARGE_TYPE_MAPPED:
  1996. case MEM_CGROUP_CHARGE_TYPE_DROP:
  1997. /* See mem_cgroup_prepare_migration() */
  1998. if (page_mapped(page) || PageCgroupMigration(pc))
  1999. goto unlock_out;
  2000. break;
  2001. case MEM_CGROUP_CHARGE_TYPE_SWAPOUT:
  2002. if (!PageAnon(page)) { /* Shared memory */
  2003. if (page->mapping && !page_is_file_cache(page))
  2004. goto unlock_out;
  2005. } else if (page_mapped(page)) /* Anon */
  2006. goto unlock_out;
  2007. break;
  2008. default:
  2009. break;
  2010. }
  2011. if (!mem_cgroup_is_root(mem))
  2012. __do_uncharge(mem, ctype);
  2013. if (ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
  2014. mem_cgroup_swap_statistics(mem, true);
  2015. mem_cgroup_charge_statistics(mem, pc, false);
  2016. ClearPageCgroupUsed(pc);
  2017. /*
  2018. * pc->mem_cgroup is not cleared here. It will be accessed when it's
  2019. * freed from LRU. This is safe because uncharged page is expected not
  2020. * to be reused (freed soon). Exception is SwapCache, it's handled by
  2021. * special functions.
  2022. */
  2023. mz = page_cgroup_zoneinfo(pc);
  2024. unlock_page_cgroup(pc);
  2025. memcg_check_events(mem, page);
  2026. /* at swapout, this memcg will be accessed to record to swap */
  2027. if (ctype != MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
  2028. css_put(&mem->css);
  2029. return mem;
  2030. unlock_out:
  2031. unlock_page_cgroup(pc);
  2032. return NULL;
  2033. }
  2034. void mem_cgroup_uncharge_page(struct page *page)
  2035. {
  2036. /* early check. */
  2037. if (page_mapped(page))
  2038. return;
  2039. if (page->mapping && !PageAnon(page))
  2040. return;
  2041. __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_MAPPED);
  2042. }
  2043. void mem_cgroup_uncharge_cache_page(struct page *page)
  2044. {
  2045. VM_BUG_ON(page_mapped(page));
  2046. VM_BUG_ON(page->mapping);
  2047. __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_CACHE);
  2048. }
  2049. /*
  2050. * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate.
  2051. * In that cases, pages are freed continuously and we can expect pages
  2052. * are in the same memcg. All these calls itself limits the number of
  2053. * pages freed at once, then uncharge_start/end() is called properly.
  2054. * This may be called prural(2) times in a context,
  2055. */
  2056. void mem_cgroup_uncharge_start(void)
  2057. {
  2058. current->memcg_batch.do_batch++;
  2059. /* We can do nest. */
  2060. if (current->memcg_batch.do_batch == 1) {
  2061. current->memcg_batch.memcg = NULL;
  2062. current->memcg_batch.bytes = 0;
  2063. current->memcg_batch.memsw_bytes = 0;
  2064. }
  2065. }
  2066. void mem_cgroup_uncharge_end(void)
  2067. {
  2068. struct memcg_batch_info *batch = &current->memcg_batch;
  2069. if (!batch->do_batch)
  2070. return;
  2071. batch->do_batch--;
  2072. if (batch->do_batch) /* If stacked, do nothing. */
  2073. return;
  2074. if (!batch->memcg)
  2075. return;
  2076. /*
  2077. * This "batch->memcg" is valid without any css_get/put etc...
  2078. * bacause we hide charges behind us.
  2079. */
  2080. if (batch->bytes)
  2081. res_counter_uncharge(&batch->memcg->res, batch->bytes);
  2082. if (batch->memsw_bytes)
  2083. res_counter_uncharge(&batch->memcg->memsw, batch->memsw_bytes);
  2084. memcg_oom_recover(batch->memcg);
  2085. /* forget this pointer (for sanity check) */
  2086. batch->memcg = NULL;
  2087. }
  2088. #ifdef CONFIG_SWAP
  2089. /*
  2090. * called after __delete_from_swap_cache() and drop "page" account.
  2091. * memcg information is recorded to swap_cgroup of "ent"
  2092. */
  2093. void
  2094. mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout)
  2095. {
  2096. struct mem_cgroup *memcg;
  2097. int ctype = MEM_CGROUP_CHARGE_TYPE_SWAPOUT;
  2098. if (!swapout) /* this was a swap cache but the swap is unused ! */
  2099. ctype = MEM_CGROUP_CHARGE_TYPE_DROP;
  2100. memcg = __mem_cgroup_uncharge_common(page, ctype);
  2101. /* record memcg information */
  2102. if (do_swap_account && swapout && memcg) {
  2103. swap_cgroup_record(ent, css_id(&memcg->css));
  2104. mem_cgroup_get(memcg);
  2105. }
  2106. if (swapout && memcg)
  2107. css_put(&memcg->css);
  2108. }
  2109. #endif
  2110. #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
  2111. /*
  2112. * called from swap_entry_free(). remove record in swap_cgroup and
  2113. * uncharge "memsw" account.
  2114. */
  2115. void mem_cgroup_uncharge_swap(swp_entry_t ent)
  2116. {
  2117. struct mem_cgroup *memcg;
  2118. unsigned short id;
  2119. if (!do_swap_account)
  2120. return;
  2121. id = swap_cgroup_record(ent, 0);
  2122. rcu_read_lock();
  2123. memcg = mem_cgroup_lookup(id);
  2124. if (memcg) {
  2125. /*
  2126. * We uncharge this because swap is freed.
  2127. * This memcg can be obsolete one. We avoid calling css_tryget
  2128. */
  2129. if (!mem_cgroup_is_root(memcg))
  2130. res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
  2131. mem_cgroup_swap_statistics(memcg, false);
  2132. mem_cgroup_put(memcg);
  2133. }
  2134. rcu_read_unlock();
  2135. }
  2136. /**
  2137. * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
  2138. * @entry: swap entry to be moved
  2139. * @from: mem_cgroup which the entry is moved from
  2140. * @to: mem_cgroup which the entry is moved to
  2141. * @need_fixup: whether we should fixup res_counters and refcounts.
  2142. *
  2143. * It succeeds only when the swap_cgroup's record for this entry is the same
  2144. * as the mem_cgroup's id of @from.
  2145. *
  2146. * Returns 0 on success, -EINVAL on failure.
  2147. *
  2148. * The caller must have charged to @to, IOW, called res_counter_charge() about
  2149. * both res and memsw, and called css_get().
  2150. */
  2151. static int mem_cgroup_move_swap_account(swp_entry_t entry,
  2152. struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
  2153. {
  2154. unsigned short old_id, new_id;
  2155. old_id = css_id(&from->css);
  2156. new_id = css_id(&to->css);
  2157. if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
  2158. mem_cgroup_swap_statistics(from, false);
  2159. mem_cgroup_swap_statistics(to, true);
  2160. /*
  2161. * This function is only called from task migration context now.
  2162. * It postpones res_counter and refcount handling till the end
  2163. * of task migration(mem_cgroup_clear_mc()) for performance
  2164. * improvement. But we cannot postpone mem_cgroup_get(to)
  2165. * because if the process that has been moved to @to does
  2166. * swap-in, the refcount of @to might be decreased to 0.
  2167. */
  2168. mem_cgroup_get(to);
  2169. if (need_fixup) {
  2170. if (!mem_cgroup_is_root(from))
  2171. res_counter_uncharge(&from->memsw, PAGE_SIZE);
  2172. mem_cgroup_put(from);
  2173. /*
  2174. * we charged both to->res and to->memsw, so we should
  2175. * uncharge to->res.
  2176. */
  2177. if (!mem_cgroup_is_root(to))
  2178. res_counter_uncharge(&to->res, PAGE_SIZE);
  2179. css_put(&to->css);
  2180. }
  2181. return 0;
  2182. }
  2183. return -EINVAL;
  2184. }
  2185. #else
  2186. static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
  2187. struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
  2188. {
  2189. return -EINVAL;
  2190. }
  2191. #endif
  2192. /*
  2193. * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
  2194. * page belongs to.
  2195. */
  2196. int mem_cgroup_prepare_migration(struct page *page,
  2197. struct page *newpage, struct mem_cgroup **ptr)
  2198. {
  2199. struct page_cgroup *pc;
  2200. struct mem_cgroup *mem = NULL;
  2201. enum charge_type ctype;
  2202. int ret = 0;
  2203. if (mem_cgroup_disabled())
  2204. return 0;
  2205. pc = lookup_page_cgroup(page);
  2206. lock_page_cgroup(pc);
  2207. if (PageCgroupUsed(pc)) {
  2208. mem = pc->mem_cgroup;
  2209. css_get(&mem->css);
  2210. /*
  2211. * At migrating an anonymous page, its mapcount goes down
  2212. * to 0 and uncharge() will be called. But, even if it's fully
  2213. * unmapped, migration may fail and this page has to be
  2214. * charged again. We set MIGRATION flag here and delay uncharge
  2215. * until end_migration() is called
  2216. *
  2217. * Corner Case Thinking
  2218. * A)
  2219. * When the old page was mapped as Anon and it's unmap-and-freed
  2220. * while migration was ongoing.
  2221. * If unmap finds the old page, uncharge() of it will be delayed
  2222. * until end_migration(). If unmap finds a new page, it's
  2223. * uncharged when it make mapcount to be 1->0. If unmap code
  2224. * finds swap_migration_entry, the new page will not be mapped
  2225. * and end_migration() will find it(mapcount==0).
  2226. *
  2227. * B)
  2228. * When the old page was mapped but migraion fails, the kernel
  2229. * remaps it. A charge for it is kept by MIGRATION flag even
  2230. * if mapcount goes down to 0. We can do remap successfully
  2231. * without charging it again.
  2232. *
  2233. * C)
  2234. * The "old" page is under lock_page() until the end of
  2235. * migration, so, the old page itself will not be swapped-out.
  2236. * If the new page is swapped out before end_migraton, our
  2237. * hook to usual swap-out path will catch the event.
  2238. */
  2239. if (PageAnon(page))
  2240. SetPageCgroupMigration(pc);
  2241. }
  2242. unlock_page_cgroup(pc);
  2243. /*
  2244. * If the page is not charged at this point,
  2245. * we return here.
  2246. */
  2247. if (!mem)
  2248. return 0;
  2249. *ptr = mem;
  2250. ret = __mem_cgroup_try_charge(NULL, GFP_KERNEL, ptr, false);
  2251. css_put(&mem->css);/* drop extra refcnt */
  2252. if (ret || *ptr == NULL) {
  2253. if (PageAnon(page)) {
  2254. lock_page_cgroup(pc);
  2255. ClearPageCgroupMigration(pc);
  2256. unlock_page_cgroup(pc);
  2257. /*
  2258. * The old page may be fully unmapped while we kept it.
  2259. */
  2260. mem_cgroup_uncharge_page(page);
  2261. }
  2262. return -ENOMEM;
  2263. }
  2264. /*
  2265. * We charge new page before it's used/mapped. So, even if unlock_page()
  2266. * is called before end_migration, we can catch all events on this new
  2267. * page. In the case new page is migrated but not remapped, new page's
  2268. * mapcount will be finally 0 and we call uncharge in end_migration().
  2269. */
  2270. pc = lookup_page_cgroup(newpage);
  2271. if (PageAnon(page))
  2272. ctype = MEM_CGROUP_CHARGE_TYPE_MAPPED;
  2273. else if (page_is_file_cache(page))
  2274. ctype = MEM_CGROUP_CHARGE_TYPE_CACHE;
  2275. else
  2276. ctype = MEM_CGROUP_CHARGE_TYPE_SHMEM;
  2277. __mem_cgroup_commit_charge(mem, pc, ctype);
  2278. return ret;
  2279. }
  2280. /* remove redundant charge if migration failed*/
  2281. void mem_cgroup_end_migration(struct mem_cgroup *mem,
  2282. struct page *oldpage, struct page *newpage)
  2283. {
  2284. struct page *used, *unused;
  2285. struct page_cgroup *pc;
  2286. if (!mem)
  2287. return;
  2288. /* blocks rmdir() */
  2289. cgroup_exclude_rmdir(&mem->css);
  2290. /* at migration success, oldpage->mapping is NULL. */
  2291. if (oldpage->mapping) {
  2292. used = oldpage;
  2293. unused = newpage;
  2294. } else {
  2295. used = newpage;
  2296. unused = oldpage;
  2297. }
  2298. /*
  2299. * We disallowed uncharge of pages under migration because mapcount
  2300. * of the page goes down to zero, temporarly.
  2301. * Clear the flag and check the page should be charged.
  2302. */
  2303. pc = lookup_page_cgroup(oldpage);
  2304. lock_page_cgroup(pc);
  2305. ClearPageCgroupMigration(pc);
  2306. unlock_page_cgroup(pc);
  2307. if (unused != oldpage)
  2308. pc = lookup_page_cgroup(unused);
  2309. __mem_cgroup_uncharge_common(unused, MEM_CGROUP_CHARGE_TYPE_FORCE);
  2310. pc = lookup_page_cgroup(used);
  2311. /*
  2312. * If a page is a file cache, radix-tree replacement is very atomic
  2313. * and we can skip this check. When it was an Anon page, its mapcount
  2314. * goes down to 0. But because we added MIGRATION flage, it's not
  2315. * uncharged yet. There are several case but page->mapcount check
  2316. * and USED bit check in mem_cgroup_uncharge_page() will do enough
  2317. * check. (see prepare_charge() also)
  2318. */
  2319. if (PageAnon(used))
  2320. mem_cgroup_uncharge_page(used);
  2321. /*
  2322. * At migration, we may charge account against cgroup which has no
  2323. * tasks.
  2324. * So, rmdir()->pre_destroy() can be called while we do this charge.
  2325. * In that case, we need to call pre_destroy() again. check it here.
  2326. */
  2327. cgroup_release_and_wakeup_rmdir(&mem->css);
  2328. }
  2329. /*
  2330. * A call to try to shrink memory usage on charge failure at shmem's swapin.
  2331. * Calling hierarchical_reclaim is not enough because we should update
  2332. * last_oom_jiffies to prevent pagefault_out_of_memory from invoking global OOM.
  2333. * Moreover considering hierarchy, we should reclaim from the mem_over_limit,
  2334. * not from the memcg which this page would be charged to.
  2335. * try_charge_swapin does all of these works properly.
  2336. */
  2337. int mem_cgroup_shmem_charge_fallback(struct page *page,
  2338. struct mm_struct *mm,
  2339. gfp_t gfp_mask)
  2340. {
  2341. struct mem_cgroup *mem = NULL;
  2342. int ret;
  2343. if (mem_cgroup_disabled())
  2344. return 0;
  2345. ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &mem);
  2346. if (!ret)
  2347. mem_cgroup_cancel_charge_swapin(mem); /* it does !mem check */
  2348. return ret;
  2349. }
  2350. static DEFINE_MUTEX(set_limit_mutex);
  2351. static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
  2352. unsigned long long val)
  2353. {
  2354. int retry_count;
  2355. u64 memswlimit, memlimit;
  2356. int ret = 0;
  2357. int children = mem_cgroup_count_children(memcg);
  2358. u64 curusage, oldusage;
  2359. int enlarge;
  2360. /*
  2361. * For keeping hierarchical_reclaim simple, how long we should retry
  2362. * is depends on callers. We set our retry-count to be function
  2363. * of # of children which we should visit in this loop.
  2364. */
  2365. retry_count = MEM_CGROUP_RECLAIM_RETRIES * children;
  2366. oldusage = res_counter_read_u64(&memcg->res, RES_USAGE);
  2367. enlarge = 0;
  2368. while (retry_count) {
  2369. if (signal_pending(current)) {
  2370. ret = -EINTR;
  2371. break;
  2372. }
  2373. /*
  2374. * Rather than hide all in some function, I do this in
  2375. * open coded manner. You see what this really does.
  2376. * We have to guarantee mem->res.limit < mem->memsw.limit.
  2377. */
  2378. mutex_lock(&set_limit_mutex);
  2379. memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
  2380. if (memswlimit < val) {
  2381. ret = -EINVAL;
  2382. mutex_unlock(&set_limit_mutex);
  2383. break;
  2384. }
  2385. memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
  2386. if (memlimit < val)
  2387. enlarge = 1;
  2388. ret = res_counter_set_limit(&memcg->res, val);
  2389. if (!ret) {
  2390. if (memswlimit == val)
  2391. memcg->memsw_is_minimum = true;
  2392. else
  2393. memcg->memsw_is_minimum = false;
  2394. }
  2395. mutex_unlock(&set_limit_mutex);
  2396. if (!ret)
  2397. break;
  2398. mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
  2399. MEM_CGROUP_RECLAIM_SHRINK);
  2400. curusage = res_counter_read_u64(&memcg->res, RES_USAGE);
  2401. /* Usage is reduced ? */
  2402. if (curusage >= oldusage)
  2403. retry_count--;
  2404. else
  2405. oldusage = curusage;
  2406. }
  2407. if (!ret && enlarge)
  2408. memcg_oom_recover(memcg);
  2409. return ret;
  2410. }
  2411. static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
  2412. unsigned long long val)
  2413. {
  2414. int retry_count;
  2415. u64 memlimit, memswlimit, oldusage, curusage;
  2416. int children = mem_cgroup_count_children(memcg);
  2417. int ret = -EBUSY;
  2418. int enlarge = 0;
  2419. /* see mem_cgroup_resize_res_limit */
  2420. retry_count = children * MEM_CGROUP_RECLAIM_RETRIES;
  2421. oldusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
  2422. while (retry_count) {
  2423. if (signal_pending(current)) {
  2424. ret = -EINTR;
  2425. break;
  2426. }
  2427. /*
  2428. * Rather than hide all in some function, I do this in
  2429. * open coded manner. You see what this really does.
  2430. * We have to guarantee mem->res.limit < mem->memsw.limit.
  2431. */
  2432. mutex_lock(&set_limit_mutex);
  2433. memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
  2434. if (memlimit > val) {
  2435. ret = -EINVAL;
  2436. mutex_unlock(&set_limit_mutex);
  2437. break;
  2438. }
  2439. memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
  2440. if (memswlimit < val)
  2441. enlarge = 1;
  2442. ret = res_counter_set_limit(&memcg->memsw, val);
  2443. if (!ret) {
  2444. if (memlimit == val)
  2445. memcg->memsw_is_minimum = true;
  2446. else
  2447. memcg->memsw_is_minimum = false;
  2448. }
  2449. mutex_unlock(&set_limit_mutex);
  2450. if (!ret)
  2451. break;
  2452. mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
  2453. MEM_CGROUP_RECLAIM_NOSWAP |
  2454. MEM_CGROUP_RECLAIM_SHRINK);
  2455. curusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
  2456. /* Usage is reduced ? */
  2457. if (curusage >= oldusage)
  2458. retry_count--;
  2459. else
  2460. oldusage = curusage;
  2461. }
  2462. if (!ret && enlarge)
  2463. memcg_oom_recover(memcg);
  2464. return ret;
  2465. }
  2466. unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
  2467. gfp_t gfp_mask, int nid,
  2468. int zid)
  2469. {
  2470. unsigned long nr_reclaimed = 0;
  2471. struct mem_cgroup_per_zone *mz, *next_mz = NULL;
  2472. unsigned long reclaimed;
  2473. int loop = 0;
  2474. struct mem_cgroup_tree_per_zone *mctz;
  2475. unsigned long long excess;
  2476. if (order > 0)
  2477. return 0;
  2478. mctz = soft_limit_tree_node_zone(nid, zid);
  2479. /*
  2480. * This loop can run a while, specially if mem_cgroup's continuously
  2481. * keep exceeding their soft limit and putting the system under
  2482. * pressure
  2483. */
  2484. do {
  2485. if (next_mz)
  2486. mz = next_mz;
  2487. else
  2488. mz = mem_cgroup_largest_soft_limit_node(mctz);
  2489. if (!mz)
  2490. break;
  2491. reclaimed = mem_cgroup_hierarchical_reclaim(mz->mem, zone,
  2492. gfp_mask,
  2493. MEM_CGROUP_RECLAIM_SOFT);
  2494. nr_reclaimed += reclaimed;
  2495. spin_lock(&mctz->lock);
  2496. /*
  2497. * If we failed to reclaim anything from this memory cgroup
  2498. * it is time to move on to the next cgroup
  2499. */
  2500. next_mz = NULL;
  2501. if (!reclaimed) {
  2502. do {
  2503. /*
  2504. * Loop until we find yet another one.
  2505. *
  2506. * By the time we get the soft_limit lock
  2507. * again, someone might have aded the
  2508. * group back on the RB tree. Iterate to
  2509. * make sure we get a different mem.
  2510. * mem_cgroup_largest_soft_limit_node returns
  2511. * NULL if no other cgroup is present on
  2512. * the tree
  2513. */
  2514. next_mz =
  2515. __mem_cgroup_largest_soft_limit_node(mctz);
  2516. if (next_mz == mz) {
  2517. css_put(&next_mz->mem->css);
  2518. next_mz = NULL;
  2519. } else /* next_mz == NULL or other memcg */
  2520. break;
  2521. } while (1);
  2522. }
  2523. __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
  2524. excess = res_counter_soft_limit_excess(&mz->mem->res);
  2525. /*
  2526. * One school of thought says that we should not add
  2527. * back the node to the tree if reclaim returns 0.
  2528. * But our reclaim could return 0, simply because due
  2529. * to priority we are exposing a smaller subset of
  2530. * memory to reclaim from. Consider this as a longer
  2531. * term TODO.
  2532. */
  2533. /* If excess == 0, no tree ops */
  2534. __mem_cgroup_insert_exceeded(mz->mem, mz, mctz, excess);
  2535. spin_unlock(&mctz->lock);
  2536. css_put(&mz->mem->css);
  2537. loop++;
  2538. /*
  2539. * Could not reclaim anything and there are no more
  2540. * mem cgroups to try or we seem to be looping without
  2541. * reclaiming anything.
  2542. */
  2543. if (!nr_reclaimed &&
  2544. (next_mz == NULL ||
  2545. loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
  2546. break;
  2547. } while (!nr_reclaimed);
  2548. if (next_mz)
  2549. css_put(&next_mz->mem->css);
  2550. return nr_reclaimed;
  2551. }
  2552. /*
  2553. * This routine traverse page_cgroup in given list and drop them all.
  2554. * *And* this routine doesn't reclaim page itself, just removes page_cgroup.
  2555. */
  2556. static int mem_cgroup_force_empty_list(struct mem_cgroup *mem,
  2557. int node, int zid, enum lru_list lru)
  2558. {
  2559. struct zone *zone;
  2560. struct mem_cgroup_per_zone *mz;
  2561. struct page_cgroup *pc, *busy;
  2562. unsigned long flags, loop;
  2563. struct list_head *list;
  2564. int ret = 0;
  2565. zone = &NODE_DATA(node)->node_zones[zid];
  2566. mz = mem_cgroup_zoneinfo(mem, node, zid);
  2567. list = &mz->lists[lru];
  2568. loop = MEM_CGROUP_ZSTAT(mz, lru);
  2569. /* give some margin against EBUSY etc...*/
  2570. loop += 256;
  2571. busy = NULL;
  2572. while (loop--) {
  2573. ret = 0;
  2574. spin_lock_irqsave(&zone->lru_lock, flags);
  2575. if (list_empty(list)) {
  2576. spin_unlock_irqrestore(&zone->lru_lock, flags);
  2577. break;
  2578. }
  2579. pc = list_entry(list->prev, struct page_cgroup, lru);
  2580. if (busy == pc) {
  2581. list_move(&pc->lru, list);
  2582. busy = NULL;
  2583. spin_unlock_irqrestore(&zone->lru_lock, flags);
  2584. continue;
  2585. }
  2586. spin_unlock_irqrestore(&zone->lru_lock, flags);
  2587. ret = mem_cgroup_move_parent(pc, mem, GFP_KERNEL);
  2588. if (ret == -ENOMEM)
  2589. break;
  2590. if (ret == -EBUSY || ret == -EINVAL) {
  2591. /* found lock contention or "pc" is obsolete. */
  2592. busy = pc;
  2593. cond_resched();
  2594. } else
  2595. busy = NULL;
  2596. }
  2597. if (!ret && !list_empty(list))
  2598. return -EBUSY;
  2599. return ret;
  2600. }
  2601. /*
  2602. * make mem_cgroup's charge to be 0 if there is no task.
  2603. * This enables deleting this mem_cgroup.
  2604. */
  2605. static int mem_cgroup_force_empty(struct mem_cgroup *mem, bool free_all)
  2606. {
  2607. int ret;
  2608. int node, zid, shrink;
  2609. int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
  2610. struct cgroup *cgrp = mem->css.cgroup;
  2611. css_get(&mem->css);
  2612. shrink = 0;
  2613. /* should free all ? */
  2614. if (free_all)
  2615. goto try_to_free;
  2616. move_account:
  2617. do {
  2618. ret = -EBUSY;
  2619. if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children))
  2620. goto out;
  2621. ret = -EINTR;
  2622. if (signal_pending(current))
  2623. goto out;
  2624. /* This is for making all *used* pages to be on LRU. */
  2625. lru_add_drain_all();
  2626. drain_all_stock_sync();
  2627. ret = 0;
  2628. for_each_node_state(node, N_HIGH_MEMORY) {
  2629. for (zid = 0; !ret && zid < MAX_NR_ZONES; zid++) {
  2630. enum lru_list l;
  2631. for_each_lru(l) {
  2632. ret = mem_cgroup_force_empty_list(mem,
  2633. node, zid, l);
  2634. if (ret)
  2635. break;
  2636. }
  2637. }
  2638. if (ret)
  2639. break;
  2640. }
  2641. memcg_oom_recover(mem);
  2642. /* it seems parent cgroup doesn't have enough mem */
  2643. if (ret == -ENOMEM)
  2644. goto try_to_free;
  2645. cond_resched();
  2646. /* "ret" should also be checked to ensure all lists are empty. */
  2647. } while (mem->res.usage > 0 || ret);
  2648. out:
  2649. css_put(&mem->css);
  2650. return ret;
  2651. try_to_free:
  2652. /* returns EBUSY if there is a task or if we come here twice. */
  2653. if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children) || shrink) {
  2654. ret = -EBUSY;
  2655. goto out;
  2656. }
  2657. /* we call try-to-free pages for make this cgroup empty */
  2658. lru_add_drain_all();
  2659. /* try to free all pages in this cgroup */
  2660. shrink = 1;
  2661. while (nr_retries && mem->res.usage > 0) {
  2662. int progress;
  2663. if (signal_pending(current)) {
  2664. ret = -EINTR;
  2665. goto out;
  2666. }
  2667. progress = try_to_free_mem_cgroup_pages(mem, GFP_KERNEL,
  2668. false, get_swappiness(mem));
  2669. if (!progress) {
  2670. nr_retries--;
  2671. /* maybe some writeback is necessary */
  2672. congestion_wait(BLK_RW_ASYNC, HZ/10);
  2673. }
  2674. }
  2675. lru_add_drain();
  2676. /* try move_account...there may be some *locked* pages. */
  2677. goto move_account;
  2678. }
  2679. int mem_cgroup_force_empty_write(struct cgroup *cont, unsigned int event)
  2680. {
  2681. return mem_cgroup_force_empty(mem_cgroup_from_cont(cont), true);
  2682. }
  2683. static u64 mem_cgroup_hierarchy_read(struct cgroup *cont, struct cftype *cft)
  2684. {
  2685. return mem_cgroup_from_cont(cont)->use_hierarchy;
  2686. }
  2687. static int mem_cgroup_hierarchy_write(struct cgroup *cont, struct cftype *cft,
  2688. u64 val)
  2689. {
  2690. int retval = 0;
  2691. struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
  2692. struct cgroup *parent = cont->parent;
  2693. struct mem_cgroup *parent_mem = NULL;
  2694. if (parent)
  2695. parent_mem = mem_cgroup_from_cont(parent);
  2696. cgroup_lock();
  2697. /*
  2698. * If parent's use_hierarchy is set, we can't make any modifications
  2699. * in the child subtrees. If it is unset, then the change can
  2700. * occur, provided the current cgroup has no children.
  2701. *
  2702. * For the root cgroup, parent_mem is NULL, we allow value to be
  2703. * set if there are no children.
  2704. */
  2705. if ((!parent_mem || !parent_mem->use_hierarchy) &&
  2706. (val == 1 || val == 0)) {
  2707. if (list_empty(&cont->children))
  2708. mem->use_hierarchy = val;
  2709. else
  2710. retval = -EBUSY;
  2711. } else
  2712. retval = -EINVAL;
  2713. cgroup_unlock();
  2714. return retval;
  2715. }
  2716. struct mem_cgroup_idx_data {
  2717. s64 val;
  2718. enum mem_cgroup_stat_index idx;
  2719. };
  2720. static int
  2721. mem_cgroup_get_idx_stat(struct mem_cgroup *mem, void *data)
  2722. {
  2723. struct mem_cgroup_idx_data *d = data;
  2724. d->val += mem_cgroup_read_stat(mem, d->idx);
  2725. return 0;
  2726. }
  2727. static void
  2728. mem_cgroup_get_recursive_idx_stat(struct mem_cgroup *mem,
  2729. enum mem_cgroup_stat_index idx, s64 *val)
  2730. {
  2731. struct mem_cgroup_idx_data d;
  2732. d.idx = idx;
  2733. d.val = 0;
  2734. mem_cgroup_walk_tree(mem, &d, mem_cgroup_get_idx_stat);
  2735. *val = d.val;
  2736. }
  2737. static inline u64 mem_cgroup_usage(struct mem_cgroup *mem, bool swap)
  2738. {
  2739. u64 idx_val, val;
  2740. if (!mem_cgroup_is_root(mem)) {
  2741. if (!swap)
  2742. return res_counter_read_u64(&mem->res, RES_USAGE);
  2743. else
  2744. return res_counter_read_u64(&mem->memsw, RES_USAGE);
  2745. }
  2746. mem_cgroup_get_recursive_idx_stat(mem, MEM_CGROUP_STAT_CACHE, &idx_val);
  2747. val = idx_val;
  2748. mem_cgroup_get_recursive_idx_stat(mem, MEM_CGROUP_STAT_RSS, &idx_val);
  2749. val += idx_val;
  2750. if (swap) {
  2751. mem_cgroup_get_recursive_idx_stat(mem,
  2752. MEM_CGROUP_STAT_SWAPOUT, &idx_val);
  2753. val += idx_val;
  2754. }
  2755. return val << PAGE_SHIFT;
  2756. }
  2757. static u64 mem_cgroup_read(struct cgroup *cont, struct cftype *cft)
  2758. {
  2759. struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
  2760. u64 val;
  2761. int type, name;
  2762. type = MEMFILE_TYPE(cft->private);
  2763. name = MEMFILE_ATTR(cft->private);
  2764. switch (type) {
  2765. case _MEM:
  2766. if (name == RES_USAGE)
  2767. val = mem_cgroup_usage(mem, false);
  2768. else
  2769. val = res_counter_read_u64(&mem->res, name);
  2770. break;
  2771. case _MEMSWAP:
  2772. if (name == RES_USAGE)
  2773. val = mem_cgroup_usage(mem, true);
  2774. else
  2775. val = res_counter_read_u64(&mem->memsw, name);
  2776. break;
  2777. default:
  2778. BUG();
  2779. break;
  2780. }
  2781. return val;
  2782. }
  2783. /*
  2784. * The user of this function is...
  2785. * RES_LIMIT.
  2786. */
  2787. static int mem_cgroup_write(struct cgroup *cont, struct cftype *cft,
  2788. const char *buffer)
  2789. {
  2790. struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
  2791. int type, name;
  2792. unsigned long long val;
  2793. int ret;
  2794. type = MEMFILE_TYPE(cft->private);
  2795. name = MEMFILE_ATTR(cft->private);
  2796. switch (name) {
  2797. case RES_LIMIT:
  2798. if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
  2799. ret = -EINVAL;
  2800. break;
  2801. }
  2802. /* This function does all necessary parse...reuse it */
  2803. ret = res_counter_memparse_write_strategy(buffer, &val);
  2804. if (ret)
  2805. break;
  2806. if (type == _MEM)
  2807. ret = mem_cgroup_resize_limit(memcg, val);
  2808. else
  2809. ret = mem_cgroup_resize_memsw_limit(memcg, val);
  2810. break;
  2811. case RES_SOFT_LIMIT:
  2812. ret = res_counter_memparse_write_strategy(buffer, &val);
  2813. if (ret)
  2814. break;
  2815. /*
  2816. * For memsw, soft limits are hard to implement in terms
  2817. * of semantics, for now, we support soft limits for
  2818. * control without swap
  2819. */
  2820. if (type == _MEM)
  2821. ret = res_counter_set_soft_limit(&memcg->res, val);
  2822. else
  2823. ret = -EINVAL;
  2824. break;
  2825. default:
  2826. ret = -EINVAL; /* should be BUG() ? */
  2827. break;
  2828. }
  2829. return ret;
  2830. }
  2831. static void memcg_get_hierarchical_limit(struct mem_cgroup *memcg,
  2832. unsigned long long *mem_limit, unsigned long long *memsw_limit)
  2833. {
  2834. struct cgroup *cgroup;
  2835. unsigned long long min_limit, min_memsw_limit, tmp;
  2836. min_limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
  2837. min_memsw_limit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
  2838. cgroup = memcg->css.cgroup;
  2839. if (!memcg->use_hierarchy)
  2840. goto out;
  2841. while (cgroup->parent) {
  2842. cgroup = cgroup->parent;
  2843. memcg = mem_cgroup_from_cont(cgroup);
  2844. if (!memcg->use_hierarchy)
  2845. break;
  2846. tmp = res_counter_read_u64(&memcg->res, RES_LIMIT);
  2847. min_limit = min(min_limit, tmp);
  2848. tmp = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
  2849. min_memsw_limit = min(min_memsw_limit, tmp);
  2850. }
  2851. out:
  2852. *mem_limit = min_limit;
  2853. *memsw_limit = min_memsw_limit;
  2854. return;
  2855. }
  2856. static int mem_cgroup_reset(struct cgroup *cont, unsigned int event)
  2857. {
  2858. struct mem_cgroup *mem;
  2859. int type, name;
  2860. mem = mem_cgroup_from_cont(cont);
  2861. type = MEMFILE_TYPE(event);
  2862. name = MEMFILE_ATTR(event);
  2863. switch (name) {
  2864. case RES_MAX_USAGE:
  2865. if (type == _MEM)
  2866. res_counter_reset_max(&mem->res);
  2867. else
  2868. res_counter_reset_max(&mem->memsw);
  2869. break;
  2870. case RES_FAILCNT:
  2871. if (type == _MEM)
  2872. res_counter_reset_failcnt(&mem->res);
  2873. else
  2874. res_counter_reset_failcnt(&mem->memsw);
  2875. break;
  2876. }
  2877. return 0;
  2878. }
  2879. static u64 mem_cgroup_move_charge_read(struct cgroup *cgrp,
  2880. struct cftype *cft)
  2881. {
  2882. return mem_cgroup_from_cont(cgrp)->move_charge_at_immigrate;
  2883. }
  2884. #ifdef CONFIG_MMU
  2885. static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
  2886. struct cftype *cft, u64 val)
  2887. {
  2888. struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
  2889. if (val >= (1 << NR_MOVE_TYPE))
  2890. return -EINVAL;
  2891. /*
  2892. * We check this value several times in both in can_attach() and
  2893. * attach(), so we need cgroup lock to prevent this value from being
  2894. * inconsistent.
  2895. */
  2896. cgroup_lock();
  2897. mem->move_charge_at_immigrate = val;
  2898. cgroup_unlock();
  2899. return 0;
  2900. }
  2901. #else
  2902. static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
  2903. struct cftype *cft, u64 val)
  2904. {
  2905. return -ENOSYS;
  2906. }
  2907. #endif
  2908. /* For read statistics */
  2909. enum {
  2910. MCS_CACHE,
  2911. MCS_RSS,
  2912. MCS_FILE_MAPPED,
  2913. MCS_PGPGIN,
  2914. MCS_PGPGOUT,
  2915. MCS_SWAP,
  2916. MCS_INACTIVE_ANON,
  2917. MCS_ACTIVE_ANON,
  2918. MCS_INACTIVE_FILE,
  2919. MCS_ACTIVE_FILE,
  2920. MCS_UNEVICTABLE,
  2921. NR_MCS_STAT,
  2922. };
  2923. struct mcs_total_stat {
  2924. s64 stat[NR_MCS_STAT];
  2925. };
  2926. struct {
  2927. char *local_name;
  2928. char *total_name;
  2929. } memcg_stat_strings[NR_MCS_STAT] = {
  2930. {"cache", "total_cache"},
  2931. {"rss", "total_rss"},
  2932. {"mapped_file", "total_mapped_file"},
  2933. {"pgpgin", "total_pgpgin"},
  2934. {"pgpgout", "total_pgpgout"},
  2935. {"swap", "total_swap"},
  2936. {"inactive_anon", "total_inactive_anon"},
  2937. {"active_anon", "total_active_anon"},
  2938. {"inactive_file", "total_inactive_file"},
  2939. {"active_file", "total_active_file"},
  2940. {"unevictable", "total_unevictable"}
  2941. };
  2942. static int mem_cgroup_get_local_stat(struct mem_cgroup *mem, void *data)
  2943. {
  2944. struct mcs_total_stat *s = data;
  2945. s64 val;
  2946. /* per cpu stat */
  2947. val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_CACHE);
  2948. s->stat[MCS_CACHE] += val * PAGE_SIZE;
  2949. val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_RSS);
  2950. s->stat[MCS_RSS] += val * PAGE_SIZE;
  2951. val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_FILE_MAPPED);
  2952. s->stat[MCS_FILE_MAPPED] += val * PAGE_SIZE;
  2953. val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_PGPGIN_COUNT);
  2954. s->stat[MCS_PGPGIN] += val;
  2955. val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_PGPGOUT_COUNT);
  2956. s->stat[MCS_PGPGOUT] += val;
  2957. if (do_swap_account) {
  2958. val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_SWAPOUT);
  2959. s->stat[MCS_SWAP] += val * PAGE_SIZE;
  2960. }
  2961. /* per zone stat */
  2962. val = mem_cgroup_get_local_zonestat(mem, LRU_INACTIVE_ANON);
  2963. s->stat[MCS_INACTIVE_ANON] += val * PAGE_SIZE;
  2964. val = mem_cgroup_get_local_zonestat(mem, LRU_ACTIVE_ANON);
  2965. s->stat[MCS_ACTIVE_ANON] += val * PAGE_SIZE;
  2966. val = mem_cgroup_get_local_zonestat(mem, LRU_INACTIVE_FILE);
  2967. s->stat[MCS_INACTIVE_FILE] += val * PAGE_SIZE;
  2968. val = mem_cgroup_get_local_zonestat(mem, LRU_ACTIVE_FILE);
  2969. s->stat[MCS_ACTIVE_FILE] += val * PAGE_SIZE;
  2970. val = mem_cgroup_get_local_zonestat(mem, LRU_UNEVICTABLE);
  2971. s->stat[MCS_UNEVICTABLE] += val * PAGE_SIZE;
  2972. return 0;
  2973. }
  2974. static void
  2975. mem_cgroup_get_total_stat(struct mem_cgroup *mem, struct mcs_total_stat *s)
  2976. {
  2977. mem_cgroup_walk_tree(mem, s, mem_cgroup_get_local_stat);
  2978. }
  2979. static int mem_control_stat_show(struct cgroup *cont, struct cftype *cft,
  2980. struct cgroup_map_cb *cb)
  2981. {
  2982. struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
  2983. struct mcs_total_stat mystat;
  2984. int i;
  2985. memset(&mystat, 0, sizeof(mystat));
  2986. mem_cgroup_get_local_stat(mem_cont, &mystat);
  2987. for (i = 0; i < NR_MCS_STAT; i++) {
  2988. if (i == MCS_SWAP && !do_swap_account)
  2989. continue;
  2990. cb->fill(cb, memcg_stat_strings[i].local_name, mystat.stat[i]);
  2991. }
  2992. /* Hierarchical information */
  2993. {
  2994. unsigned long long limit, memsw_limit;
  2995. memcg_get_hierarchical_limit(mem_cont, &limit, &memsw_limit);
  2996. cb->fill(cb, "hierarchical_memory_limit", limit);
  2997. if (do_swap_account)
  2998. cb->fill(cb, "hierarchical_memsw_limit", memsw_limit);
  2999. }
  3000. memset(&mystat, 0, sizeof(mystat));
  3001. mem_cgroup_get_total_stat(mem_cont, &mystat);
  3002. for (i = 0; i < NR_MCS_STAT; i++) {
  3003. if (i == MCS_SWAP && !do_swap_account)
  3004. continue;
  3005. cb->fill(cb, memcg_stat_strings[i].total_name, mystat.stat[i]);
  3006. }
  3007. #ifdef CONFIG_DEBUG_VM
  3008. cb->fill(cb, "inactive_ratio", calc_inactive_ratio(mem_cont, NULL));
  3009. {
  3010. int nid, zid;
  3011. struct mem_cgroup_per_zone *mz;
  3012. unsigned long recent_rotated[2] = {0, 0};
  3013. unsigned long recent_scanned[2] = {0, 0};
  3014. for_each_online_node(nid)
  3015. for (zid = 0; zid < MAX_NR_ZONES; zid++) {
  3016. mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
  3017. recent_rotated[0] +=
  3018. mz->reclaim_stat.recent_rotated[0];
  3019. recent_rotated[1] +=
  3020. mz->reclaim_stat.recent_rotated[1];
  3021. recent_scanned[0] +=
  3022. mz->reclaim_stat.recent_scanned[0];
  3023. recent_scanned[1] +=
  3024. mz->reclaim_stat.recent_scanned[1];
  3025. }
  3026. cb->fill(cb, "recent_rotated_anon", recent_rotated[0]);
  3027. cb->fill(cb, "recent_rotated_file", recent_rotated[1]);
  3028. cb->fill(cb, "recent_scanned_anon", recent_scanned[0]);
  3029. cb->fill(cb, "recent_scanned_file", recent_scanned[1]);
  3030. }
  3031. #endif
  3032. return 0;
  3033. }
  3034. static u64 mem_cgroup_swappiness_read(struct cgroup *cgrp, struct cftype *cft)
  3035. {
  3036. struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
  3037. return get_swappiness(memcg);
  3038. }
  3039. static int mem_cgroup_swappiness_write(struct cgroup *cgrp, struct cftype *cft,
  3040. u64 val)
  3041. {
  3042. struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
  3043. struct mem_cgroup *parent;
  3044. if (val > 100)
  3045. return -EINVAL;
  3046. if (cgrp->parent == NULL)
  3047. return -EINVAL;
  3048. parent = mem_cgroup_from_cont(cgrp->parent);
  3049. cgroup_lock();
  3050. /* If under hierarchy, only empty-root can set this value */
  3051. if ((parent->use_hierarchy) ||
  3052. (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
  3053. cgroup_unlock();
  3054. return -EINVAL;
  3055. }
  3056. spin_lock(&memcg->reclaim_param_lock);
  3057. memcg->swappiness = val;
  3058. spin_unlock(&memcg->reclaim_param_lock);
  3059. cgroup_unlock();
  3060. return 0;
  3061. }
  3062. static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
  3063. {
  3064. struct mem_cgroup_threshold_ary *t;
  3065. u64 usage;
  3066. int i;
  3067. rcu_read_lock();
  3068. if (!swap)
  3069. t = rcu_dereference(memcg->thresholds.primary);
  3070. else
  3071. t = rcu_dereference(memcg->memsw_thresholds.primary);
  3072. if (!t)
  3073. goto unlock;
  3074. usage = mem_cgroup_usage(memcg, swap);
  3075. /*
  3076. * current_threshold points to threshold just below usage.
  3077. * If it's not true, a threshold was crossed after last
  3078. * call of __mem_cgroup_threshold().
  3079. */
  3080. i = t->current_threshold;
  3081. /*
  3082. * Iterate backward over array of thresholds starting from
  3083. * current_threshold and check if a threshold is crossed.
  3084. * If none of thresholds below usage is crossed, we read
  3085. * only one element of the array here.
  3086. */
  3087. for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
  3088. eventfd_signal(t->entries[i].eventfd, 1);
  3089. /* i = current_threshold + 1 */
  3090. i++;
  3091. /*
  3092. * Iterate forward over array of thresholds starting from
  3093. * current_threshold+1 and check if a threshold is crossed.
  3094. * If none of thresholds above usage is crossed, we read
  3095. * only one element of the array here.
  3096. */
  3097. for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
  3098. eventfd_signal(t->entries[i].eventfd, 1);
  3099. /* Update current_threshold */
  3100. t->current_threshold = i - 1;
  3101. unlock:
  3102. rcu_read_unlock();
  3103. }
  3104. static void mem_cgroup_threshold(struct mem_cgroup *memcg)
  3105. {
  3106. __mem_cgroup_threshold(memcg, false);
  3107. if (do_swap_account)
  3108. __mem_cgroup_threshold(memcg, true);
  3109. }
  3110. static int compare_thresholds(const void *a, const void *b)
  3111. {
  3112. const struct mem_cgroup_threshold *_a = a;
  3113. const struct mem_cgroup_threshold *_b = b;
  3114. return _a->threshold - _b->threshold;
  3115. }
  3116. static int mem_cgroup_oom_notify_cb(struct mem_cgroup *mem, void *data)
  3117. {
  3118. struct mem_cgroup_eventfd_list *ev;
  3119. list_for_each_entry(ev, &mem->oom_notify, list)
  3120. eventfd_signal(ev->eventfd, 1);
  3121. return 0;
  3122. }
  3123. static void mem_cgroup_oom_notify(struct mem_cgroup *mem)
  3124. {
  3125. mem_cgroup_walk_tree(mem, NULL, mem_cgroup_oom_notify_cb);
  3126. }
  3127. static int mem_cgroup_usage_register_event(struct cgroup *cgrp,
  3128. struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
  3129. {
  3130. struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
  3131. struct mem_cgroup_thresholds *thresholds;
  3132. struct mem_cgroup_threshold_ary *new;
  3133. int type = MEMFILE_TYPE(cft->private);
  3134. u64 threshold, usage;
  3135. int i, size, ret;
  3136. ret = res_counter_memparse_write_strategy(args, &threshold);
  3137. if (ret)
  3138. return ret;
  3139. mutex_lock(&memcg->thresholds_lock);
  3140. if (type == _MEM)
  3141. thresholds = &memcg->thresholds;
  3142. else if (type == _MEMSWAP)
  3143. thresholds = &memcg->memsw_thresholds;
  3144. else
  3145. BUG();
  3146. usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
  3147. /* Check if a threshold crossed before adding a new one */
  3148. if (thresholds->primary)
  3149. __mem_cgroup_threshold(memcg, type == _MEMSWAP);
  3150. size = thresholds->primary ? thresholds->primary->size + 1 : 1;
  3151. /* Allocate memory for new array of thresholds */
  3152. new = kmalloc(sizeof(*new) + size * sizeof(struct mem_cgroup_threshold),
  3153. GFP_KERNEL);
  3154. if (!new) {
  3155. ret = -ENOMEM;
  3156. goto unlock;
  3157. }
  3158. new->size = size;
  3159. /* Copy thresholds (if any) to new array */
  3160. if (thresholds->primary) {
  3161. memcpy(new->entries, thresholds->primary->entries, (size - 1) *
  3162. sizeof(struct mem_cgroup_threshold));
  3163. }
  3164. /* Add new threshold */
  3165. new->entries[size - 1].eventfd = eventfd;
  3166. new->entries[size - 1].threshold = threshold;
  3167. /* Sort thresholds. Registering of new threshold isn't time-critical */
  3168. sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
  3169. compare_thresholds, NULL);
  3170. /* Find current threshold */
  3171. new->current_threshold = -1;
  3172. for (i = 0; i < size; i++) {
  3173. if (new->entries[i].threshold < usage) {
  3174. /*
  3175. * new->current_threshold will not be used until
  3176. * rcu_assign_pointer(), so it's safe to increment
  3177. * it here.
  3178. */
  3179. ++new->current_threshold;
  3180. }
  3181. }
  3182. /* Free old spare buffer and save old primary buffer as spare */
  3183. kfree(thresholds->spare);
  3184. thresholds->spare = thresholds->primary;
  3185. rcu_assign_pointer(thresholds->primary, new);
  3186. /* To be sure that nobody uses thresholds */
  3187. synchronize_rcu();
  3188. unlock:
  3189. mutex_unlock(&memcg->thresholds_lock);
  3190. return ret;
  3191. }
  3192. static void mem_cgroup_usage_unregister_event(struct cgroup *cgrp,
  3193. struct cftype *cft, struct eventfd_ctx *eventfd)
  3194. {
  3195. struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
  3196. struct mem_cgroup_thresholds *thresholds;
  3197. struct mem_cgroup_threshold_ary *new;
  3198. int type = MEMFILE_TYPE(cft->private);
  3199. u64 usage;
  3200. int i, j, size;
  3201. mutex_lock(&memcg->thresholds_lock);
  3202. if (type == _MEM)
  3203. thresholds = &memcg->thresholds;
  3204. else if (type == _MEMSWAP)
  3205. thresholds = &memcg->memsw_thresholds;
  3206. else
  3207. BUG();
  3208. /*
  3209. * Something went wrong if we trying to unregister a threshold
  3210. * if we don't have thresholds
  3211. */
  3212. BUG_ON(!thresholds);
  3213. usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
  3214. /* Check if a threshold crossed before removing */
  3215. __mem_cgroup_threshold(memcg, type == _MEMSWAP);
  3216. /* Calculate new number of threshold */
  3217. size = 0;
  3218. for (i = 0; i < thresholds->primary->size; i++) {
  3219. if (thresholds->primary->entries[i].eventfd != eventfd)
  3220. size++;
  3221. }
  3222. new = thresholds->spare;
  3223. /* Set thresholds array to NULL if we don't have thresholds */
  3224. if (!size) {
  3225. kfree(new);
  3226. new = NULL;
  3227. goto swap_buffers;
  3228. }
  3229. new->size = size;
  3230. /* Copy thresholds and find current threshold */
  3231. new->current_threshold = -1;
  3232. for (i = 0, j = 0; i < thresholds->primary->size; i++) {
  3233. if (thresholds->primary->entries[i].eventfd == eventfd)
  3234. continue;
  3235. new->entries[j] = thresholds->primary->entries[i];
  3236. if (new->entries[j].threshold < usage) {
  3237. /*
  3238. * new->current_threshold will not be used
  3239. * until rcu_assign_pointer(), so it's safe to increment
  3240. * it here.
  3241. */
  3242. ++new->current_threshold;
  3243. }
  3244. j++;
  3245. }
  3246. swap_buffers:
  3247. /* Swap primary and spare array */
  3248. thresholds->spare = thresholds->primary;
  3249. rcu_assign_pointer(thresholds->primary, new);
  3250. /* To be sure that nobody uses thresholds */
  3251. synchronize_rcu();
  3252. mutex_unlock(&memcg->thresholds_lock);
  3253. }
  3254. static int mem_cgroup_oom_register_event(struct cgroup *cgrp,
  3255. struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
  3256. {
  3257. struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
  3258. struct mem_cgroup_eventfd_list *event;
  3259. int type = MEMFILE_TYPE(cft->private);
  3260. BUG_ON(type != _OOM_TYPE);
  3261. event = kmalloc(sizeof(*event), GFP_KERNEL);
  3262. if (!event)
  3263. return -ENOMEM;
  3264. mutex_lock(&memcg_oom_mutex);
  3265. event->eventfd = eventfd;
  3266. list_add(&event->list, &memcg->oom_notify);
  3267. /* already in OOM ? */
  3268. if (atomic_read(&memcg->oom_lock))
  3269. eventfd_signal(eventfd, 1);
  3270. mutex_unlock(&memcg_oom_mutex);
  3271. return 0;
  3272. }
  3273. static void mem_cgroup_oom_unregister_event(struct cgroup *cgrp,
  3274. struct cftype *cft, struct eventfd_ctx *eventfd)
  3275. {
  3276. struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
  3277. struct mem_cgroup_eventfd_list *ev, *tmp;
  3278. int type = MEMFILE_TYPE(cft->private);
  3279. BUG_ON(type != _OOM_TYPE);
  3280. mutex_lock(&memcg_oom_mutex);
  3281. list_for_each_entry_safe(ev, tmp, &mem->oom_notify, list) {
  3282. if (ev->eventfd == eventfd) {
  3283. list_del(&ev->list);
  3284. kfree(ev);
  3285. }
  3286. }
  3287. mutex_unlock(&memcg_oom_mutex);
  3288. }
  3289. static int mem_cgroup_oom_control_read(struct cgroup *cgrp,
  3290. struct cftype *cft, struct cgroup_map_cb *cb)
  3291. {
  3292. struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
  3293. cb->fill(cb, "oom_kill_disable", mem->oom_kill_disable);
  3294. if (atomic_read(&mem->oom_lock))
  3295. cb->fill(cb, "under_oom", 1);
  3296. else
  3297. cb->fill(cb, "under_oom", 0);
  3298. return 0;
  3299. }
  3300. /*
  3301. */
  3302. static int mem_cgroup_oom_control_write(struct cgroup *cgrp,
  3303. struct cftype *cft, u64 val)
  3304. {
  3305. struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
  3306. struct mem_cgroup *parent;
  3307. /* cannot set to root cgroup and only 0 and 1 are allowed */
  3308. if (!cgrp->parent || !((val == 0) || (val == 1)))
  3309. return -EINVAL;
  3310. parent = mem_cgroup_from_cont(cgrp->parent);
  3311. cgroup_lock();
  3312. /* oom-kill-disable is a flag for subhierarchy. */
  3313. if ((parent->use_hierarchy) ||
  3314. (mem->use_hierarchy && !list_empty(&cgrp->children))) {
  3315. cgroup_unlock();
  3316. return -EINVAL;
  3317. }
  3318. mem->oom_kill_disable = val;
  3319. if (!val)
  3320. memcg_oom_recover(mem);
  3321. cgroup_unlock();
  3322. return 0;
  3323. }
  3324. static struct cftype mem_cgroup_files[] = {
  3325. {
  3326. .name = "usage_in_bytes",
  3327. .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
  3328. .read_u64 = mem_cgroup_read,
  3329. .register_event = mem_cgroup_usage_register_event,
  3330. .unregister_event = mem_cgroup_usage_unregister_event,
  3331. },
  3332. {
  3333. .name = "max_usage_in_bytes",
  3334. .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
  3335. .trigger = mem_cgroup_reset,
  3336. .read_u64 = mem_cgroup_read,
  3337. },
  3338. {
  3339. .name = "limit_in_bytes",
  3340. .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
  3341. .write_string = mem_cgroup_write,
  3342. .read_u64 = mem_cgroup_read,
  3343. },
  3344. {
  3345. .name = "soft_limit_in_bytes",
  3346. .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
  3347. .write_string = mem_cgroup_write,
  3348. .read_u64 = mem_cgroup_read,
  3349. },
  3350. {
  3351. .name = "failcnt",
  3352. .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
  3353. .trigger = mem_cgroup_reset,
  3354. .read_u64 = mem_cgroup_read,
  3355. },
  3356. {
  3357. .name = "stat",
  3358. .read_map = mem_control_stat_show,
  3359. },
  3360. {
  3361. .name = "force_empty",
  3362. .trigger = mem_cgroup_force_empty_write,
  3363. },
  3364. {
  3365. .name = "use_hierarchy",
  3366. .write_u64 = mem_cgroup_hierarchy_write,
  3367. .read_u64 = mem_cgroup_hierarchy_read,
  3368. },
  3369. {
  3370. .name = "swappiness",
  3371. .read_u64 = mem_cgroup_swappiness_read,
  3372. .write_u64 = mem_cgroup_swappiness_write,
  3373. },
  3374. {
  3375. .name = "move_charge_at_immigrate",
  3376. .read_u64 = mem_cgroup_move_charge_read,
  3377. .write_u64 = mem_cgroup_move_charge_write,
  3378. },
  3379. {
  3380. .name = "oom_control",
  3381. .read_map = mem_cgroup_oom_control_read,
  3382. .write_u64 = mem_cgroup_oom_control_write,
  3383. .register_event = mem_cgroup_oom_register_event,
  3384. .unregister_event = mem_cgroup_oom_unregister_event,
  3385. .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
  3386. },
  3387. };
  3388. #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
  3389. static struct cftype memsw_cgroup_files[] = {
  3390. {
  3391. .name = "memsw.usage_in_bytes",
  3392. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
  3393. .read_u64 = mem_cgroup_read,
  3394. .register_event = mem_cgroup_usage_register_event,
  3395. .unregister_event = mem_cgroup_usage_unregister_event,
  3396. },
  3397. {
  3398. .name = "memsw.max_usage_in_bytes",
  3399. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
  3400. .trigger = mem_cgroup_reset,
  3401. .read_u64 = mem_cgroup_read,
  3402. },
  3403. {
  3404. .name = "memsw.limit_in_bytes",
  3405. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
  3406. .write_string = mem_cgroup_write,
  3407. .read_u64 = mem_cgroup_read,
  3408. },
  3409. {
  3410. .name = "memsw.failcnt",
  3411. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
  3412. .trigger = mem_cgroup_reset,
  3413. .read_u64 = mem_cgroup_read,
  3414. },
  3415. };
  3416. static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
  3417. {
  3418. if (!do_swap_account)
  3419. return 0;
  3420. return cgroup_add_files(cont, ss, memsw_cgroup_files,
  3421. ARRAY_SIZE(memsw_cgroup_files));
  3422. };
  3423. #else
  3424. static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
  3425. {
  3426. return 0;
  3427. }
  3428. #endif
  3429. static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
  3430. {
  3431. struct mem_cgroup_per_node *pn;
  3432. struct mem_cgroup_per_zone *mz;
  3433. enum lru_list l;
  3434. int zone, tmp = node;
  3435. /*
  3436. * This routine is called against possible nodes.
  3437. * But it's BUG to call kmalloc() against offline node.
  3438. *
  3439. * TODO: this routine can waste much memory for nodes which will
  3440. * never be onlined. It's better to use memory hotplug callback
  3441. * function.
  3442. */
  3443. if (!node_state(node, N_NORMAL_MEMORY))
  3444. tmp = -1;
  3445. pn = kmalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
  3446. if (!pn)
  3447. return 1;
  3448. mem->info.nodeinfo[node] = pn;
  3449. memset(pn, 0, sizeof(*pn));
  3450. for (zone = 0; zone < MAX_NR_ZONES; zone++) {
  3451. mz = &pn->zoneinfo[zone];
  3452. for_each_lru(l)
  3453. INIT_LIST_HEAD(&mz->lists[l]);
  3454. mz->usage_in_excess = 0;
  3455. mz->on_tree = false;
  3456. mz->mem = mem;
  3457. }
  3458. return 0;
  3459. }
  3460. static void free_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
  3461. {
  3462. kfree(mem->info.nodeinfo[node]);
  3463. }
  3464. static struct mem_cgroup *mem_cgroup_alloc(void)
  3465. {
  3466. struct mem_cgroup *mem;
  3467. int size = sizeof(struct mem_cgroup);
  3468. /* Can be very big if MAX_NUMNODES is very big */
  3469. if (size < PAGE_SIZE)
  3470. mem = kmalloc(size, GFP_KERNEL);
  3471. else
  3472. mem = vmalloc(size);
  3473. if (!mem)
  3474. return NULL;
  3475. memset(mem, 0, size);
  3476. mem->stat = alloc_percpu(struct mem_cgroup_stat_cpu);
  3477. if (!mem->stat) {
  3478. if (size < PAGE_SIZE)
  3479. kfree(mem);
  3480. else
  3481. vfree(mem);
  3482. mem = NULL;
  3483. }
  3484. return mem;
  3485. }
  3486. /*
  3487. * At destroying mem_cgroup, references from swap_cgroup can remain.
  3488. * (scanning all at force_empty is too costly...)
  3489. *
  3490. * Instead of clearing all references at force_empty, we remember
  3491. * the number of reference from swap_cgroup and free mem_cgroup when
  3492. * it goes down to 0.
  3493. *
  3494. * Removal of cgroup itself succeeds regardless of refs from swap.
  3495. */
  3496. static void __mem_cgroup_free(struct mem_cgroup *mem)
  3497. {
  3498. int node;
  3499. mem_cgroup_remove_from_trees(mem);
  3500. free_css_id(&mem_cgroup_subsys, &mem->css);
  3501. for_each_node_state(node, N_POSSIBLE)
  3502. free_mem_cgroup_per_zone_info(mem, node);
  3503. free_percpu(mem->stat);
  3504. if (sizeof(struct mem_cgroup) < PAGE_SIZE)
  3505. kfree(mem);
  3506. else
  3507. vfree(mem);
  3508. }
  3509. static void mem_cgroup_get(struct mem_cgroup *mem)
  3510. {
  3511. atomic_inc(&mem->refcnt);
  3512. }
  3513. static void __mem_cgroup_put(struct mem_cgroup *mem, int count)
  3514. {
  3515. if (atomic_sub_and_test(count, &mem->refcnt)) {
  3516. struct mem_cgroup *parent = parent_mem_cgroup(mem);
  3517. __mem_cgroup_free(mem);
  3518. if (parent)
  3519. mem_cgroup_put(parent);
  3520. }
  3521. }
  3522. static void mem_cgroup_put(struct mem_cgroup *mem)
  3523. {
  3524. __mem_cgroup_put(mem, 1);
  3525. }
  3526. /*
  3527. * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
  3528. */
  3529. static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *mem)
  3530. {
  3531. if (!mem->res.parent)
  3532. return NULL;
  3533. return mem_cgroup_from_res_counter(mem->res.parent, res);
  3534. }
  3535. #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
  3536. static void __init enable_swap_cgroup(void)
  3537. {
  3538. if (!mem_cgroup_disabled() && really_do_swap_account)
  3539. do_swap_account = 1;
  3540. }
  3541. #else
  3542. static void __init enable_swap_cgroup(void)
  3543. {
  3544. }
  3545. #endif
  3546. static int mem_cgroup_soft_limit_tree_init(void)
  3547. {
  3548. struct mem_cgroup_tree_per_node *rtpn;
  3549. struct mem_cgroup_tree_per_zone *rtpz;
  3550. int tmp, node, zone;
  3551. for_each_node_state(node, N_POSSIBLE) {
  3552. tmp = node;
  3553. if (!node_state(node, N_NORMAL_MEMORY))
  3554. tmp = -1;
  3555. rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, tmp);
  3556. if (!rtpn)
  3557. return 1;
  3558. soft_limit_tree.rb_tree_per_node[node] = rtpn;
  3559. for (zone = 0; zone < MAX_NR_ZONES; zone++) {
  3560. rtpz = &rtpn->rb_tree_per_zone[zone];
  3561. rtpz->rb_root = RB_ROOT;
  3562. spin_lock_init(&rtpz->lock);
  3563. }
  3564. }
  3565. return 0;
  3566. }
  3567. static struct cgroup_subsys_state * __ref
  3568. mem_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cont)
  3569. {
  3570. struct mem_cgroup *mem, *parent;
  3571. long error = -ENOMEM;
  3572. int node;
  3573. mem = mem_cgroup_alloc();
  3574. if (!mem)
  3575. return ERR_PTR(error);
  3576. for_each_node_state(node, N_POSSIBLE)
  3577. if (alloc_mem_cgroup_per_zone_info(mem, node))
  3578. goto free_out;
  3579. /* root ? */
  3580. if (cont->parent == NULL) {
  3581. int cpu;
  3582. enable_swap_cgroup();
  3583. parent = NULL;
  3584. root_mem_cgroup = mem;
  3585. if (mem_cgroup_soft_limit_tree_init())
  3586. goto free_out;
  3587. for_each_possible_cpu(cpu) {
  3588. struct memcg_stock_pcp *stock =
  3589. &per_cpu(memcg_stock, cpu);
  3590. INIT_WORK(&stock->work, drain_local_stock);
  3591. }
  3592. hotcpu_notifier(memcg_stock_cpu_callback, 0);
  3593. } else {
  3594. parent = mem_cgroup_from_cont(cont->parent);
  3595. mem->use_hierarchy = parent->use_hierarchy;
  3596. mem->oom_kill_disable = parent->oom_kill_disable;
  3597. }
  3598. if (parent && parent->use_hierarchy) {
  3599. res_counter_init(&mem->res, &parent->res);
  3600. res_counter_init(&mem->memsw, &parent->memsw);
  3601. /*
  3602. * We increment refcnt of the parent to ensure that we can
  3603. * safely access it on res_counter_charge/uncharge.
  3604. * This refcnt will be decremented when freeing this
  3605. * mem_cgroup(see mem_cgroup_put).
  3606. */
  3607. mem_cgroup_get(parent);
  3608. } else {
  3609. res_counter_init(&mem->res, NULL);
  3610. res_counter_init(&mem->memsw, NULL);
  3611. }
  3612. mem->last_scanned_child = 0;
  3613. spin_lock_init(&mem->reclaim_param_lock);
  3614. INIT_LIST_HEAD(&mem->oom_notify);
  3615. if (parent)
  3616. mem->swappiness = get_swappiness(parent);
  3617. atomic_set(&mem->refcnt, 1);
  3618. mem->move_charge_at_immigrate = 0;
  3619. mutex_init(&mem->thresholds_lock);
  3620. return &mem->css;
  3621. free_out:
  3622. __mem_cgroup_free(mem);
  3623. root_mem_cgroup = NULL;
  3624. return ERR_PTR(error);
  3625. }
  3626. static int mem_cgroup_pre_destroy(struct cgroup_subsys *ss,
  3627. struct cgroup *cont)
  3628. {
  3629. struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
  3630. return mem_cgroup_force_empty(mem, false);
  3631. }
  3632. static void mem_cgroup_destroy(struct cgroup_subsys *ss,
  3633. struct cgroup *cont)
  3634. {
  3635. struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
  3636. mem_cgroup_put(mem);
  3637. }
  3638. static int mem_cgroup_populate(struct cgroup_subsys *ss,
  3639. struct cgroup *cont)
  3640. {
  3641. int ret;
  3642. ret = cgroup_add_files(cont, ss, mem_cgroup_files,
  3643. ARRAY_SIZE(mem_cgroup_files));
  3644. if (!ret)
  3645. ret = register_memsw_files(cont, ss);
  3646. return ret;
  3647. }
  3648. #ifdef CONFIG_MMU
  3649. /* Handlers for move charge at task migration. */
  3650. #define PRECHARGE_COUNT_AT_ONCE 256
  3651. static int mem_cgroup_do_precharge(unsigned long count)
  3652. {
  3653. int ret = 0;
  3654. int batch_count = PRECHARGE_COUNT_AT_ONCE;
  3655. struct mem_cgroup *mem = mc.to;
  3656. if (mem_cgroup_is_root(mem)) {
  3657. mc.precharge += count;
  3658. /* we don't need css_get for root */
  3659. return ret;
  3660. }
  3661. /* try to charge at once */
  3662. if (count > 1) {
  3663. struct res_counter *dummy;
  3664. /*
  3665. * "mem" cannot be under rmdir() because we've already checked
  3666. * by cgroup_lock_live_cgroup() that it is not removed and we
  3667. * are still under the same cgroup_mutex. So we can postpone
  3668. * css_get().
  3669. */
  3670. if (res_counter_charge(&mem->res, PAGE_SIZE * count, &dummy))
  3671. goto one_by_one;
  3672. if (do_swap_account && res_counter_charge(&mem->memsw,
  3673. PAGE_SIZE * count, &dummy)) {
  3674. res_counter_uncharge(&mem->res, PAGE_SIZE * count);
  3675. goto one_by_one;
  3676. }
  3677. mc.precharge += count;
  3678. VM_BUG_ON(test_bit(CSS_ROOT, &mem->css.flags));
  3679. WARN_ON_ONCE(count > INT_MAX);
  3680. __css_get(&mem->css, (int)count);
  3681. return ret;
  3682. }
  3683. one_by_one:
  3684. /* fall back to one by one charge */
  3685. while (count--) {
  3686. if (signal_pending(current)) {
  3687. ret = -EINTR;
  3688. break;
  3689. }
  3690. if (!batch_count--) {
  3691. batch_count = PRECHARGE_COUNT_AT_ONCE;
  3692. cond_resched();
  3693. }
  3694. ret = __mem_cgroup_try_charge(NULL, GFP_KERNEL, &mem, false);
  3695. if (ret || !mem)
  3696. /* mem_cgroup_clear_mc() will do uncharge later */
  3697. return -ENOMEM;
  3698. mc.precharge++;
  3699. }
  3700. return ret;
  3701. }
  3702. /**
  3703. * is_target_pte_for_mc - check a pte whether it is valid for move charge
  3704. * @vma: the vma the pte to be checked belongs
  3705. * @addr: the address corresponding to the pte to be checked
  3706. * @ptent: the pte to be checked
  3707. * @target: the pointer the target page or swap ent will be stored(can be NULL)
  3708. *
  3709. * Returns
  3710. * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
  3711. * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
  3712. * move charge. if @target is not NULL, the page is stored in target->page
  3713. * with extra refcnt got(Callers should handle it).
  3714. * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
  3715. * target for charge migration. if @target is not NULL, the entry is stored
  3716. * in target->ent.
  3717. *
  3718. * Called with pte lock held.
  3719. */
  3720. union mc_target {
  3721. struct page *page;
  3722. swp_entry_t ent;
  3723. };
  3724. enum mc_target_type {
  3725. MC_TARGET_NONE, /* not used */
  3726. MC_TARGET_PAGE,
  3727. MC_TARGET_SWAP,
  3728. };
  3729. static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
  3730. unsigned long addr, pte_t ptent)
  3731. {
  3732. struct page *page = vm_normal_page(vma, addr, ptent);
  3733. if (!page || !page_mapped(page))
  3734. return NULL;
  3735. if (PageAnon(page)) {
  3736. /* we don't move shared anon */
  3737. if (!move_anon() || page_mapcount(page) > 2)
  3738. return NULL;
  3739. } else if (!move_file())
  3740. /* we ignore mapcount for file pages */
  3741. return NULL;
  3742. if (!get_page_unless_zero(page))
  3743. return NULL;
  3744. return page;
  3745. }
  3746. static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
  3747. unsigned long addr, pte_t ptent, swp_entry_t *entry)
  3748. {
  3749. int usage_count;
  3750. struct page *page = NULL;
  3751. swp_entry_t ent = pte_to_swp_entry(ptent);
  3752. if (!move_anon() || non_swap_entry(ent))
  3753. return NULL;
  3754. usage_count = mem_cgroup_count_swap_user(ent, &page);
  3755. if (usage_count > 1) { /* we don't move shared anon */
  3756. if (page)
  3757. put_page(page);
  3758. return NULL;
  3759. }
  3760. if (do_swap_account)
  3761. entry->val = ent.val;
  3762. return page;
  3763. }
  3764. static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
  3765. unsigned long addr, pte_t ptent, swp_entry_t *entry)
  3766. {
  3767. struct page *page = NULL;
  3768. struct inode *inode;
  3769. struct address_space *mapping;
  3770. pgoff_t pgoff;
  3771. if (!vma->vm_file) /* anonymous vma */
  3772. return NULL;
  3773. if (!move_file())
  3774. return NULL;
  3775. inode = vma->vm_file->f_path.dentry->d_inode;
  3776. mapping = vma->vm_file->f_mapping;
  3777. if (pte_none(ptent))
  3778. pgoff = linear_page_index(vma, addr);
  3779. else /* pte_file(ptent) is true */
  3780. pgoff = pte_to_pgoff(ptent);
  3781. /* page is moved even if it's not RSS of this task(page-faulted). */
  3782. if (!mapping_cap_swap_backed(mapping)) { /* normal file */
  3783. page = find_get_page(mapping, pgoff);
  3784. } else { /* shmem/tmpfs file. we should take account of swap too. */
  3785. swp_entry_t ent;
  3786. mem_cgroup_get_shmem_target(inode, pgoff, &page, &ent);
  3787. if (do_swap_account)
  3788. entry->val = ent.val;
  3789. }
  3790. return page;
  3791. }
  3792. static int is_target_pte_for_mc(struct vm_area_struct *vma,
  3793. unsigned long addr, pte_t ptent, union mc_target *target)
  3794. {
  3795. struct page *page = NULL;
  3796. struct page_cgroup *pc;
  3797. int ret = 0;
  3798. swp_entry_t ent = { .val = 0 };
  3799. if (pte_present(ptent))
  3800. page = mc_handle_present_pte(vma, addr, ptent);
  3801. else if (is_swap_pte(ptent))
  3802. page = mc_handle_swap_pte(vma, addr, ptent, &ent);
  3803. else if (pte_none(ptent) || pte_file(ptent))
  3804. page = mc_handle_file_pte(vma, addr, ptent, &ent);
  3805. if (!page && !ent.val)
  3806. return 0;
  3807. if (page) {
  3808. pc = lookup_page_cgroup(page);
  3809. /*
  3810. * Do only loose check w/o page_cgroup lock.
  3811. * mem_cgroup_move_account() checks the pc is valid or not under
  3812. * the lock.
  3813. */
  3814. if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
  3815. ret = MC_TARGET_PAGE;
  3816. if (target)
  3817. target->page = page;
  3818. }
  3819. if (!ret || !target)
  3820. put_page(page);
  3821. }
  3822. /* There is a swap entry and a page doesn't exist or isn't charged */
  3823. if (ent.val && !ret &&
  3824. css_id(&mc.from->css) == lookup_swap_cgroup(ent)) {
  3825. ret = MC_TARGET_SWAP;
  3826. if (target)
  3827. target->ent = ent;
  3828. }
  3829. return ret;
  3830. }
  3831. static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
  3832. unsigned long addr, unsigned long end,
  3833. struct mm_walk *walk)
  3834. {
  3835. struct vm_area_struct *vma = walk->private;
  3836. pte_t *pte;
  3837. spinlock_t *ptl;
  3838. pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
  3839. for (; addr != end; pte++, addr += PAGE_SIZE)
  3840. if (is_target_pte_for_mc(vma, addr, *pte, NULL))
  3841. mc.precharge++; /* increment precharge temporarily */
  3842. pte_unmap_unlock(pte - 1, ptl);
  3843. cond_resched();
  3844. return 0;
  3845. }
  3846. static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
  3847. {
  3848. unsigned long precharge;
  3849. struct vm_area_struct *vma;
  3850. down_read(&mm->mmap_sem);
  3851. for (vma = mm->mmap; vma; vma = vma->vm_next) {
  3852. struct mm_walk mem_cgroup_count_precharge_walk = {
  3853. .pmd_entry = mem_cgroup_count_precharge_pte_range,
  3854. .mm = mm,
  3855. .private = vma,
  3856. };
  3857. if (is_vm_hugetlb_page(vma))
  3858. continue;
  3859. walk_page_range(vma->vm_start, vma->vm_end,
  3860. &mem_cgroup_count_precharge_walk);
  3861. }
  3862. up_read(&mm->mmap_sem);
  3863. precharge = mc.precharge;
  3864. mc.precharge = 0;
  3865. return precharge;
  3866. }
  3867. static int mem_cgroup_precharge_mc(struct mm_struct *mm)
  3868. {
  3869. return mem_cgroup_do_precharge(mem_cgroup_count_precharge(mm));
  3870. }
  3871. static void mem_cgroup_clear_mc(void)
  3872. {
  3873. /* we must uncharge all the leftover precharges from mc.to */
  3874. if (mc.precharge) {
  3875. __mem_cgroup_cancel_charge(mc.to, mc.precharge);
  3876. mc.precharge = 0;
  3877. memcg_oom_recover(mc.to);
  3878. }
  3879. /*
  3880. * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
  3881. * we must uncharge here.
  3882. */
  3883. if (mc.moved_charge) {
  3884. __mem_cgroup_cancel_charge(mc.from, mc.moved_charge);
  3885. mc.moved_charge = 0;
  3886. memcg_oom_recover(mc.from);
  3887. }
  3888. /* we must fixup refcnts and charges */
  3889. if (mc.moved_swap) {
  3890. WARN_ON_ONCE(mc.moved_swap > INT_MAX);
  3891. /* uncharge swap account from the old cgroup */
  3892. if (!mem_cgroup_is_root(mc.from))
  3893. res_counter_uncharge(&mc.from->memsw,
  3894. PAGE_SIZE * mc.moved_swap);
  3895. __mem_cgroup_put(mc.from, mc.moved_swap);
  3896. if (!mem_cgroup_is_root(mc.to)) {
  3897. /*
  3898. * we charged both to->res and to->memsw, so we should
  3899. * uncharge to->res.
  3900. */
  3901. res_counter_uncharge(&mc.to->res,
  3902. PAGE_SIZE * mc.moved_swap);
  3903. VM_BUG_ON(test_bit(CSS_ROOT, &mc.to->css.flags));
  3904. __css_put(&mc.to->css, mc.moved_swap);
  3905. }
  3906. /* we've already done mem_cgroup_get(mc.to) */
  3907. mc.moved_swap = 0;
  3908. }
  3909. mc.from = NULL;
  3910. mc.to = NULL;
  3911. mc.moving_task = NULL;
  3912. wake_up_all(&mc.waitq);
  3913. }
  3914. static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
  3915. struct cgroup *cgroup,
  3916. struct task_struct *p,
  3917. bool threadgroup)
  3918. {
  3919. int ret = 0;
  3920. struct mem_cgroup *mem = mem_cgroup_from_cont(cgroup);
  3921. if (mem->move_charge_at_immigrate) {
  3922. struct mm_struct *mm;
  3923. struct mem_cgroup *from = mem_cgroup_from_task(p);
  3924. VM_BUG_ON(from == mem);
  3925. mm = get_task_mm(p);
  3926. if (!mm)
  3927. return 0;
  3928. /* We move charges only when we move a owner of the mm */
  3929. if (mm->owner == p) {
  3930. VM_BUG_ON(mc.from);
  3931. VM_BUG_ON(mc.to);
  3932. VM_BUG_ON(mc.precharge);
  3933. VM_BUG_ON(mc.moved_charge);
  3934. VM_BUG_ON(mc.moved_swap);
  3935. VM_BUG_ON(mc.moving_task);
  3936. mc.from = from;
  3937. mc.to = mem;
  3938. mc.precharge = 0;
  3939. mc.moved_charge = 0;
  3940. mc.moved_swap = 0;
  3941. mc.moving_task = current;
  3942. ret = mem_cgroup_precharge_mc(mm);
  3943. if (ret)
  3944. mem_cgroup_clear_mc();
  3945. }
  3946. mmput(mm);
  3947. }
  3948. return ret;
  3949. }
  3950. static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
  3951. struct cgroup *cgroup,
  3952. struct task_struct *p,
  3953. bool threadgroup)
  3954. {
  3955. mem_cgroup_clear_mc();
  3956. }
  3957. static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
  3958. unsigned long addr, unsigned long end,
  3959. struct mm_walk *walk)
  3960. {
  3961. int ret = 0;
  3962. struct vm_area_struct *vma = walk->private;
  3963. pte_t *pte;
  3964. spinlock_t *ptl;
  3965. retry:
  3966. pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
  3967. for (; addr != end; addr += PAGE_SIZE) {
  3968. pte_t ptent = *(pte++);
  3969. union mc_target target;
  3970. int type;
  3971. struct page *page;
  3972. struct page_cgroup *pc;
  3973. swp_entry_t ent;
  3974. if (!mc.precharge)
  3975. break;
  3976. type = is_target_pte_for_mc(vma, addr, ptent, &target);
  3977. switch (type) {
  3978. case MC_TARGET_PAGE:
  3979. page = target.page;
  3980. if (isolate_lru_page(page))
  3981. goto put;
  3982. pc = lookup_page_cgroup(page);
  3983. if (!mem_cgroup_move_account(pc,
  3984. mc.from, mc.to, false)) {
  3985. mc.precharge--;
  3986. /* we uncharge from mc.from later. */
  3987. mc.moved_charge++;
  3988. }
  3989. putback_lru_page(page);
  3990. put: /* is_target_pte_for_mc() gets the page */
  3991. put_page(page);
  3992. break;
  3993. case MC_TARGET_SWAP:
  3994. ent = target.ent;
  3995. if (!mem_cgroup_move_swap_account(ent,
  3996. mc.from, mc.to, false)) {
  3997. mc.precharge--;
  3998. /* we fixup refcnts and charges later. */
  3999. mc.moved_swap++;
  4000. }
  4001. break;
  4002. default:
  4003. break;
  4004. }
  4005. }
  4006. pte_unmap_unlock(pte - 1, ptl);
  4007. cond_resched();
  4008. if (addr != end) {
  4009. /*
  4010. * We have consumed all precharges we got in can_attach().
  4011. * We try charge one by one, but don't do any additional
  4012. * charges to mc.to if we have failed in charge once in attach()
  4013. * phase.
  4014. */
  4015. ret = mem_cgroup_do_precharge(1);
  4016. if (!ret)
  4017. goto retry;
  4018. }
  4019. return ret;
  4020. }
  4021. static void mem_cgroup_move_charge(struct mm_struct *mm)
  4022. {
  4023. struct vm_area_struct *vma;
  4024. lru_add_drain_all();
  4025. down_read(&mm->mmap_sem);
  4026. for (vma = mm->mmap; vma; vma = vma->vm_next) {
  4027. int ret;
  4028. struct mm_walk mem_cgroup_move_charge_walk = {
  4029. .pmd_entry = mem_cgroup_move_charge_pte_range,
  4030. .mm = mm,
  4031. .private = vma,
  4032. };
  4033. if (is_vm_hugetlb_page(vma))
  4034. continue;
  4035. ret = walk_page_range(vma->vm_start, vma->vm_end,
  4036. &mem_cgroup_move_charge_walk);
  4037. if (ret)
  4038. /*
  4039. * means we have consumed all precharges and failed in
  4040. * doing additional charge. Just abandon here.
  4041. */
  4042. break;
  4043. }
  4044. up_read(&mm->mmap_sem);
  4045. }
  4046. static void mem_cgroup_move_task(struct cgroup_subsys *ss,
  4047. struct cgroup *cont,
  4048. struct cgroup *old_cont,
  4049. struct task_struct *p,
  4050. bool threadgroup)
  4051. {
  4052. struct mm_struct *mm;
  4053. if (!mc.to)
  4054. /* no need to move charge */
  4055. return;
  4056. mm = get_task_mm(p);
  4057. if (mm) {
  4058. mem_cgroup_move_charge(mm);
  4059. mmput(mm);
  4060. }
  4061. mem_cgroup_clear_mc();
  4062. }
  4063. #else /* !CONFIG_MMU */
  4064. static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
  4065. struct cgroup *cgroup,
  4066. struct task_struct *p,
  4067. bool threadgroup)
  4068. {
  4069. return 0;
  4070. }
  4071. static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
  4072. struct cgroup *cgroup,
  4073. struct task_struct *p,
  4074. bool threadgroup)
  4075. {
  4076. }
  4077. static void mem_cgroup_move_task(struct cgroup_subsys *ss,
  4078. struct cgroup *cont,
  4079. struct cgroup *old_cont,
  4080. struct task_struct *p,
  4081. bool threadgroup)
  4082. {
  4083. }
  4084. #endif
  4085. struct cgroup_subsys mem_cgroup_subsys = {
  4086. .name = "memory",
  4087. .subsys_id = mem_cgroup_subsys_id,
  4088. .create = mem_cgroup_create,
  4089. .pre_destroy = mem_cgroup_pre_destroy,
  4090. .destroy = mem_cgroup_destroy,
  4091. .populate = mem_cgroup_populate,
  4092. .can_attach = mem_cgroup_can_attach,
  4093. .cancel_attach = mem_cgroup_cancel_attach,
  4094. .attach = mem_cgroup_move_task,
  4095. .early_init = 0,
  4096. .use_id = 1,
  4097. };
  4098. #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
  4099. static int __init disable_swap_account(char *s)
  4100. {
  4101. really_do_swap_account = 0;
  4102. return 1;
  4103. }
  4104. __setup("noswapaccount", disable_swap_account);
  4105. #endif