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