memcontrol.c 118 KB

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