memcontrol.c 118 KB

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