memcontrol.c 119 KB

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