memcontrol.c 119 KB

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