memcontrol.c 118 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644
  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. * Return the memory (and swap, if configured) limit for a memcg.
  972. */
  973. u64 mem_cgroup_get_limit(struct mem_cgroup *memcg)
  974. {
  975. u64 limit;
  976. u64 memsw;
  977. limit = res_counter_read_u64(&memcg->res, RES_LIMIT) +
  978. total_swap_pages;
  979. memsw = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
  980. /*
  981. * If memsw is finite and limits the amount of swap space available
  982. * to this memcg, return that limit.
  983. */
  984. return min(limit, memsw);
  985. }
  986. /*
  987. * Visit the first child (need not be the first child as per the ordering
  988. * of the cgroup list, since we track last_scanned_child) of @mem and use
  989. * that to reclaim free pages from.
  990. */
  991. static struct mem_cgroup *
  992. mem_cgroup_select_victim(struct mem_cgroup *root_mem)
  993. {
  994. struct mem_cgroup *ret = NULL;
  995. struct cgroup_subsys_state *css;
  996. int nextid, found;
  997. if (!root_mem->use_hierarchy) {
  998. css_get(&root_mem->css);
  999. ret = root_mem;
  1000. }
  1001. while (!ret) {
  1002. rcu_read_lock();
  1003. nextid = root_mem->last_scanned_child + 1;
  1004. css = css_get_next(&mem_cgroup_subsys, nextid, &root_mem->css,
  1005. &found);
  1006. if (css && css_tryget(css))
  1007. ret = container_of(css, struct mem_cgroup, css);
  1008. rcu_read_unlock();
  1009. /* Updates scanning parameter */
  1010. spin_lock(&root_mem->reclaim_param_lock);
  1011. if (!css) {
  1012. /* this means start scan from ID:1 */
  1013. root_mem->last_scanned_child = 0;
  1014. } else
  1015. root_mem->last_scanned_child = found;
  1016. spin_unlock(&root_mem->reclaim_param_lock);
  1017. }
  1018. return ret;
  1019. }
  1020. /*
  1021. * Scan the hierarchy if needed to reclaim memory. We remember the last child
  1022. * we reclaimed from, so that we don't end up penalizing one child extensively
  1023. * based on its position in the children list.
  1024. *
  1025. * root_mem is the original ancestor that we've been reclaim from.
  1026. *
  1027. * We give up and return to the caller when we visit root_mem twice.
  1028. * (other groups can be removed while we're walking....)
  1029. *
  1030. * If shrink==true, for avoiding to free too much, this returns immedieately.
  1031. */
  1032. static int mem_cgroup_hierarchical_reclaim(struct mem_cgroup *root_mem,
  1033. struct zone *zone,
  1034. gfp_t gfp_mask,
  1035. unsigned long reclaim_options)
  1036. {
  1037. struct mem_cgroup *victim;
  1038. int ret, total = 0;
  1039. int loop = 0;
  1040. bool noswap = reclaim_options & MEM_CGROUP_RECLAIM_NOSWAP;
  1041. bool shrink = reclaim_options & MEM_CGROUP_RECLAIM_SHRINK;
  1042. bool check_soft = reclaim_options & MEM_CGROUP_RECLAIM_SOFT;
  1043. unsigned long excess = mem_cgroup_get_excess(root_mem);
  1044. /* If memsw_is_minimum==1, swap-out is of-no-use. */
  1045. if (root_mem->memsw_is_minimum)
  1046. noswap = true;
  1047. while (1) {
  1048. victim = mem_cgroup_select_victim(root_mem);
  1049. if (victim == root_mem) {
  1050. loop++;
  1051. if (loop >= 1)
  1052. drain_all_stock_async();
  1053. if (loop >= 2) {
  1054. /*
  1055. * If we have not been able to reclaim
  1056. * anything, it might because there are
  1057. * no reclaimable pages under this hierarchy
  1058. */
  1059. if (!check_soft || !total) {
  1060. css_put(&victim->css);
  1061. break;
  1062. }
  1063. /*
  1064. * We want to do more targetted reclaim.
  1065. * excess >> 2 is not to excessive so as to
  1066. * reclaim too much, nor too less that we keep
  1067. * coming back to reclaim from this cgroup
  1068. */
  1069. if (total >= (excess >> 2) ||
  1070. (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS)) {
  1071. css_put(&victim->css);
  1072. break;
  1073. }
  1074. }
  1075. }
  1076. if (!mem_cgroup_local_usage(victim)) {
  1077. /* this cgroup's local usage == 0 */
  1078. css_put(&victim->css);
  1079. continue;
  1080. }
  1081. /* we use swappiness of local cgroup */
  1082. if (check_soft)
  1083. ret = mem_cgroup_shrink_node_zone(victim, gfp_mask,
  1084. noswap, get_swappiness(victim), zone,
  1085. zone->zone_pgdat->node_id);
  1086. else
  1087. ret = try_to_free_mem_cgroup_pages(victim, gfp_mask,
  1088. noswap, get_swappiness(victim));
  1089. css_put(&victim->css);
  1090. /*
  1091. * At shrinking usage, we can't check we should stop here or
  1092. * reclaim more. It's depends on callers. last_scanned_child
  1093. * will work enough for keeping fairness under tree.
  1094. */
  1095. if (shrink)
  1096. return ret;
  1097. total += ret;
  1098. if (check_soft) {
  1099. if (res_counter_check_under_soft_limit(&root_mem->res))
  1100. return total;
  1101. } else if (mem_cgroup_check_under_limit(root_mem))
  1102. return 1 + total;
  1103. }
  1104. return total;
  1105. }
  1106. static int mem_cgroup_oom_lock_cb(struct mem_cgroup *mem, void *data)
  1107. {
  1108. int *val = (int *)data;
  1109. int x;
  1110. /*
  1111. * Logically, we can stop scanning immediately when we find
  1112. * a memcg is already locked. But condidering unlock ops and
  1113. * creation/removal of memcg, scan-all is simple operation.
  1114. */
  1115. x = atomic_inc_return(&mem->oom_lock);
  1116. *val = max(x, *val);
  1117. return 0;
  1118. }
  1119. /*
  1120. * Check OOM-Killer is already running under our hierarchy.
  1121. * If someone is running, return false.
  1122. */
  1123. static bool mem_cgroup_oom_lock(struct mem_cgroup *mem)
  1124. {
  1125. int lock_count = 0;
  1126. mem_cgroup_walk_tree(mem, &lock_count, mem_cgroup_oom_lock_cb);
  1127. if (lock_count == 1)
  1128. return true;
  1129. return false;
  1130. }
  1131. static int mem_cgroup_oom_unlock_cb(struct mem_cgroup *mem, void *data)
  1132. {
  1133. /*
  1134. * When a new child is created while the hierarchy is under oom,
  1135. * mem_cgroup_oom_lock() may not be called. We have to use
  1136. * atomic_add_unless() here.
  1137. */
  1138. atomic_add_unless(&mem->oom_lock, -1, 0);
  1139. return 0;
  1140. }
  1141. static void mem_cgroup_oom_unlock(struct mem_cgroup *mem)
  1142. {
  1143. mem_cgroup_walk_tree(mem, NULL, mem_cgroup_oom_unlock_cb);
  1144. }
  1145. static DEFINE_MUTEX(memcg_oom_mutex);
  1146. static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
  1147. struct oom_wait_info {
  1148. struct mem_cgroup *mem;
  1149. wait_queue_t wait;
  1150. };
  1151. static int memcg_oom_wake_function(wait_queue_t *wait,
  1152. unsigned mode, int sync, void *arg)
  1153. {
  1154. struct mem_cgroup *wake_mem = (struct mem_cgroup *)arg;
  1155. struct oom_wait_info *oom_wait_info;
  1156. oom_wait_info = container_of(wait, struct oom_wait_info, wait);
  1157. if (oom_wait_info->mem == wake_mem)
  1158. goto wakeup;
  1159. /* if no hierarchy, no match */
  1160. if (!oom_wait_info->mem->use_hierarchy || !wake_mem->use_hierarchy)
  1161. return 0;
  1162. /*
  1163. * Both of oom_wait_info->mem and wake_mem are stable under us.
  1164. * Then we can use css_is_ancestor without taking care of RCU.
  1165. */
  1166. if (!css_is_ancestor(&oom_wait_info->mem->css, &wake_mem->css) &&
  1167. !css_is_ancestor(&wake_mem->css, &oom_wait_info->mem->css))
  1168. return 0;
  1169. wakeup:
  1170. return autoremove_wake_function(wait, mode, sync, arg);
  1171. }
  1172. static void memcg_wakeup_oom(struct mem_cgroup *mem)
  1173. {
  1174. /* for filtering, pass "mem" as argument. */
  1175. __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, mem);
  1176. }
  1177. static void memcg_oom_recover(struct mem_cgroup *mem)
  1178. {
  1179. if (atomic_read(&mem->oom_lock))
  1180. memcg_wakeup_oom(mem);
  1181. }
  1182. /*
  1183. * try to call OOM killer. returns false if we should exit memory-reclaim loop.
  1184. */
  1185. bool mem_cgroup_handle_oom(struct mem_cgroup *mem, gfp_t mask)
  1186. {
  1187. struct oom_wait_info owait;
  1188. bool locked, need_to_kill;
  1189. owait.mem = mem;
  1190. owait.wait.flags = 0;
  1191. owait.wait.func = memcg_oom_wake_function;
  1192. owait.wait.private = current;
  1193. INIT_LIST_HEAD(&owait.wait.task_list);
  1194. need_to_kill = true;
  1195. /* At first, try to OOM lock hierarchy under mem.*/
  1196. mutex_lock(&memcg_oom_mutex);
  1197. locked = mem_cgroup_oom_lock(mem);
  1198. /*
  1199. * Even if signal_pending(), we can't quit charge() loop without
  1200. * accounting. So, UNINTERRUPTIBLE is appropriate. But SIGKILL
  1201. * under OOM is always welcomed, use TASK_KILLABLE here.
  1202. */
  1203. prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
  1204. if (!locked || mem->oom_kill_disable)
  1205. need_to_kill = false;
  1206. if (locked)
  1207. mem_cgroup_oom_notify(mem);
  1208. mutex_unlock(&memcg_oom_mutex);
  1209. if (need_to_kill) {
  1210. finish_wait(&memcg_oom_waitq, &owait.wait);
  1211. mem_cgroup_out_of_memory(mem, mask);
  1212. } else {
  1213. schedule();
  1214. finish_wait(&memcg_oom_waitq, &owait.wait);
  1215. }
  1216. mutex_lock(&memcg_oom_mutex);
  1217. mem_cgroup_oom_unlock(mem);
  1218. memcg_wakeup_oom(mem);
  1219. mutex_unlock(&memcg_oom_mutex);
  1220. if (test_thread_flag(TIF_MEMDIE) || fatal_signal_pending(current))
  1221. return false;
  1222. /* Give chance to dying process */
  1223. schedule_timeout(1);
  1224. return true;
  1225. }
  1226. /*
  1227. * Currently used to update mapped file statistics, but the routine can be
  1228. * generalized to update other statistics as well.
  1229. */
  1230. void mem_cgroup_update_file_mapped(struct page *page, int val)
  1231. {
  1232. struct mem_cgroup *mem;
  1233. struct page_cgroup *pc;
  1234. pc = lookup_page_cgroup(page);
  1235. if (unlikely(!pc))
  1236. return;
  1237. lock_page_cgroup(pc);
  1238. mem = pc->mem_cgroup;
  1239. if (!mem || !PageCgroupUsed(pc))
  1240. goto done;
  1241. /*
  1242. * Preemption is already disabled. We can use __this_cpu_xxx
  1243. */
  1244. if (val > 0) {
  1245. __this_cpu_inc(mem->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
  1246. SetPageCgroupFileMapped(pc);
  1247. } else {
  1248. __this_cpu_dec(mem->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
  1249. ClearPageCgroupFileMapped(pc);
  1250. }
  1251. done:
  1252. unlock_page_cgroup(pc);
  1253. }
  1254. /*
  1255. * size of first charge trial. "32" comes from vmscan.c's magic value.
  1256. * TODO: maybe necessary to use big numbers in big irons.
  1257. */
  1258. #define CHARGE_SIZE (32 * PAGE_SIZE)
  1259. struct memcg_stock_pcp {
  1260. struct mem_cgroup *cached; /* this never be root cgroup */
  1261. int charge;
  1262. struct work_struct work;
  1263. };
  1264. static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
  1265. static atomic_t memcg_drain_count;
  1266. /*
  1267. * Try to consume stocked charge on this cpu. If success, PAGE_SIZE is consumed
  1268. * from local stock and true is returned. If the stock is 0 or charges from a
  1269. * cgroup which is not current target, returns false. This stock will be
  1270. * refilled.
  1271. */
  1272. static bool consume_stock(struct mem_cgroup *mem)
  1273. {
  1274. struct memcg_stock_pcp *stock;
  1275. bool ret = true;
  1276. stock = &get_cpu_var(memcg_stock);
  1277. if (mem == stock->cached && stock->charge)
  1278. stock->charge -= PAGE_SIZE;
  1279. else /* need to call res_counter_charge */
  1280. ret = false;
  1281. put_cpu_var(memcg_stock);
  1282. return ret;
  1283. }
  1284. /*
  1285. * Returns stocks cached in percpu to res_counter and reset cached information.
  1286. */
  1287. static void drain_stock(struct memcg_stock_pcp *stock)
  1288. {
  1289. struct mem_cgroup *old = stock->cached;
  1290. if (stock->charge) {
  1291. res_counter_uncharge(&old->res, stock->charge);
  1292. if (do_swap_account)
  1293. res_counter_uncharge(&old->memsw, stock->charge);
  1294. }
  1295. stock->cached = NULL;
  1296. stock->charge = 0;
  1297. }
  1298. /*
  1299. * This must be called under preempt disabled or must be called by
  1300. * a thread which is pinned to local cpu.
  1301. */
  1302. static void drain_local_stock(struct work_struct *dummy)
  1303. {
  1304. struct memcg_stock_pcp *stock = &__get_cpu_var(memcg_stock);
  1305. drain_stock(stock);
  1306. }
  1307. /*
  1308. * Cache charges(val) which is from res_counter, to local per_cpu area.
  1309. * This will be consumed by consume_stock() function, later.
  1310. */
  1311. static void refill_stock(struct mem_cgroup *mem, int val)
  1312. {
  1313. struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock);
  1314. if (stock->cached != mem) { /* reset if necessary */
  1315. drain_stock(stock);
  1316. stock->cached = mem;
  1317. }
  1318. stock->charge += val;
  1319. put_cpu_var(memcg_stock);
  1320. }
  1321. /*
  1322. * Tries to drain stocked charges in other cpus. This function is asynchronous
  1323. * and just put a work per cpu for draining localy on each cpu. Caller can
  1324. * expects some charges will be back to res_counter later but cannot wait for
  1325. * it.
  1326. */
  1327. static void drain_all_stock_async(void)
  1328. {
  1329. int cpu;
  1330. /* This function is for scheduling "drain" in asynchronous way.
  1331. * The result of "drain" is not directly handled by callers. Then,
  1332. * if someone is calling drain, we don't have to call drain more.
  1333. * Anyway, WORK_STRUCT_PENDING check in queue_work_on() will catch if
  1334. * there is a race. We just do loose check here.
  1335. */
  1336. if (atomic_read(&memcg_drain_count))
  1337. return;
  1338. /* Notify other cpus that system-wide "drain" is running */
  1339. atomic_inc(&memcg_drain_count);
  1340. get_online_cpus();
  1341. for_each_online_cpu(cpu) {
  1342. struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
  1343. schedule_work_on(cpu, &stock->work);
  1344. }
  1345. put_online_cpus();
  1346. atomic_dec(&memcg_drain_count);
  1347. /* We don't wait for flush_work */
  1348. }
  1349. /* This is a synchronous drain interface. */
  1350. static void drain_all_stock_sync(void)
  1351. {
  1352. /* called when force_empty is called */
  1353. atomic_inc(&memcg_drain_count);
  1354. schedule_on_each_cpu(drain_local_stock);
  1355. atomic_dec(&memcg_drain_count);
  1356. }
  1357. static int __cpuinit memcg_stock_cpu_callback(struct notifier_block *nb,
  1358. unsigned long action,
  1359. void *hcpu)
  1360. {
  1361. int cpu = (unsigned long)hcpu;
  1362. struct memcg_stock_pcp *stock;
  1363. if (action != CPU_DEAD)
  1364. return NOTIFY_OK;
  1365. stock = &per_cpu(memcg_stock, cpu);
  1366. drain_stock(stock);
  1367. return NOTIFY_OK;
  1368. }
  1369. /*
  1370. * Unlike exported interface, "oom" parameter is added. if oom==true,
  1371. * oom-killer can be invoked.
  1372. */
  1373. static int __mem_cgroup_try_charge(struct mm_struct *mm,
  1374. gfp_t gfp_mask, struct mem_cgroup **memcg, bool oom)
  1375. {
  1376. struct mem_cgroup *mem, *mem_over_limit;
  1377. int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
  1378. struct res_counter *fail_res;
  1379. int csize = CHARGE_SIZE;
  1380. /*
  1381. * Unlike gloval-vm's OOM-kill, we're not in memory shortage
  1382. * in system level. So, allow to go ahead dying process in addition to
  1383. * MEMDIE process.
  1384. */
  1385. if (unlikely(test_thread_flag(TIF_MEMDIE)
  1386. || fatal_signal_pending(current)))
  1387. goto bypass;
  1388. /*
  1389. * We always charge the cgroup the mm_struct belongs to.
  1390. * The mm_struct's mem_cgroup changes on task migration if the
  1391. * thread group leader migrates. It's possible that mm is not
  1392. * set, if so charge the init_mm (happens for pagecache usage).
  1393. */
  1394. mem = *memcg;
  1395. if (likely(!mem)) {
  1396. mem = try_get_mem_cgroup_from_mm(mm);
  1397. *memcg = mem;
  1398. } else {
  1399. css_get(&mem->css);
  1400. }
  1401. if (unlikely(!mem))
  1402. return 0;
  1403. VM_BUG_ON(css_is_removed(&mem->css));
  1404. if (mem_cgroup_is_root(mem))
  1405. goto done;
  1406. while (1) {
  1407. int ret = 0;
  1408. unsigned long flags = 0;
  1409. if (consume_stock(mem))
  1410. goto done;
  1411. ret = res_counter_charge(&mem->res, csize, &fail_res);
  1412. if (likely(!ret)) {
  1413. if (!do_swap_account)
  1414. break;
  1415. ret = res_counter_charge(&mem->memsw, csize, &fail_res);
  1416. if (likely(!ret))
  1417. break;
  1418. /* mem+swap counter fails */
  1419. res_counter_uncharge(&mem->res, csize);
  1420. flags |= MEM_CGROUP_RECLAIM_NOSWAP;
  1421. mem_over_limit = mem_cgroup_from_res_counter(fail_res,
  1422. memsw);
  1423. } else
  1424. /* mem counter fails */
  1425. mem_over_limit = mem_cgroup_from_res_counter(fail_res,
  1426. res);
  1427. /* reduce request size and retry */
  1428. if (csize > PAGE_SIZE) {
  1429. csize = PAGE_SIZE;
  1430. continue;
  1431. }
  1432. if (!(gfp_mask & __GFP_WAIT))
  1433. goto nomem;
  1434. ret = mem_cgroup_hierarchical_reclaim(mem_over_limit, NULL,
  1435. gfp_mask, flags);
  1436. if (ret)
  1437. continue;
  1438. /*
  1439. * try_to_free_mem_cgroup_pages() might not give us a full
  1440. * picture of reclaim. Some pages are reclaimed and might be
  1441. * moved to swap cache or just unmapped from the cgroup.
  1442. * Check the limit again to see if the reclaim reduced the
  1443. * current usage of the cgroup before giving up
  1444. *
  1445. */
  1446. if (mem_cgroup_check_under_limit(mem_over_limit))
  1447. continue;
  1448. /* try to avoid oom while someone is moving charge */
  1449. if (mc.moving_task && current != mc.moving_task) {
  1450. struct mem_cgroup *from, *to;
  1451. bool do_continue = false;
  1452. /*
  1453. * There is a small race that "from" or "to" can be
  1454. * freed by rmdir, so we use css_tryget().
  1455. */
  1456. from = mc.from;
  1457. to = mc.to;
  1458. if (from && css_tryget(&from->css)) {
  1459. if (mem_over_limit->use_hierarchy)
  1460. do_continue = css_is_ancestor(
  1461. &from->css,
  1462. &mem_over_limit->css);
  1463. else
  1464. do_continue = (from == mem_over_limit);
  1465. css_put(&from->css);
  1466. }
  1467. if (!do_continue && to && css_tryget(&to->css)) {
  1468. if (mem_over_limit->use_hierarchy)
  1469. do_continue = css_is_ancestor(
  1470. &to->css,
  1471. &mem_over_limit->css);
  1472. else
  1473. do_continue = (to == mem_over_limit);
  1474. css_put(&to->css);
  1475. }
  1476. if (do_continue) {
  1477. DEFINE_WAIT(wait);
  1478. prepare_to_wait(&mc.waitq, &wait,
  1479. TASK_INTERRUPTIBLE);
  1480. /* moving charge context might have finished. */
  1481. if (mc.moving_task)
  1482. schedule();
  1483. finish_wait(&mc.waitq, &wait);
  1484. continue;
  1485. }
  1486. }
  1487. if (!nr_retries--) {
  1488. if (!oom)
  1489. goto nomem;
  1490. if (mem_cgroup_handle_oom(mem_over_limit, gfp_mask)) {
  1491. nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
  1492. continue;
  1493. }
  1494. /* When we reach here, current task is dying .*/
  1495. css_put(&mem->css);
  1496. goto bypass;
  1497. }
  1498. }
  1499. if (csize > PAGE_SIZE)
  1500. refill_stock(mem, csize - PAGE_SIZE);
  1501. done:
  1502. return 0;
  1503. nomem:
  1504. css_put(&mem->css);
  1505. return -ENOMEM;
  1506. bypass:
  1507. *memcg = NULL;
  1508. return 0;
  1509. }
  1510. /*
  1511. * Somemtimes we have to undo a charge we got by try_charge().
  1512. * This function is for that and do uncharge, put css's refcnt.
  1513. * gotten by try_charge().
  1514. */
  1515. static void __mem_cgroup_cancel_charge(struct mem_cgroup *mem,
  1516. unsigned long count)
  1517. {
  1518. if (!mem_cgroup_is_root(mem)) {
  1519. res_counter_uncharge(&mem->res, PAGE_SIZE * count);
  1520. if (do_swap_account)
  1521. res_counter_uncharge(&mem->memsw, PAGE_SIZE * count);
  1522. VM_BUG_ON(test_bit(CSS_ROOT, &mem->css.flags));
  1523. WARN_ON_ONCE(count > INT_MAX);
  1524. __css_put(&mem->css, (int)count);
  1525. }
  1526. /* we don't need css_put for root */
  1527. }
  1528. static void mem_cgroup_cancel_charge(struct mem_cgroup *mem)
  1529. {
  1530. __mem_cgroup_cancel_charge(mem, 1);
  1531. }
  1532. /*
  1533. * A helper function to get mem_cgroup from ID. must be called under
  1534. * rcu_read_lock(). The caller must check css_is_removed() or some if
  1535. * it's concern. (dropping refcnt from swap can be called against removed
  1536. * memcg.)
  1537. */
  1538. static struct mem_cgroup *mem_cgroup_lookup(unsigned short id)
  1539. {
  1540. struct cgroup_subsys_state *css;
  1541. /* ID 0 is unused ID */
  1542. if (!id)
  1543. return NULL;
  1544. css = css_lookup(&mem_cgroup_subsys, id);
  1545. if (!css)
  1546. return NULL;
  1547. return container_of(css, struct mem_cgroup, css);
  1548. }
  1549. struct mem_cgroup *try_get_mem_cgroup_from_page(struct page *page)
  1550. {
  1551. struct mem_cgroup *mem = NULL;
  1552. struct page_cgroup *pc;
  1553. unsigned short id;
  1554. swp_entry_t ent;
  1555. VM_BUG_ON(!PageLocked(page));
  1556. pc = lookup_page_cgroup(page);
  1557. lock_page_cgroup(pc);
  1558. if (PageCgroupUsed(pc)) {
  1559. mem = pc->mem_cgroup;
  1560. if (mem && !css_tryget(&mem->css))
  1561. mem = NULL;
  1562. } else if (PageSwapCache(page)) {
  1563. ent.val = page_private(page);
  1564. id = lookup_swap_cgroup(ent);
  1565. rcu_read_lock();
  1566. mem = mem_cgroup_lookup(id);
  1567. if (mem && !css_tryget(&mem->css))
  1568. mem = NULL;
  1569. rcu_read_unlock();
  1570. }
  1571. unlock_page_cgroup(pc);
  1572. return mem;
  1573. }
  1574. /*
  1575. * commit a charge got by __mem_cgroup_try_charge() and makes page_cgroup to be
  1576. * USED state. If already USED, uncharge and return.
  1577. */
  1578. static void __mem_cgroup_commit_charge(struct mem_cgroup *mem,
  1579. struct page_cgroup *pc,
  1580. enum charge_type ctype)
  1581. {
  1582. /* try_charge() can return NULL to *memcg, taking care of it. */
  1583. if (!mem)
  1584. return;
  1585. lock_page_cgroup(pc);
  1586. if (unlikely(PageCgroupUsed(pc))) {
  1587. unlock_page_cgroup(pc);
  1588. mem_cgroup_cancel_charge(mem);
  1589. return;
  1590. }
  1591. pc->mem_cgroup = mem;
  1592. /*
  1593. * We access a page_cgroup asynchronously without lock_page_cgroup().
  1594. * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
  1595. * is accessed after testing USED bit. To make pc->mem_cgroup visible
  1596. * before USED bit, we need memory barrier here.
  1597. * See mem_cgroup_add_lru_list(), etc.
  1598. */
  1599. smp_wmb();
  1600. switch (ctype) {
  1601. case MEM_CGROUP_CHARGE_TYPE_CACHE:
  1602. case MEM_CGROUP_CHARGE_TYPE_SHMEM:
  1603. SetPageCgroupCache(pc);
  1604. SetPageCgroupUsed(pc);
  1605. break;
  1606. case MEM_CGROUP_CHARGE_TYPE_MAPPED:
  1607. ClearPageCgroupCache(pc);
  1608. SetPageCgroupUsed(pc);
  1609. break;
  1610. default:
  1611. break;
  1612. }
  1613. mem_cgroup_charge_statistics(mem, pc, true);
  1614. unlock_page_cgroup(pc);
  1615. /*
  1616. * "charge_statistics" updated event counter. Then, check it.
  1617. * Insert ancestor (and ancestor's ancestors), to softlimit RB-tree.
  1618. * if they exceeds softlimit.
  1619. */
  1620. memcg_check_events(mem, pc->page);
  1621. }
  1622. /**
  1623. * __mem_cgroup_move_account - move account of the page
  1624. * @pc: page_cgroup of the page.
  1625. * @from: mem_cgroup which the page is moved from.
  1626. * @to: mem_cgroup which the page is moved to. @from != @to.
  1627. * @uncharge: whether we should call uncharge and css_put against @from.
  1628. *
  1629. * The caller must confirm following.
  1630. * - page is not on LRU (isolate_page() is useful.)
  1631. * - the pc is locked, used, and ->mem_cgroup points to @from.
  1632. *
  1633. * This function doesn't do "charge" nor css_get to new cgroup. It should be
  1634. * done by a caller(__mem_cgroup_try_charge would be usefull). If @uncharge is
  1635. * true, this function does "uncharge" from old cgroup, but it doesn't if
  1636. * @uncharge is false, so a caller should do "uncharge".
  1637. */
  1638. static void __mem_cgroup_move_account(struct page_cgroup *pc,
  1639. struct mem_cgroup *from, struct mem_cgroup *to, bool uncharge)
  1640. {
  1641. VM_BUG_ON(from == to);
  1642. VM_BUG_ON(PageLRU(pc->page));
  1643. VM_BUG_ON(!PageCgroupLocked(pc));
  1644. VM_BUG_ON(!PageCgroupUsed(pc));
  1645. VM_BUG_ON(pc->mem_cgroup != from);
  1646. if (PageCgroupFileMapped(pc)) {
  1647. /* Update mapped_file data for mem_cgroup */
  1648. preempt_disable();
  1649. __this_cpu_dec(from->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
  1650. __this_cpu_inc(to->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
  1651. preempt_enable();
  1652. }
  1653. mem_cgroup_charge_statistics(from, pc, false);
  1654. if (uncharge)
  1655. /* This is not "cancel", but cancel_charge does all we need. */
  1656. mem_cgroup_cancel_charge(from);
  1657. /* caller should have done css_get */
  1658. pc->mem_cgroup = to;
  1659. mem_cgroup_charge_statistics(to, pc, true);
  1660. /*
  1661. * We charges against "to" which may not have any tasks. Then, "to"
  1662. * can be under rmdir(). But in current implementation, caller of
  1663. * this function is just force_empty() and move charge, so it's
  1664. * garanteed that "to" is never removed. So, we don't check rmdir
  1665. * status here.
  1666. */
  1667. }
  1668. /*
  1669. * check whether the @pc is valid for moving account and call
  1670. * __mem_cgroup_move_account()
  1671. */
  1672. static int mem_cgroup_move_account(struct page_cgroup *pc,
  1673. struct mem_cgroup *from, struct mem_cgroup *to, bool uncharge)
  1674. {
  1675. int ret = -EINVAL;
  1676. lock_page_cgroup(pc);
  1677. if (PageCgroupUsed(pc) && pc->mem_cgroup == from) {
  1678. __mem_cgroup_move_account(pc, from, to, uncharge);
  1679. ret = 0;
  1680. }
  1681. unlock_page_cgroup(pc);
  1682. /*
  1683. * check events
  1684. */
  1685. memcg_check_events(to, pc->page);
  1686. memcg_check_events(from, pc->page);
  1687. return ret;
  1688. }
  1689. /*
  1690. * move charges to its parent.
  1691. */
  1692. static int mem_cgroup_move_parent(struct page_cgroup *pc,
  1693. struct mem_cgroup *child,
  1694. gfp_t gfp_mask)
  1695. {
  1696. struct page *page = pc->page;
  1697. struct cgroup *cg = child->css.cgroup;
  1698. struct cgroup *pcg = cg->parent;
  1699. struct mem_cgroup *parent;
  1700. int ret;
  1701. /* Is ROOT ? */
  1702. if (!pcg)
  1703. return -EINVAL;
  1704. ret = -EBUSY;
  1705. if (!get_page_unless_zero(page))
  1706. goto out;
  1707. if (isolate_lru_page(page))
  1708. goto put;
  1709. parent = mem_cgroup_from_cont(pcg);
  1710. ret = __mem_cgroup_try_charge(NULL, gfp_mask, &parent, false);
  1711. if (ret || !parent)
  1712. goto put_back;
  1713. ret = mem_cgroup_move_account(pc, child, parent, true);
  1714. if (ret)
  1715. mem_cgroup_cancel_charge(parent);
  1716. put_back:
  1717. putback_lru_page(page);
  1718. put:
  1719. put_page(page);
  1720. out:
  1721. return ret;
  1722. }
  1723. /*
  1724. * Charge the memory controller for page usage.
  1725. * Return
  1726. * 0 if the charge was successful
  1727. * < 0 if the cgroup is over its limit
  1728. */
  1729. static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
  1730. gfp_t gfp_mask, enum charge_type ctype,
  1731. struct mem_cgroup *memcg)
  1732. {
  1733. struct mem_cgroup *mem;
  1734. struct page_cgroup *pc;
  1735. int ret;
  1736. pc = lookup_page_cgroup(page);
  1737. /* can happen at boot */
  1738. if (unlikely(!pc))
  1739. return 0;
  1740. prefetchw(pc);
  1741. mem = memcg;
  1742. ret = __mem_cgroup_try_charge(mm, gfp_mask, &mem, true);
  1743. if (ret || !mem)
  1744. return ret;
  1745. __mem_cgroup_commit_charge(mem, pc, ctype);
  1746. return 0;
  1747. }
  1748. int mem_cgroup_newpage_charge(struct page *page,
  1749. struct mm_struct *mm, gfp_t gfp_mask)
  1750. {
  1751. if (mem_cgroup_disabled())
  1752. return 0;
  1753. if (PageCompound(page))
  1754. return 0;
  1755. /*
  1756. * If already mapped, we don't have to account.
  1757. * If page cache, page->mapping has address_space.
  1758. * But page->mapping may have out-of-use anon_vma pointer,
  1759. * detecit it by PageAnon() check. newly-mapped-anon's page->mapping
  1760. * is NULL.
  1761. */
  1762. if (page_mapped(page) || (page->mapping && !PageAnon(page)))
  1763. return 0;
  1764. if (unlikely(!mm))
  1765. mm = &init_mm;
  1766. return mem_cgroup_charge_common(page, mm, gfp_mask,
  1767. MEM_CGROUP_CHARGE_TYPE_MAPPED, NULL);
  1768. }
  1769. static void
  1770. __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
  1771. enum charge_type ctype);
  1772. int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
  1773. gfp_t gfp_mask)
  1774. {
  1775. struct mem_cgroup *mem = NULL;
  1776. int ret;
  1777. if (mem_cgroup_disabled())
  1778. return 0;
  1779. if (PageCompound(page))
  1780. return 0;
  1781. /*
  1782. * Corner case handling. This is called from add_to_page_cache()
  1783. * in usual. But some FS (shmem) precharges this page before calling it
  1784. * and call add_to_page_cache() with GFP_NOWAIT.
  1785. *
  1786. * For GFP_NOWAIT case, the page may be pre-charged before calling
  1787. * add_to_page_cache(). (See shmem.c) check it here and avoid to call
  1788. * charge twice. (It works but has to pay a bit larger cost.)
  1789. * And when the page is SwapCache, it should take swap information
  1790. * into account. This is under lock_page() now.
  1791. */
  1792. if (!(gfp_mask & __GFP_WAIT)) {
  1793. struct page_cgroup *pc;
  1794. pc = lookup_page_cgroup(page);
  1795. if (!pc)
  1796. return 0;
  1797. lock_page_cgroup(pc);
  1798. if (PageCgroupUsed(pc)) {
  1799. unlock_page_cgroup(pc);
  1800. return 0;
  1801. }
  1802. unlock_page_cgroup(pc);
  1803. }
  1804. if (unlikely(!mm && !mem))
  1805. mm = &init_mm;
  1806. if (page_is_file_cache(page))
  1807. return mem_cgroup_charge_common(page, mm, gfp_mask,
  1808. MEM_CGROUP_CHARGE_TYPE_CACHE, NULL);
  1809. /* shmem */
  1810. if (PageSwapCache(page)) {
  1811. ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &mem);
  1812. if (!ret)
  1813. __mem_cgroup_commit_charge_swapin(page, mem,
  1814. MEM_CGROUP_CHARGE_TYPE_SHMEM);
  1815. } else
  1816. ret = mem_cgroup_charge_common(page, mm, gfp_mask,
  1817. MEM_CGROUP_CHARGE_TYPE_SHMEM, mem);
  1818. return ret;
  1819. }
  1820. /*
  1821. * While swap-in, try_charge -> commit or cancel, the page is locked.
  1822. * And when try_charge() successfully returns, one refcnt to memcg without
  1823. * struct page_cgroup is acquired. This refcnt will be consumed by
  1824. * "commit()" or removed by "cancel()"
  1825. */
  1826. int mem_cgroup_try_charge_swapin(struct mm_struct *mm,
  1827. struct page *page,
  1828. gfp_t mask, struct mem_cgroup **ptr)
  1829. {
  1830. struct mem_cgroup *mem;
  1831. int ret;
  1832. if (mem_cgroup_disabled())
  1833. return 0;
  1834. if (!do_swap_account)
  1835. goto charge_cur_mm;
  1836. /*
  1837. * A racing thread's fault, or swapoff, may have already updated
  1838. * the pte, and even removed page from swap cache: in those cases
  1839. * do_swap_page()'s pte_same() test will fail; but there's also a
  1840. * KSM case which does need to charge the page.
  1841. */
  1842. if (!PageSwapCache(page))
  1843. goto charge_cur_mm;
  1844. mem = try_get_mem_cgroup_from_page(page);
  1845. if (!mem)
  1846. goto charge_cur_mm;
  1847. *ptr = mem;
  1848. ret = __mem_cgroup_try_charge(NULL, mask, ptr, true);
  1849. /* drop extra refcnt from tryget */
  1850. css_put(&mem->css);
  1851. return ret;
  1852. charge_cur_mm:
  1853. if (unlikely(!mm))
  1854. mm = &init_mm;
  1855. return __mem_cgroup_try_charge(mm, mask, ptr, true);
  1856. }
  1857. static void
  1858. __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
  1859. enum charge_type ctype)
  1860. {
  1861. struct page_cgroup *pc;
  1862. if (mem_cgroup_disabled())
  1863. return;
  1864. if (!ptr)
  1865. return;
  1866. cgroup_exclude_rmdir(&ptr->css);
  1867. pc = lookup_page_cgroup(page);
  1868. mem_cgroup_lru_del_before_commit_swapcache(page);
  1869. __mem_cgroup_commit_charge(ptr, pc, ctype);
  1870. mem_cgroup_lru_add_after_commit_swapcache(page);
  1871. /*
  1872. * Now swap is on-memory. This means this page may be
  1873. * counted both as mem and swap....double count.
  1874. * Fix it by uncharging from memsw. Basically, this SwapCache is stable
  1875. * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
  1876. * may call delete_from_swap_cache() before reach here.
  1877. */
  1878. if (do_swap_account && PageSwapCache(page)) {
  1879. swp_entry_t ent = {.val = page_private(page)};
  1880. unsigned short id;
  1881. struct mem_cgroup *memcg;
  1882. id = swap_cgroup_record(ent, 0);
  1883. rcu_read_lock();
  1884. memcg = mem_cgroup_lookup(id);
  1885. if (memcg) {
  1886. /*
  1887. * This recorded memcg can be obsolete one. So, avoid
  1888. * calling css_tryget
  1889. */
  1890. if (!mem_cgroup_is_root(memcg))
  1891. res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
  1892. mem_cgroup_swap_statistics(memcg, false);
  1893. mem_cgroup_put(memcg);
  1894. }
  1895. rcu_read_unlock();
  1896. }
  1897. /*
  1898. * At swapin, we may charge account against cgroup which has no tasks.
  1899. * So, rmdir()->pre_destroy() can be called while we do this charge.
  1900. * In that case, we need to call pre_destroy() again. check it here.
  1901. */
  1902. cgroup_release_and_wakeup_rmdir(&ptr->css);
  1903. }
  1904. void mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr)
  1905. {
  1906. __mem_cgroup_commit_charge_swapin(page, ptr,
  1907. MEM_CGROUP_CHARGE_TYPE_MAPPED);
  1908. }
  1909. void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *mem)
  1910. {
  1911. if (mem_cgroup_disabled())
  1912. return;
  1913. if (!mem)
  1914. return;
  1915. mem_cgroup_cancel_charge(mem);
  1916. }
  1917. static void
  1918. __do_uncharge(struct mem_cgroup *mem, const enum charge_type ctype)
  1919. {
  1920. struct memcg_batch_info *batch = NULL;
  1921. bool uncharge_memsw = true;
  1922. /* If swapout, usage of swap doesn't decrease */
  1923. if (!do_swap_account || ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
  1924. uncharge_memsw = false;
  1925. batch = &current->memcg_batch;
  1926. /*
  1927. * In usual, we do css_get() when we remember memcg pointer.
  1928. * But in this case, we keep res->usage until end of a series of
  1929. * uncharges. Then, it's ok to ignore memcg's refcnt.
  1930. */
  1931. if (!batch->memcg)
  1932. batch->memcg = mem;
  1933. /*
  1934. * do_batch > 0 when unmapping pages or inode invalidate/truncate.
  1935. * In those cases, all pages freed continously can be expected to be in
  1936. * the same cgroup and we have chance to coalesce uncharges.
  1937. * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE)
  1938. * because we want to do uncharge as soon as possible.
  1939. */
  1940. if (!batch->do_batch || test_thread_flag(TIF_MEMDIE))
  1941. goto direct_uncharge;
  1942. /*
  1943. * In typical case, batch->memcg == mem. This means we can
  1944. * merge a series of uncharges to an uncharge of res_counter.
  1945. * If not, we uncharge res_counter ony by one.
  1946. */
  1947. if (batch->memcg != mem)
  1948. goto direct_uncharge;
  1949. /* remember freed charge and uncharge it later */
  1950. batch->bytes += PAGE_SIZE;
  1951. if (uncharge_memsw)
  1952. batch->memsw_bytes += PAGE_SIZE;
  1953. return;
  1954. direct_uncharge:
  1955. res_counter_uncharge(&mem->res, PAGE_SIZE);
  1956. if (uncharge_memsw)
  1957. res_counter_uncharge(&mem->memsw, PAGE_SIZE);
  1958. if (unlikely(batch->memcg != mem))
  1959. memcg_oom_recover(mem);
  1960. return;
  1961. }
  1962. /*
  1963. * uncharge if !page_mapped(page)
  1964. */
  1965. static struct mem_cgroup *
  1966. __mem_cgroup_uncharge_common(struct page *page, enum charge_type ctype)
  1967. {
  1968. struct page_cgroup *pc;
  1969. struct mem_cgroup *mem = NULL;
  1970. struct mem_cgroup_per_zone *mz;
  1971. if (mem_cgroup_disabled())
  1972. return NULL;
  1973. if (PageSwapCache(page))
  1974. return NULL;
  1975. /*
  1976. * Check if our page_cgroup is valid
  1977. */
  1978. pc = lookup_page_cgroup(page);
  1979. if (unlikely(!pc || !PageCgroupUsed(pc)))
  1980. return NULL;
  1981. lock_page_cgroup(pc);
  1982. mem = pc->mem_cgroup;
  1983. if (!PageCgroupUsed(pc))
  1984. goto unlock_out;
  1985. switch (ctype) {
  1986. case MEM_CGROUP_CHARGE_TYPE_MAPPED:
  1987. case MEM_CGROUP_CHARGE_TYPE_DROP:
  1988. /* See mem_cgroup_prepare_migration() */
  1989. if (page_mapped(page) || PageCgroupMigration(pc))
  1990. goto unlock_out;
  1991. break;
  1992. case MEM_CGROUP_CHARGE_TYPE_SWAPOUT:
  1993. if (!PageAnon(page)) { /* Shared memory */
  1994. if (page->mapping && !page_is_file_cache(page))
  1995. goto unlock_out;
  1996. } else if (page_mapped(page)) /* Anon */
  1997. goto unlock_out;
  1998. break;
  1999. default:
  2000. break;
  2001. }
  2002. if (!mem_cgroup_is_root(mem))
  2003. __do_uncharge(mem, ctype);
  2004. if (ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
  2005. mem_cgroup_swap_statistics(mem, true);
  2006. mem_cgroup_charge_statistics(mem, pc, false);
  2007. ClearPageCgroupUsed(pc);
  2008. /*
  2009. * pc->mem_cgroup is not cleared here. It will be accessed when it's
  2010. * freed from LRU. This is safe because uncharged page is expected not
  2011. * to be reused (freed soon). Exception is SwapCache, it's handled by
  2012. * special functions.
  2013. */
  2014. mz = page_cgroup_zoneinfo(pc);
  2015. unlock_page_cgroup(pc);
  2016. memcg_check_events(mem, page);
  2017. /* at swapout, this memcg will be accessed to record to swap */
  2018. if (ctype != MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
  2019. css_put(&mem->css);
  2020. return mem;
  2021. unlock_out:
  2022. unlock_page_cgroup(pc);
  2023. return NULL;
  2024. }
  2025. void mem_cgroup_uncharge_page(struct page *page)
  2026. {
  2027. /* early check. */
  2028. if (page_mapped(page))
  2029. return;
  2030. if (page->mapping && !PageAnon(page))
  2031. return;
  2032. __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_MAPPED);
  2033. }
  2034. void mem_cgroup_uncharge_cache_page(struct page *page)
  2035. {
  2036. VM_BUG_ON(page_mapped(page));
  2037. VM_BUG_ON(page->mapping);
  2038. __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_CACHE);
  2039. }
  2040. /*
  2041. * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate.
  2042. * In that cases, pages are freed continuously and we can expect pages
  2043. * are in the same memcg. All these calls itself limits the number of
  2044. * pages freed at once, then uncharge_start/end() is called properly.
  2045. * This may be called prural(2) times in a context,
  2046. */
  2047. void mem_cgroup_uncharge_start(void)
  2048. {
  2049. current->memcg_batch.do_batch++;
  2050. /* We can do nest. */
  2051. if (current->memcg_batch.do_batch == 1) {
  2052. current->memcg_batch.memcg = NULL;
  2053. current->memcg_batch.bytes = 0;
  2054. current->memcg_batch.memsw_bytes = 0;
  2055. }
  2056. }
  2057. void mem_cgroup_uncharge_end(void)
  2058. {
  2059. struct memcg_batch_info *batch = &current->memcg_batch;
  2060. if (!batch->do_batch)
  2061. return;
  2062. batch->do_batch--;
  2063. if (batch->do_batch) /* If stacked, do nothing. */
  2064. return;
  2065. if (!batch->memcg)
  2066. return;
  2067. /*
  2068. * This "batch->memcg" is valid without any css_get/put etc...
  2069. * bacause we hide charges behind us.
  2070. */
  2071. if (batch->bytes)
  2072. res_counter_uncharge(&batch->memcg->res, batch->bytes);
  2073. if (batch->memsw_bytes)
  2074. res_counter_uncharge(&batch->memcg->memsw, batch->memsw_bytes);
  2075. memcg_oom_recover(batch->memcg);
  2076. /* forget this pointer (for sanity check) */
  2077. batch->memcg = NULL;
  2078. }
  2079. #ifdef CONFIG_SWAP
  2080. /*
  2081. * called after __delete_from_swap_cache() and drop "page" account.
  2082. * memcg information is recorded to swap_cgroup of "ent"
  2083. */
  2084. void
  2085. mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout)
  2086. {
  2087. struct mem_cgroup *memcg;
  2088. int ctype = MEM_CGROUP_CHARGE_TYPE_SWAPOUT;
  2089. if (!swapout) /* this was a swap cache but the swap is unused ! */
  2090. ctype = MEM_CGROUP_CHARGE_TYPE_DROP;
  2091. memcg = __mem_cgroup_uncharge_common(page, ctype);
  2092. /* record memcg information */
  2093. if (do_swap_account && swapout && memcg) {
  2094. swap_cgroup_record(ent, css_id(&memcg->css));
  2095. mem_cgroup_get(memcg);
  2096. }
  2097. if (swapout && memcg)
  2098. css_put(&memcg->css);
  2099. }
  2100. #endif
  2101. #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
  2102. /*
  2103. * called from swap_entry_free(). remove record in swap_cgroup and
  2104. * uncharge "memsw" account.
  2105. */
  2106. void mem_cgroup_uncharge_swap(swp_entry_t ent)
  2107. {
  2108. struct mem_cgroup *memcg;
  2109. unsigned short id;
  2110. if (!do_swap_account)
  2111. return;
  2112. id = swap_cgroup_record(ent, 0);
  2113. rcu_read_lock();
  2114. memcg = mem_cgroup_lookup(id);
  2115. if (memcg) {
  2116. /*
  2117. * We uncharge this because swap is freed.
  2118. * This memcg can be obsolete one. We avoid calling css_tryget
  2119. */
  2120. if (!mem_cgroup_is_root(memcg))
  2121. res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
  2122. mem_cgroup_swap_statistics(memcg, false);
  2123. mem_cgroup_put(memcg);
  2124. }
  2125. rcu_read_unlock();
  2126. }
  2127. /**
  2128. * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
  2129. * @entry: swap entry to be moved
  2130. * @from: mem_cgroup which the entry is moved from
  2131. * @to: mem_cgroup which the entry is moved to
  2132. * @need_fixup: whether we should fixup res_counters and refcounts.
  2133. *
  2134. * It succeeds only when the swap_cgroup's record for this entry is the same
  2135. * as the mem_cgroup's id of @from.
  2136. *
  2137. * Returns 0 on success, -EINVAL on failure.
  2138. *
  2139. * The caller must have charged to @to, IOW, called res_counter_charge() about
  2140. * both res and memsw, and called css_get().
  2141. */
  2142. static int mem_cgroup_move_swap_account(swp_entry_t entry,
  2143. struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
  2144. {
  2145. unsigned short old_id, new_id;
  2146. old_id = css_id(&from->css);
  2147. new_id = css_id(&to->css);
  2148. if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
  2149. mem_cgroup_swap_statistics(from, false);
  2150. mem_cgroup_swap_statistics(to, true);
  2151. /*
  2152. * This function is only called from task migration context now.
  2153. * It postpones res_counter and refcount handling till the end
  2154. * of task migration(mem_cgroup_clear_mc()) for performance
  2155. * improvement. But we cannot postpone mem_cgroup_get(to)
  2156. * because if the process that has been moved to @to does
  2157. * swap-in, the refcount of @to might be decreased to 0.
  2158. */
  2159. mem_cgroup_get(to);
  2160. if (need_fixup) {
  2161. if (!mem_cgroup_is_root(from))
  2162. res_counter_uncharge(&from->memsw, PAGE_SIZE);
  2163. mem_cgroup_put(from);
  2164. /*
  2165. * we charged both to->res and to->memsw, so we should
  2166. * uncharge to->res.
  2167. */
  2168. if (!mem_cgroup_is_root(to))
  2169. res_counter_uncharge(&to->res, PAGE_SIZE);
  2170. css_put(&to->css);
  2171. }
  2172. return 0;
  2173. }
  2174. return -EINVAL;
  2175. }
  2176. #else
  2177. static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
  2178. struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
  2179. {
  2180. return -EINVAL;
  2181. }
  2182. #endif
  2183. /*
  2184. * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
  2185. * page belongs to.
  2186. */
  2187. int mem_cgroup_prepare_migration(struct page *page,
  2188. struct page *newpage, struct mem_cgroup **ptr)
  2189. {
  2190. struct page_cgroup *pc;
  2191. struct mem_cgroup *mem = NULL;
  2192. enum charge_type ctype;
  2193. int ret = 0;
  2194. if (mem_cgroup_disabled())
  2195. return 0;
  2196. pc = lookup_page_cgroup(page);
  2197. lock_page_cgroup(pc);
  2198. if (PageCgroupUsed(pc)) {
  2199. mem = pc->mem_cgroup;
  2200. css_get(&mem->css);
  2201. /*
  2202. * At migrating an anonymous page, its mapcount goes down
  2203. * to 0 and uncharge() will be called. But, even if it's fully
  2204. * unmapped, migration may fail and this page has to be
  2205. * charged again. We set MIGRATION flag here and delay uncharge
  2206. * until end_migration() is called
  2207. *
  2208. * Corner Case Thinking
  2209. * A)
  2210. * When the old page was mapped as Anon and it's unmap-and-freed
  2211. * while migration was ongoing.
  2212. * If unmap finds the old page, uncharge() of it will be delayed
  2213. * until end_migration(). If unmap finds a new page, it's
  2214. * uncharged when it make mapcount to be 1->0. If unmap code
  2215. * finds swap_migration_entry, the new page will not be mapped
  2216. * and end_migration() will find it(mapcount==0).
  2217. *
  2218. * B)
  2219. * When the old page was mapped but migraion fails, the kernel
  2220. * remaps it. A charge for it is kept by MIGRATION flag even
  2221. * if mapcount goes down to 0. We can do remap successfully
  2222. * without charging it again.
  2223. *
  2224. * C)
  2225. * The "old" page is under lock_page() until the end of
  2226. * migration, so, the old page itself will not be swapped-out.
  2227. * If the new page is swapped out before end_migraton, our
  2228. * hook to usual swap-out path will catch the event.
  2229. */
  2230. if (PageAnon(page))
  2231. SetPageCgroupMigration(pc);
  2232. }
  2233. unlock_page_cgroup(pc);
  2234. /*
  2235. * If the page is not charged at this point,
  2236. * we return here.
  2237. */
  2238. if (!mem)
  2239. return 0;
  2240. *ptr = mem;
  2241. ret = __mem_cgroup_try_charge(NULL, GFP_KERNEL, ptr, false);
  2242. css_put(&mem->css);/* drop extra refcnt */
  2243. if (ret || *ptr == NULL) {
  2244. if (PageAnon(page)) {
  2245. lock_page_cgroup(pc);
  2246. ClearPageCgroupMigration(pc);
  2247. unlock_page_cgroup(pc);
  2248. /*
  2249. * The old page may be fully unmapped while we kept it.
  2250. */
  2251. mem_cgroup_uncharge_page(page);
  2252. }
  2253. return -ENOMEM;
  2254. }
  2255. /*
  2256. * We charge new page before it's used/mapped. So, even if unlock_page()
  2257. * is called before end_migration, we can catch all events on this new
  2258. * page. In the case new page is migrated but not remapped, new page's
  2259. * mapcount will be finally 0 and we call uncharge in end_migration().
  2260. */
  2261. pc = lookup_page_cgroup(newpage);
  2262. if (PageAnon(page))
  2263. ctype = MEM_CGROUP_CHARGE_TYPE_MAPPED;
  2264. else if (page_is_file_cache(page))
  2265. ctype = MEM_CGROUP_CHARGE_TYPE_CACHE;
  2266. else
  2267. ctype = MEM_CGROUP_CHARGE_TYPE_SHMEM;
  2268. __mem_cgroup_commit_charge(mem, pc, ctype);
  2269. return ret;
  2270. }
  2271. /* remove redundant charge if migration failed*/
  2272. void mem_cgroup_end_migration(struct mem_cgroup *mem,
  2273. struct page *oldpage, struct page *newpage)
  2274. {
  2275. struct page *used, *unused;
  2276. struct page_cgroup *pc;
  2277. if (!mem)
  2278. return;
  2279. /* blocks rmdir() */
  2280. cgroup_exclude_rmdir(&mem->css);
  2281. /* at migration success, oldpage->mapping is NULL. */
  2282. if (oldpage->mapping) {
  2283. used = oldpage;
  2284. unused = newpage;
  2285. } else {
  2286. used = newpage;
  2287. unused = oldpage;
  2288. }
  2289. /*
  2290. * We disallowed uncharge of pages under migration because mapcount
  2291. * of the page goes down to zero, temporarly.
  2292. * Clear the flag and check the page should be charged.
  2293. */
  2294. pc = lookup_page_cgroup(oldpage);
  2295. lock_page_cgroup(pc);
  2296. ClearPageCgroupMigration(pc);
  2297. unlock_page_cgroup(pc);
  2298. if (unused != oldpage)
  2299. pc = lookup_page_cgroup(unused);
  2300. __mem_cgroup_uncharge_common(unused, MEM_CGROUP_CHARGE_TYPE_FORCE);
  2301. pc = lookup_page_cgroup(used);
  2302. /*
  2303. * If a page is a file cache, radix-tree replacement is very atomic
  2304. * and we can skip this check. When it was an Anon page, its mapcount
  2305. * goes down to 0. But because we added MIGRATION flage, it's not
  2306. * uncharged yet. There are several case but page->mapcount check
  2307. * and USED bit check in mem_cgroup_uncharge_page() will do enough
  2308. * check. (see prepare_charge() also)
  2309. */
  2310. if (PageAnon(used))
  2311. mem_cgroup_uncharge_page(used);
  2312. /*
  2313. * At migration, we may charge account against cgroup which has no
  2314. * tasks.
  2315. * So, rmdir()->pre_destroy() can be called while we do this charge.
  2316. * In that case, we need to call pre_destroy() again. check it here.
  2317. */
  2318. cgroup_release_and_wakeup_rmdir(&mem->css);
  2319. }
  2320. /*
  2321. * A call to try to shrink memory usage on charge failure at shmem's swapin.
  2322. * Calling hierarchical_reclaim is not enough because we should update
  2323. * last_oom_jiffies to prevent pagefault_out_of_memory from invoking global OOM.
  2324. * Moreover considering hierarchy, we should reclaim from the mem_over_limit,
  2325. * not from the memcg which this page would be charged to.
  2326. * try_charge_swapin does all of these works properly.
  2327. */
  2328. int mem_cgroup_shmem_charge_fallback(struct page *page,
  2329. struct mm_struct *mm,
  2330. gfp_t gfp_mask)
  2331. {
  2332. struct mem_cgroup *mem = NULL;
  2333. int ret;
  2334. if (mem_cgroup_disabled())
  2335. return 0;
  2336. ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &mem);
  2337. if (!ret)
  2338. mem_cgroup_cancel_charge_swapin(mem); /* it does !mem check */
  2339. return ret;
  2340. }
  2341. static DEFINE_MUTEX(set_limit_mutex);
  2342. static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
  2343. unsigned long long val)
  2344. {
  2345. int retry_count;
  2346. u64 memswlimit, memlimit;
  2347. int ret = 0;
  2348. int children = mem_cgroup_count_children(memcg);
  2349. u64 curusage, oldusage;
  2350. int enlarge;
  2351. /*
  2352. * For keeping hierarchical_reclaim simple, how long we should retry
  2353. * is depends on callers. We set our retry-count to be function
  2354. * of # of children which we should visit in this loop.
  2355. */
  2356. retry_count = MEM_CGROUP_RECLAIM_RETRIES * children;
  2357. oldusage = res_counter_read_u64(&memcg->res, RES_USAGE);
  2358. enlarge = 0;
  2359. while (retry_count) {
  2360. if (signal_pending(current)) {
  2361. ret = -EINTR;
  2362. break;
  2363. }
  2364. /*
  2365. * Rather than hide all in some function, I do this in
  2366. * open coded manner. You see what this really does.
  2367. * We have to guarantee mem->res.limit < mem->memsw.limit.
  2368. */
  2369. mutex_lock(&set_limit_mutex);
  2370. memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
  2371. if (memswlimit < val) {
  2372. ret = -EINVAL;
  2373. mutex_unlock(&set_limit_mutex);
  2374. break;
  2375. }
  2376. memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
  2377. if (memlimit < val)
  2378. enlarge = 1;
  2379. ret = res_counter_set_limit(&memcg->res, val);
  2380. if (!ret) {
  2381. if (memswlimit == val)
  2382. memcg->memsw_is_minimum = true;
  2383. else
  2384. memcg->memsw_is_minimum = false;
  2385. }
  2386. mutex_unlock(&set_limit_mutex);
  2387. if (!ret)
  2388. break;
  2389. mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
  2390. MEM_CGROUP_RECLAIM_SHRINK);
  2391. curusage = res_counter_read_u64(&memcg->res, RES_USAGE);
  2392. /* Usage is reduced ? */
  2393. if (curusage >= oldusage)
  2394. retry_count--;
  2395. else
  2396. oldusage = curusage;
  2397. }
  2398. if (!ret && enlarge)
  2399. memcg_oom_recover(memcg);
  2400. return ret;
  2401. }
  2402. static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
  2403. unsigned long long val)
  2404. {
  2405. int retry_count;
  2406. u64 memlimit, memswlimit, oldusage, curusage;
  2407. int children = mem_cgroup_count_children(memcg);
  2408. int ret = -EBUSY;
  2409. int enlarge = 0;
  2410. /* see mem_cgroup_resize_res_limit */
  2411. retry_count = children * MEM_CGROUP_RECLAIM_RETRIES;
  2412. oldusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
  2413. while (retry_count) {
  2414. if (signal_pending(current)) {
  2415. ret = -EINTR;
  2416. break;
  2417. }
  2418. /*
  2419. * Rather than hide all in some function, I do this in
  2420. * open coded manner. You see what this really does.
  2421. * We have to guarantee mem->res.limit < mem->memsw.limit.
  2422. */
  2423. mutex_lock(&set_limit_mutex);
  2424. memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
  2425. if (memlimit > val) {
  2426. ret = -EINVAL;
  2427. mutex_unlock(&set_limit_mutex);
  2428. break;
  2429. }
  2430. memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
  2431. if (memswlimit < val)
  2432. enlarge = 1;
  2433. ret = res_counter_set_limit(&memcg->memsw, val);
  2434. if (!ret) {
  2435. if (memlimit == val)
  2436. memcg->memsw_is_minimum = true;
  2437. else
  2438. memcg->memsw_is_minimum = false;
  2439. }
  2440. mutex_unlock(&set_limit_mutex);
  2441. if (!ret)
  2442. break;
  2443. mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
  2444. MEM_CGROUP_RECLAIM_NOSWAP |
  2445. MEM_CGROUP_RECLAIM_SHRINK);
  2446. curusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
  2447. /* Usage is reduced ? */
  2448. if (curusage >= oldusage)
  2449. retry_count--;
  2450. else
  2451. oldusage = curusage;
  2452. }
  2453. if (!ret && enlarge)
  2454. memcg_oom_recover(memcg);
  2455. return ret;
  2456. }
  2457. unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
  2458. gfp_t gfp_mask, int nid,
  2459. int zid)
  2460. {
  2461. unsigned long nr_reclaimed = 0;
  2462. struct mem_cgroup_per_zone *mz, *next_mz = NULL;
  2463. unsigned long reclaimed;
  2464. int loop = 0;
  2465. struct mem_cgroup_tree_per_zone *mctz;
  2466. unsigned long long excess;
  2467. if (order > 0)
  2468. return 0;
  2469. mctz = soft_limit_tree_node_zone(nid, zid);
  2470. /*
  2471. * This loop can run a while, specially if mem_cgroup's continuously
  2472. * keep exceeding their soft limit and putting the system under
  2473. * pressure
  2474. */
  2475. do {
  2476. if (next_mz)
  2477. mz = next_mz;
  2478. else
  2479. mz = mem_cgroup_largest_soft_limit_node(mctz);
  2480. if (!mz)
  2481. break;
  2482. reclaimed = mem_cgroup_hierarchical_reclaim(mz->mem, zone,
  2483. gfp_mask,
  2484. MEM_CGROUP_RECLAIM_SOFT);
  2485. nr_reclaimed += reclaimed;
  2486. spin_lock(&mctz->lock);
  2487. /*
  2488. * If we failed to reclaim anything from this memory cgroup
  2489. * it is time to move on to the next cgroup
  2490. */
  2491. next_mz = NULL;
  2492. if (!reclaimed) {
  2493. do {
  2494. /*
  2495. * Loop until we find yet another one.
  2496. *
  2497. * By the time we get the soft_limit lock
  2498. * again, someone might have aded the
  2499. * group back on the RB tree. Iterate to
  2500. * make sure we get a different mem.
  2501. * mem_cgroup_largest_soft_limit_node returns
  2502. * NULL if no other cgroup is present on
  2503. * the tree
  2504. */
  2505. next_mz =
  2506. __mem_cgroup_largest_soft_limit_node(mctz);
  2507. if (next_mz == mz) {
  2508. css_put(&next_mz->mem->css);
  2509. next_mz = NULL;
  2510. } else /* next_mz == NULL or other memcg */
  2511. break;
  2512. } while (1);
  2513. }
  2514. __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
  2515. excess = res_counter_soft_limit_excess(&mz->mem->res);
  2516. /*
  2517. * One school of thought says that we should not add
  2518. * back the node to the tree if reclaim returns 0.
  2519. * But our reclaim could return 0, simply because due
  2520. * to priority we are exposing a smaller subset of
  2521. * memory to reclaim from. Consider this as a longer
  2522. * term TODO.
  2523. */
  2524. /* If excess == 0, no tree ops */
  2525. __mem_cgroup_insert_exceeded(mz->mem, mz, mctz, excess);
  2526. spin_unlock(&mctz->lock);
  2527. css_put(&mz->mem->css);
  2528. loop++;
  2529. /*
  2530. * Could not reclaim anything and there are no more
  2531. * mem cgroups to try or we seem to be looping without
  2532. * reclaiming anything.
  2533. */
  2534. if (!nr_reclaimed &&
  2535. (next_mz == NULL ||
  2536. loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
  2537. break;
  2538. } while (!nr_reclaimed);
  2539. if (next_mz)
  2540. css_put(&next_mz->mem->css);
  2541. return nr_reclaimed;
  2542. }
  2543. /*
  2544. * This routine traverse page_cgroup in given list and drop them all.
  2545. * *And* this routine doesn't reclaim page itself, just removes page_cgroup.
  2546. */
  2547. static int mem_cgroup_force_empty_list(struct mem_cgroup *mem,
  2548. int node, int zid, enum lru_list lru)
  2549. {
  2550. struct zone *zone;
  2551. struct mem_cgroup_per_zone *mz;
  2552. struct page_cgroup *pc, *busy;
  2553. unsigned long flags, loop;
  2554. struct list_head *list;
  2555. int ret = 0;
  2556. zone = &NODE_DATA(node)->node_zones[zid];
  2557. mz = mem_cgroup_zoneinfo(mem, node, zid);
  2558. list = &mz->lists[lru];
  2559. loop = MEM_CGROUP_ZSTAT(mz, lru);
  2560. /* give some margin against EBUSY etc...*/
  2561. loop += 256;
  2562. busy = NULL;
  2563. while (loop--) {
  2564. ret = 0;
  2565. spin_lock_irqsave(&zone->lru_lock, flags);
  2566. if (list_empty(list)) {
  2567. spin_unlock_irqrestore(&zone->lru_lock, flags);
  2568. break;
  2569. }
  2570. pc = list_entry(list->prev, struct page_cgroup, lru);
  2571. if (busy == pc) {
  2572. list_move(&pc->lru, list);
  2573. busy = NULL;
  2574. spin_unlock_irqrestore(&zone->lru_lock, flags);
  2575. continue;
  2576. }
  2577. spin_unlock_irqrestore(&zone->lru_lock, flags);
  2578. ret = mem_cgroup_move_parent(pc, mem, GFP_KERNEL);
  2579. if (ret == -ENOMEM)
  2580. break;
  2581. if (ret == -EBUSY || ret == -EINVAL) {
  2582. /* found lock contention or "pc" is obsolete. */
  2583. busy = pc;
  2584. cond_resched();
  2585. } else
  2586. busy = NULL;
  2587. }
  2588. if (!ret && !list_empty(list))
  2589. return -EBUSY;
  2590. return ret;
  2591. }
  2592. /*
  2593. * make mem_cgroup's charge to be 0 if there is no task.
  2594. * This enables deleting this mem_cgroup.
  2595. */
  2596. static int mem_cgroup_force_empty(struct mem_cgroup *mem, bool free_all)
  2597. {
  2598. int ret;
  2599. int node, zid, shrink;
  2600. int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
  2601. struct cgroup *cgrp = mem->css.cgroup;
  2602. css_get(&mem->css);
  2603. shrink = 0;
  2604. /* should free all ? */
  2605. if (free_all)
  2606. goto try_to_free;
  2607. move_account:
  2608. do {
  2609. ret = -EBUSY;
  2610. if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children))
  2611. goto out;
  2612. ret = -EINTR;
  2613. if (signal_pending(current))
  2614. goto out;
  2615. /* This is for making all *used* pages to be on LRU. */
  2616. lru_add_drain_all();
  2617. drain_all_stock_sync();
  2618. ret = 0;
  2619. for_each_node_state(node, N_HIGH_MEMORY) {
  2620. for (zid = 0; !ret && zid < MAX_NR_ZONES; zid++) {
  2621. enum lru_list l;
  2622. for_each_lru(l) {
  2623. ret = mem_cgroup_force_empty_list(mem,
  2624. node, zid, l);
  2625. if (ret)
  2626. break;
  2627. }
  2628. }
  2629. if (ret)
  2630. break;
  2631. }
  2632. memcg_oom_recover(mem);
  2633. /* it seems parent cgroup doesn't have enough mem */
  2634. if (ret == -ENOMEM)
  2635. goto try_to_free;
  2636. cond_resched();
  2637. /* "ret" should also be checked to ensure all lists are empty. */
  2638. } while (mem->res.usage > 0 || ret);
  2639. out:
  2640. css_put(&mem->css);
  2641. return ret;
  2642. try_to_free:
  2643. /* returns EBUSY if there is a task or if we come here twice. */
  2644. if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children) || shrink) {
  2645. ret = -EBUSY;
  2646. goto out;
  2647. }
  2648. /* we call try-to-free pages for make this cgroup empty */
  2649. lru_add_drain_all();
  2650. /* try to free all pages in this cgroup */
  2651. shrink = 1;
  2652. while (nr_retries && mem->res.usage > 0) {
  2653. int progress;
  2654. if (signal_pending(current)) {
  2655. ret = -EINTR;
  2656. goto out;
  2657. }
  2658. progress = try_to_free_mem_cgroup_pages(mem, GFP_KERNEL,
  2659. false, get_swappiness(mem));
  2660. if (!progress) {
  2661. nr_retries--;
  2662. /* maybe some writeback is necessary */
  2663. congestion_wait(BLK_RW_ASYNC, HZ/10);
  2664. }
  2665. }
  2666. lru_add_drain();
  2667. /* try move_account...there may be some *locked* pages. */
  2668. goto move_account;
  2669. }
  2670. int mem_cgroup_force_empty_write(struct cgroup *cont, unsigned int event)
  2671. {
  2672. return mem_cgroup_force_empty(mem_cgroup_from_cont(cont), true);
  2673. }
  2674. static u64 mem_cgroup_hierarchy_read(struct cgroup *cont, struct cftype *cft)
  2675. {
  2676. return mem_cgroup_from_cont(cont)->use_hierarchy;
  2677. }
  2678. static int mem_cgroup_hierarchy_write(struct cgroup *cont, struct cftype *cft,
  2679. u64 val)
  2680. {
  2681. int retval = 0;
  2682. struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
  2683. struct cgroup *parent = cont->parent;
  2684. struct mem_cgroup *parent_mem = NULL;
  2685. if (parent)
  2686. parent_mem = mem_cgroup_from_cont(parent);
  2687. cgroup_lock();
  2688. /*
  2689. * If parent's use_hierarchy is set, we can't make any modifications
  2690. * in the child subtrees. If it is unset, then the change can
  2691. * occur, provided the current cgroup has no children.
  2692. *
  2693. * For the root cgroup, parent_mem is NULL, we allow value to be
  2694. * set if there are no children.
  2695. */
  2696. if ((!parent_mem || !parent_mem->use_hierarchy) &&
  2697. (val == 1 || val == 0)) {
  2698. if (list_empty(&cont->children))
  2699. mem->use_hierarchy = val;
  2700. else
  2701. retval = -EBUSY;
  2702. } else
  2703. retval = -EINVAL;
  2704. cgroup_unlock();
  2705. return retval;
  2706. }
  2707. struct mem_cgroup_idx_data {
  2708. s64 val;
  2709. enum mem_cgroup_stat_index idx;
  2710. };
  2711. static int
  2712. mem_cgroup_get_idx_stat(struct mem_cgroup *mem, void *data)
  2713. {
  2714. struct mem_cgroup_idx_data *d = data;
  2715. d->val += mem_cgroup_read_stat(mem, d->idx);
  2716. return 0;
  2717. }
  2718. static void
  2719. mem_cgroup_get_recursive_idx_stat(struct mem_cgroup *mem,
  2720. enum mem_cgroup_stat_index idx, s64 *val)
  2721. {
  2722. struct mem_cgroup_idx_data d;
  2723. d.idx = idx;
  2724. d.val = 0;
  2725. mem_cgroup_walk_tree(mem, &d, mem_cgroup_get_idx_stat);
  2726. *val = d.val;
  2727. }
  2728. static inline u64 mem_cgroup_usage(struct mem_cgroup *mem, bool swap)
  2729. {
  2730. u64 idx_val, val;
  2731. if (!mem_cgroup_is_root(mem)) {
  2732. if (!swap)
  2733. return res_counter_read_u64(&mem->res, RES_USAGE);
  2734. else
  2735. return res_counter_read_u64(&mem->memsw, RES_USAGE);
  2736. }
  2737. mem_cgroup_get_recursive_idx_stat(mem, MEM_CGROUP_STAT_CACHE, &idx_val);
  2738. val = idx_val;
  2739. mem_cgroup_get_recursive_idx_stat(mem, MEM_CGROUP_STAT_RSS, &idx_val);
  2740. val += idx_val;
  2741. if (swap) {
  2742. mem_cgroup_get_recursive_idx_stat(mem,
  2743. MEM_CGROUP_STAT_SWAPOUT, &idx_val);
  2744. val += idx_val;
  2745. }
  2746. return val << PAGE_SHIFT;
  2747. }
  2748. static u64 mem_cgroup_read(struct cgroup *cont, struct cftype *cft)
  2749. {
  2750. struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
  2751. u64 val;
  2752. int type, name;
  2753. type = MEMFILE_TYPE(cft->private);
  2754. name = MEMFILE_ATTR(cft->private);
  2755. switch (type) {
  2756. case _MEM:
  2757. if (name == RES_USAGE)
  2758. val = mem_cgroup_usage(mem, false);
  2759. else
  2760. val = res_counter_read_u64(&mem->res, name);
  2761. break;
  2762. case _MEMSWAP:
  2763. if (name == RES_USAGE)
  2764. val = mem_cgroup_usage(mem, true);
  2765. else
  2766. val = res_counter_read_u64(&mem->memsw, name);
  2767. break;
  2768. default:
  2769. BUG();
  2770. break;
  2771. }
  2772. return val;
  2773. }
  2774. /*
  2775. * The user of this function is...
  2776. * RES_LIMIT.
  2777. */
  2778. static int mem_cgroup_write(struct cgroup *cont, struct cftype *cft,
  2779. const char *buffer)
  2780. {
  2781. struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
  2782. int type, name;
  2783. unsigned long long val;
  2784. int ret;
  2785. type = MEMFILE_TYPE(cft->private);
  2786. name = MEMFILE_ATTR(cft->private);
  2787. switch (name) {
  2788. case RES_LIMIT:
  2789. if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
  2790. ret = -EINVAL;
  2791. break;
  2792. }
  2793. /* This function does all necessary parse...reuse it */
  2794. ret = res_counter_memparse_write_strategy(buffer, &val);
  2795. if (ret)
  2796. break;
  2797. if (type == _MEM)
  2798. ret = mem_cgroup_resize_limit(memcg, val);
  2799. else
  2800. ret = mem_cgroup_resize_memsw_limit(memcg, val);
  2801. break;
  2802. case RES_SOFT_LIMIT:
  2803. ret = res_counter_memparse_write_strategy(buffer, &val);
  2804. if (ret)
  2805. break;
  2806. /*
  2807. * For memsw, soft limits are hard to implement in terms
  2808. * of semantics, for now, we support soft limits for
  2809. * control without swap
  2810. */
  2811. if (type == _MEM)
  2812. ret = res_counter_set_soft_limit(&memcg->res, val);
  2813. else
  2814. ret = -EINVAL;
  2815. break;
  2816. default:
  2817. ret = -EINVAL; /* should be BUG() ? */
  2818. break;
  2819. }
  2820. return ret;
  2821. }
  2822. static void memcg_get_hierarchical_limit(struct mem_cgroup *memcg,
  2823. unsigned long long *mem_limit, unsigned long long *memsw_limit)
  2824. {
  2825. struct cgroup *cgroup;
  2826. unsigned long long min_limit, min_memsw_limit, tmp;
  2827. min_limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
  2828. min_memsw_limit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
  2829. cgroup = memcg->css.cgroup;
  2830. if (!memcg->use_hierarchy)
  2831. goto out;
  2832. while (cgroup->parent) {
  2833. cgroup = cgroup->parent;
  2834. memcg = mem_cgroup_from_cont(cgroup);
  2835. if (!memcg->use_hierarchy)
  2836. break;
  2837. tmp = res_counter_read_u64(&memcg->res, RES_LIMIT);
  2838. min_limit = min(min_limit, tmp);
  2839. tmp = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
  2840. min_memsw_limit = min(min_memsw_limit, tmp);
  2841. }
  2842. out:
  2843. *mem_limit = min_limit;
  2844. *memsw_limit = min_memsw_limit;
  2845. return;
  2846. }
  2847. static int mem_cgroup_reset(struct cgroup *cont, unsigned int event)
  2848. {
  2849. struct mem_cgroup *mem;
  2850. int type, name;
  2851. mem = mem_cgroup_from_cont(cont);
  2852. type = MEMFILE_TYPE(event);
  2853. name = MEMFILE_ATTR(event);
  2854. switch (name) {
  2855. case RES_MAX_USAGE:
  2856. if (type == _MEM)
  2857. res_counter_reset_max(&mem->res);
  2858. else
  2859. res_counter_reset_max(&mem->memsw);
  2860. break;
  2861. case RES_FAILCNT:
  2862. if (type == _MEM)
  2863. res_counter_reset_failcnt(&mem->res);
  2864. else
  2865. res_counter_reset_failcnt(&mem->memsw);
  2866. break;
  2867. }
  2868. return 0;
  2869. }
  2870. static u64 mem_cgroup_move_charge_read(struct cgroup *cgrp,
  2871. struct cftype *cft)
  2872. {
  2873. return mem_cgroup_from_cont(cgrp)->move_charge_at_immigrate;
  2874. }
  2875. #ifdef CONFIG_MMU
  2876. static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
  2877. struct cftype *cft, u64 val)
  2878. {
  2879. struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
  2880. if (val >= (1 << NR_MOVE_TYPE))
  2881. return -EINVAL;
  2882. /*
  2883. * We check this value several times in both in can_attach() and
  2884. * attach(), so we need cgroup lock to prevent this value from being
  2885. * inconsistent.
  2886. */
  2887. cgroup_lock();
  2888. mem->move_charge_at_immigrate = val;
  2889. cgroup_unlock();
  2890. return 0;
  2891. }
  2892. #else
  2893. static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
  2894. struct cftype *cft, u64 val)
  2895. {
  2896. return -ENOSYS;
  2897. }
  2898. #endif
  2899. /* For read statistics */
  2900. enum {
  2901. MCS_CACHE,
  2902. MCS_RSS,
  2903. MCS_FILE_MAPPED,
  2904. MCS_PGPGIN,
  2905. MCS_PGPGOUT,
  2906. MCS_SWAP,
  2907. MCS_INACTIVE_ANON,
  2908. MCS_ACTIVE_ANON,
  2909. MCS_INACTIVE_FILE,
  2910. MCS_ACTIVE_FILE,
  2911. MCS_UNEVICTABLE,
  2912. NR_MCS_STAT,
  2913. };
  2914. struct mcs_total_stat {
  2915. s64 stat[NR_MCS_STAT];
  2916. };
  2917. struct {
  2918. char *local_name;
  2919. char *total_name;
  2920. } memcg_stat_strings[NR_MCS_STAT] = {
  2921. {"cache", "total_cache"},
  2922. {"rss", "total_rss"},
  2923. {"mapped_file", "total_mapped_file"},
  2924. {"pgpgin", "total_pgpgin"},
  2925. {"pgpgout", "total_pgpgout"},
  2926. {"swap", "total_swap"},
  2927. {"inactive_anon", "total_inactive_anon"},
  2928. {"active_anon", "total_active_anon"},
  2929. {"inactive_file", "total_inactive_file"},
  2930. {"active_file", "total_active_file"},
  2931. {"unevictable", "total_unevictable"}
  2932. };
  2933. static int mem_cgroup_get_local_stat(struct mem_cgroup *mem, void *data)
  2934. {
  2935. struct mcs_total_stat *s = data;
  2936. s64 val;
  2937. /* per cpu stat */
  2938. val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_CACHE);
  2939. s->stat[MCS_CACHE] += val * PAGE_SIZE;
  2940. val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_RSS);
  2941. s->stat[MCS_RSS] += val * PAGE_SIZE;
  2942. val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_FILE_MAPPED);
  2943. s->stat[MCS_FILE_MAPPED] += val * PAGE_SIZE;
  2944. val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_PGPGIN_COUNT);
  2945. s->stat[MCS_PGPGIN] += val;
  2946. val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_PGPGOUT_COUNT);
  2947. s->stat[MCS_PGPGOUT] += val;
  2948. if (do_swap_account) {
  2949. val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_SWAPOUT);
  2950. s->stat[MCS_SWAP] += val * PAGE_SIZE;
  2951. }
  2952. /* per zone stat */
  2953. val = mem_cgroup_get_local_zonestat(mem, LRU_INACTIVE_ANON);
  2954. s->stat[MCS_INACTIVE_ANON] += val * PAGE_SIZE;
  2955. val = mem_cgroup_get_local_zonestat(mem, LRU_ACTIVE_ANON);
  2956. s->stat[MCS_ACTIVE_ANON] += val * PAGE_SIZE;
  2957. val = mem_cgroup_get_local_zonestat(mem, LRU_INACTIVE_FILE);
  2958. s->stat[MCS_INACTIVE_FILE] += val * PAGE_SIZE;
  2959. val = mem_cgroup_get_local_zonestat(mem, LRU_ACTIVE_FILE);
  2960. s->stat[MCS_ACTIVE_FILE] += val * PAGE_SIZE;
  2961. val = mem_cgroup_get_local_zonestat(mem, LRU_UNEVICTABLE);
  2962. s->stat[MCS_UNEVICTABLE] += val * PAGE_SIZE;
  2963. return 0;
  2964. }
  2965. static void
  2966. mem_cgroup_get_total_stat(struct mem_cgroup *mem, struct mcs_total_stat *s)
  2967. {
  2968. mem_cgroup_walk_tree(mem, s, mem_cgroup_get_local_stat);
  2969. }
  2970. static int mem_control_stat_show(struct cgroup *cont, struct cftype *cft,
  2971. struct cgroup_map_cb *cb)
  2972. {
  2973. struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
  2974. struct mcs_total_stat mystat;
  2975. int i;
  2976. memset(&mystat, 0, sizeof(mystat));
  2977. mem_cgroup_get_local_stat(mem_cont, &mystat);
  2978. for (i = 0; i < NR_MCS_STAT; i++) {
  2979. if (i == MCS_SWAP && !do_swap_account)
  2980. continue;
  2981. cb->fill(cb, memcg_stat_strings[i].local_name, mystat.stat[i]);
  2982. }
  2983. /* Hierarchical information */
  2984. {
  2985. unsigned long long limit, memsw_limit;
  2986. memcg_get_hierarchical_limit(mem_cont, &limit, &memsw_limit);
  2987. cb->fill(cb, "hierarchical_memory_limit", limit);
  2988. if (do_swap_account)
  2989. cb->fill(cb, "hierarchical_memsw_limit", memsw_limit);
  2990. }
  2991. memset(&mystat, 0, sizeof(mystat));
  2992. mem_cgroup_get_total_stat(mem_cont, &mystat);
  2993. for (i = 0; i < NR_MCS_STAT; i++) {
  2994. if (i == MCS_SWAP && !do_swap_account)
  2995. continue;
  2996. cb->fill(cb, memcg_stat_strings[i].total_name, mystat.stat[i]);
  2997. }
  2998. #ifdef CONFIG_DEBUG_VM
  2999. cb->fill(cb, "inactive_ratio", calc_inactive_ratio(mem_cont, NULL));
  3000. {
  3001. int nid, zid;
  3002. struct mem_cgroup_per_zone *mz;
  3003. unsigned long recent_rotated[2] = {0, 0};
  3004. unsigned long recent_scanned[2] = {0, 0};
  3005. for_each_online_node(nid)
  3006. for (zid = 0; zid < MAX_NR_ZONES; zid++) {
  3007. mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
  3008. recent_rotated[0] +=
  3009. mz->reclaim_stat.recent_rotated[0];
  3010. recent_rotated[1] +=
  3011. mz->reclaim_stat.recent_rotated[1];
  3012. recent_scanned[0] +=
  3013. mz->reclaim_stat.recent_scanned[0];
  3014. recent_scanned[1] +=
  3015. mz->reclaim_stat.recent_scanned[1];
  3016. }
  3017. cb->fill(cb, "recent_rotated_anon", recent_rotated[0]);
  3018. cb->fill(cb, "recent_rotated_file", recent_rotated[1]);
  3019. cb->fill(cb, "recent_scanned_anon", recent_scanned[0]);
  3020. cb->fill(cb, "recent_scanned_file", recent_scanned[1]);
  3021. }
  3022. #endif
  3023. return 0;
  3024. }
  3025. static u64 mem_cgroup_swappiness_read(struct cgroup *cgrp, struct cftype *cft)
  3026. {
  3027. struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
  3028. return get_swappiness(memcg);
  3029. }
  3030. static int mem_cgroup_swappiness_write(struct cgroup *cgrp, struct cftype *cft,
  3031. u64 val)
  3032. {
  3033. struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
  3034. struct mem_cgroup *parent;
  3035. if (val > 100)
  3036. return -EINVAL;
  3037. if (cgrp->parent == NULL)
  3038. return -EINVAL;
  3039. parent = mem_cgroup_from_cont(cgrp->parent);
  3040. cgroup_lock();
  3041. /* If under hierarchy, only empty-root can set this value */
  3042. if ((parent->use_hierarchy) ||
  3043. (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
  3044. cgroup_unlock();
  3045. return -EINVAL;
  3046. }
  3047. spin_lock(&memcg->reclaim_param_lock);
  3048. memcg->swappiness = val;
  3049. spin_unlock(&memcg->reclaim_param_lock);
  3050. cgroup_unlock();
  3051. return 0;
  3052. }
  3053. static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
  3054. {
  3055. struct mem_cgroup_threshold_ary *t;
  3056. u64 usage;
  3057. int i;
  3058. rcu_read_lock();
  3059. if (!swap)
  3060. t = rcu_dereference(memcg->thresholds.primary);
  3061. else
  3062. t = rcu_dereference(memcg->memsw_thresholds.primary);
  3063. if (!t)
  3064. goto unlock;
  3065. usage = mem_cgroup_usage(memcg, swap);
  3066. /*
  3067. * current_threshold points to threshold just below usage.
  3068. * If it's not true, a threshold was crossed after last
  3069. * call of __mem_cgroup_threshold().
  3070. */
  3071. i = t->current_threshold;
  3072. /*
  3073. * Iterate backward over array of thresholds starting from
  3074. * current_threshold and check if a threshold is crossed.
  3075. * If none of thresholds below usage is crossed, we read
  3076. * only one element of the array here.
  3077. */
  3078. for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
  3079. eventfd_signal(t->entries[i].eventfd, 1);
  3080. /* i = current_threshold + 1 */
  3081. i++;
  3082. /*
  3083. * Iterate forward over array of thresholds starting from
  3084. * current_threshold+1 and check if a threshold is crossed.
  3085. * If none of thresholds above usage is crossed, we read
  3086. * only one element of the array here.
  3087. */
  3088. for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
  3089. eventfd_signal(t->entries[i].eventfd, 1);
  3090. /* Update current_threshold */
  3091. t->current_threshold = i - 1;
  3092. unlock:
  3093. rcu_read_unlock();
  3094. }
  3095. static void mem_cgroup_threshold(struct mem_cgroup *memcg)
  3096. {
  3097. __mem_cgroup_threshold(memcg, false);
  3098. if (do_swap_account)
  3099. __mem_cgroup_threshold(memcg, true);
  3100. }
  3101. static int compare_thresholds(const void *a, const void *b)
  3102. {
  3103. const struct mem_cgroup_threshold *_a = a;
  3104. const struct mem_cgroup_threshold *_b = b;
  3105. return _a->threshold - _b->threshold;
  3106. }
  3107. static int mem_cgroup_oom_notify_cb(struct mem_cgroup *mem, void *data)
  3108. {
  3109. struct mem_cgroup_eventfd_list *ev;
  3110. list_for_each_entry(ev, &mem->oom_notify, list)
  3111. eventfd_signal(ev->eventfd, 1);
  3112. return 0;
  3113. }
  3114. static void mem_cgroup_oom_notify(struct mem_cgroup *mem)
  3115. {
  3116. mem_cgroup_walk_tree(mem, NULL, mem_cgroup_oom_notify_cb);
  3117. }
  3118. static int mem_cgroup_usage_register_event(struct cgroup *cgrp,
  3119. struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
  3120. {
  3121. struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
  3122. struct mem_cgroup_thresholds *thresholds;
  3123. struct mem_cgroup_threshold_ary *new;
  3124. int type = MEMFILE_TYPE(cft->private);
  3125. u64 threshold, usage;
  3126. int i, size, ret;
  3127. ret = res_counter_memparse_write_strategy(args, &threshold);
  3128. if (ret)
  3129. return ret;
  3130. mutex_lock(&memcg->thresholds_lock);
  3131. if (type == _MEM)
  3132. thresholds = &memcg->thresholds;
  3133. else if (type == _MEMSWAP)
  3134. thresholds = &memcg->memsw_thresholds;
  3135. else
  3136. BUG();
  3137. usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
  3138. /* Check if a threshold crossed before adding a new one */
  3139. if (thresholds->primary)
  3140. __mem_cgroup_threshold(memcg, type == _MEMSWAP);
  3141. size = thresholds->primary ? thresholds->primary->size + 1 : 1;
  3142. /* Allocate memory for new array of thresholds */
  3143. new = kmalloc(sizeof(*new) + size * sizeof(struct mem_cgroup_threshold),
  3144. GFP_KERNEL);
  3145. if (!new) {
  3146. ret = -ENOMEM;
  3147. goto unlock;
  3148. }
  3149. new->size = size;
  3150. /* Copy thresholds (if any) to new array */
  3151. if (thresholds->primary) {
  3152. memcpy(new->entries, thresholds->primary->entries, (size - 1) *
  3153. sizeof(struct mem_cgroup_threshold));
  3154. }
  3155. /* Add new threshold */
  3156. new->entries[size - 1].eventfd = eventfd;
  3157. new->entries[size - 1].threshold = threshold;
  3158. /* Sort thresholds. Registering of new threshold isn't time-critical */
  3159. sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
  3160. compare_thresholds, NULL);
  3161. /* Find current threshold */
  3162. new->current_threshold = -1;
  3163. for (i = 0; i < size; i++) {
  3164. if (new->entries[i].threshold < usage) {
  3165. /*
  3166. * new->current_threshold will not be used until
  3167. * rcu_assign_pointer(), so it's safe to increment
  3168. * it here.
  3169. */
  3170. ++new->current_threshold;
  3171. }
  3172. }
  3173. /* Free old spare buffer and save old primary buffer as spare */
  3174. kfree(thresholds->spare);
  3175. thresholds->spare = thresholds->primary;
  3176. rcu_assign_pointer(thresholds->primary, new);
  3177. /* To be sure that nobody uses thresholds */
  3178. synchronize_rcu();
  3179. unlock:
  3180. mutex_unlock(&memcg->thresholds_lock);
  3181. return ret;
  3182. }
  3183. static void mem_cgroup_usage_unregister_event(struct cgroup *cgrp,
  3184. struct cftype *cft, struct eventfd_ctx *eventfd)
  3185. {
  3186. struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
  3187. struct mem_cgroup_thresholds *thresholds;
  3188. struct mem_cgroup_threshold_ary *new;
  3189. int type = MEMFILE_TYPE(cft->private);
  3190. u64 usage;
  3191. int i, j, size;
  3192. mutex_lock(&memcg->thresholds_lock);
  3193. if (type == _MEM)
  3194. thresholds = &memcg->thresholds;
  3195. else if (type == _MEMSWAP)
  3196. thresholds = &memcg->memsw_thresholds;
  3197. else
  3198. BUG();
  3199. /*
  3200. * Something went wrong if we trying to unregister a threshold
  3201. * if we don't have thresholds
  3202. */
  3203. BUG_ON(!thresholds);
  3204. usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
  3205. /* Check if a threshold crossed before removing */
  3206. __mem_cgroup_threshold(memcg, type == _MEMSWAP);
  3207. /* Calculate new number of threshold */
  3208. size = 0;
  3209. for (i = 0; i < thresholds->primary->size; i++) {
  3210. if (thresholds->primary->entries[i].eventfd != eventfd)
  3211. size++;
  3212. }
  3213. new = thresholds->spare;
  3214. /* Set thresholds array to NULL if we don't have thresholds */
  3215. if (!size) {
  3216. kfree(new);
  3217. new = NULL;
  3218. goto swap_buffers;
  3219. }
  3220. new->size = size;
  3221. /* Copy thresholds and find current threshold */
  3222. new->current_threshold = -1;
  3223. for (i = 0, j = 0; i < thresholds->primary->size; i++) {
  3224. if (thresholds->primary->entries[i].eventfd == eventfd)
  3225. continue;
  3226. new->entries[j] = thresholds->primary->entries[i];
  3227. if (new->entries[j].threshold < usage) {
  3228. /*
  3229. * new->current_threshold will not be used
  3230. * until rcu_assign_pointer(), so it's safe to increment
  3231. * it here.
  3232. */
  3233. ++new->current_threshold;
  3234. }
  3235. j++;
  3236. }
  3237. swap_buffers:
  3238. /* Swap primary and spare array */
  3239. thresholds->spare = thresholds->primary;
  3240. rcu_assign_pointer(thresholds->primary, new);
  3241. /* To be sure that nobody uses thresholds */
  3242. synchronize_rcu();
  3243. mutex_unlock(&memcg->thresholds_lock);
  3244. }
  3245. static int mem_cgroup_oom_register_event(struct cgroup *cgrp,
  3246. struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
  3247. {
  3248. struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
  3249. struct mem_cgroup_eventfd_list *event;
  3250. int type = MEMFILE_TYPE(cft->private);
  3251. BUG_ON(type != _OOM_TYPE);
  3252. event = kmalloc(sizeof(*event), GFP_KERNEL);
  3253. if (!event)
  3254. return -ENOMEM;
  3255. mutex_lock(&memcg_oom_mutex);
  3256. event->eventfd = eventfd;
  3257. list_add(&event->list, &memcg->oom_notify);
  3258. /* already in OOM ? */
  3259. if (atomic_read(&memcg->oom_lock))
  3260. eventfd_signal(eventfd, 1);
  3261. mutex_unlock(&memcg_oom_mutex);
  3262. return 0;
  3263. }
  3264. static void mem_cgroup_oom_unregister_event(struct cgroup *cgrp,
  3265. struct cftype *cft, struct eventfd_ctx *eventfd)
  3266. {
  3267. struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
  3268. struct mem_cgroup_eventfd_list *ev, *tmp;
  3269. int type = MEMFILE_TYPE(cft->private);
  3270. BUG_ON(type != _OOM_TYPE);
  3271. mutex_lock(&memcg_oom_mutex);
  3272. list_for_each_entry_safe(ev, tmp, &mem->oom_notify, list) {
  3273. if (ev->eventfd == eventfd) {
  3274. list_del(&ev->list);
  3275. kfree(ev);
  3276. }
  3277. }
  3278. mutex_unlock(&memcg_oom_mutex);
  3279. }
  3280. static int mem_cgroup_oom_control_read(struct cgroup *cgrp,
  3281. struct cftype *cft, struct cgroup_map_cb *cb)
  3282. {
  3283. struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
  3284. cb->fill(cb, "oom_kill_disable", mem->oom_kill_disable);
  3285. if (atomic_read(&mem->oom_lock))
  3286. cb->fill(cb, "under_oom", 1);
  3287. else
  3288. cb->fill(cb, "under_oom", 0);
  3289. return 0;
  3290. }
  3291. /*
  3292. */
  3293. static int mem_cgroup_oom_control_write(struct cgroup *cgrp,
  3294. struct cftype *cft, u64 val)
  3295. {
  3296. struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
  3297. struct mem_cgroup *parent;
  3298. /* cannot set to root cgroup and only 0 and 1 are allowed */
  3299. if (!cgrp->parent || !((val == 0) || (val == 1)))
  3300. return -EINVAL;
  3301. parent = mem_cgroup_from_cont(cgrp->parent);
  3302. cgroup_lock();
  3303. /* oom-kill-disable is a flag for subhierarchy. */
  3304. if ((parent->use_hierarchy) ||
  3305. (mem->use_hierarchy && !list_empty(&cgrp->children))) {
  3306. cgroup_unlock();
  3307. return -EINVAL;
  3308. }
  3309. mem->oom_kill_disable = val;
  3310. if (!val)
  3311. memcg_oom_recover(mem);
  3312. cgroup_unlock();
  3313. return 0;
  3314. }
  3315. static struct cftype mem_cgroup_files[] = {
  3316. {
  3317. .name = "usage_in_bytes",
  3318. .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
  3319. .read_u64 = mem_cgroup_read,
  3320. .register_event = mem_cgroup_usage_register_event,
  3321. .unregister_event = mem_cgroup_usage_unregister_event,
  3322. },
  3323. {
  3324. .name = "max_usage_in_bytes",
  3325. .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
  3326. .trigger = mem_cgroup_reset,
  3327. .read_u64 = mem_cgroup_read,
  3328. },
  3329. {
  3330. .name = "limit_in_bytes",
  3331. .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
  3332. .write_string = mem_cgroup_write,
  3333. .read_u64 = mem_cgroup_read,
  3334. },
  3335. {
  3336. .name = "soft_limit_in_bytes",
  3337. .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
  3338. .write_string = mem_cgroup_write,
  3339. .read_u64 = mem_cgroup_read,
  3340. },
  3341. {
  3342. .name = "failcnt",
  3343. .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
  3344. .trigger = mem_cgroup_reset,
  3345. .read_u64 = mem_cgroup_read,
  3346. },
  3347. {
  3348. .name = "stat",
  3349. .read_map = mem_control_stat_show,
  3350. },
  3351. {
  3352. .name = "force_empty",
  3353. .trigger = mem_cgroup_force_empty_write,
  3354. },
  3355. {
  3356. .name = "use_hierarchy",
  3357. .write_u64 = mem_cgroup_hierarchy_write,
  3358. .read_u64 = mem_cgroup_hierarchy_read,
  3359. },
  3360. {
  3361. .name = "swappiness",
  3362. .read_u64 = mem_cgroup_swappiness_read,
  3363. .write_u64 = mem_cgroup_swappiness_write,
  3364. },
  3365. {
  3366. .name = "move_charge_at_immigrate",
  3367. .read_u64 = mem_cgroup_move_charge_read,
  3368. .write_u64 = mem_cgroup_move_charge_write,
  3369. },
  3370. {
  3371. .name = "oom_control",
  3372. .read_map = mem_cgroup_oom_control_read,
  3373. .write_u64 = mem_cgroup_oom_control_write,
  3374. .register_event = mem_cgroup_oom_register_event,
  3375. .unregister_event = mem_cgroup_oom_unregister_event,
  3376. .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
  3377. },
  3378. };
  3379. #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
  3380. static struct cftype memsw_cgroup_files[] = {
  3381. {
  3382. .name = "memsw.usage_in_bytes",
  3383. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
  3384. .read_u64 = mem_cgroup_read,
  3385. .register_event = mem_cgroup_usage_register_event,
  3386. .unregister_event = mem_cgroup_usage_unregister_event,
  3387. },
  3388. {
  3389. .name = "memsw.max_usage_in_bytes",
  3390. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
  3391. .trigger = mem_cgroup_reset,
  3392. .read_u64 = mem_cgroup_read,
  3393. },
  3394. {
  3395. .name = "memsw.limit_in_bytes",
  3396. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
  3397. .write_string = mem_cgroup_write,
  3398. .read_u64 = mem_cgroup_read,
  3399. },
  3400. {
  3401. .name = "memsw.failcnt",
  3402. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
  3403. .trigger = mem_cgroup_reset,
  3404. .read_u64 = mem_cgroup_read,
  3405. },
  3406. };
  3407. static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
  3408. {
  3409. if (!do_swap_account)
  3410. return 0;
  3411. return cgroup_add_files(cont, ss, memsw_cgroup_files,
  3412. ARRAY_SIZE(memsw_cgroup_files));
  3413. };
  3414. #else
  3415. static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
  3416. {
  3417. return 0;
  3418. }
  3419. #endif
  3420. static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
  3421. {
  3422. struct mem_cgroup_per_node *pn;
  3423. struct mem_cgroup_per_zone *mz;
  3424. enum lru_list l;
  3425. int zone, tmp = node;
  3426. /*
  3427. * This routine is called against possible nodes.
  3428. * But it's BUG to call kmalloc() against offline node.
  3429. *
  3430. * TODO: this routine can waste much memory for nodes which will
  3431. * never be onlined. It's better to use memory hotplug callback
  3432. * function.
  3433. */
  3434. if (!node_state(node, N_NORMAL_MEMORY))
  3435. tmp = -1;
  3436. pn = kmalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
  3437. if (!pn)
  3438. return 1;
  3439. mem->info.nodeinfo[node] = pn;
  3440. memset(pn, 0, sizeof(*pn));
  3441. for (zone = 0; zone < MAX_NR_ZONES; zone++) {
  3442. mz = &pn->zoneinfo[zone];
  3443. for_each_lru(l)
  3444. INIT_LIST_HEAD(&mz->lists[l]);
  3445. mz->usage_in_excess = 0;
  3446. mz->on_tree = false;
  3447. mz->mem = mem;
  3448. }
  3449. return 0;
  3450. }
  3451. static void free_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
  3452. {
  3453. kfree(mem->info.nodeinfo[node]);
  3454. }
  3455. static struct mem_cgroup *mem_cgroup_alloc(void)
  3456. {
  3457. struct mem_cgroup *mem;
  3458. int size = sizeof(struct mem_cgroup);
  3459. /* Can be very big if MAX_NUMNODES is very big */
  3460. if (size < PAGE_SIZE)
  3461. mem = kmalloc(size, GFP_KERNEL);
  3462. else
  3463. mem = vmalloc(size);
  3464. if (!mem)
  3465. return NULL;
  3466. memset(mem, 0, size);
  3467. mem->stat = alloc_percpu(struct mem_cgroup_stat_cpu);
  3468. if (!mem->stat) {
  3469. if (size < PAGE_SIZE)
  3470. kfree(mem);
  3471. else
  3472. vfree(mem);
  3473. mem = NULL;
  3474. }
  3475. return mem;
  3476. }
  3477. /*
  3478. * At destroying mem_cgroup, references from swap_cgroup can remain.
  3479. * (scanning all at force_empty is too costly...)
  3480. *
  3481. * Instead of clearing all references at force_empty, we remember
  3482. * the number of reference from swap_cgroup and free mem_cgroup when
  3483. * it goes down to 0.
  3484. *
  3485. * Removal of cgroup itself succeeds regardless of refs from swap.
  3486. */
  3487. static void __mem_cgroup_free(struct mem_cgroup *mem)
  3488. {
  3489. int node;
  3490. mem_cgroup_remove_from_trees(mem);
  3491. free_css_id(&mem_cgroup_subsys, &mem->css);
  3492. for_each_node_state(node, N_POSSIBLE)
  3493. free_mem_cgroup_per_zone_info(mem, node);
  3494. free_percpu(mem->stat);
  3495. if (sizeof(struct mem_cgroup) < PAGE_SIZE)
  3496. kfree(mem);
  3497. else
  3498. vfree(mem);
  3499. }
  3500. static void mem_cgroup_get(struct mem_cgroup *mem)
  3501. {
  3502. atomic_inc(&mem->refcnt);
  3503. }
  3504. static void __mem_cgroup_put(struct mem_cgroup *mem, int count)
  3505. {
  3506. if (atomic_sub_and_test(count, &mem->refcnt)) {
  3507. struct mem_cgroup *parent = parent_mem_cgroup(mem);
  3508. __mem_cgroup_free(mem);
  3509. if (parent)
  3510. mem_cgroup_put(parent);
  3511. }
  3512. }
  3513. static void mem_cgroup_put(struct mem_cgroup *mem)
  3514. {
  3515. __mem_cgroup_put(mem, 1);
  3516. }
  3517. /*
  3518. * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
  3519. */
  3520. static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *mem)
  3521. {
  3522. if (!mem->res.parent)
  3523. return NULL;
  3524. return mem_cgroup_from_res_counter(mem->res.parent, res);
  3525. }
  3526. #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
  3527. static void __init enable_swap_cgroup(void)
  3528. {
  3529. if (!mem_cgroup_disabled() && really_do_swap_account)
  3530. do_swap_account = 1;
  3531. }
  3532. #else
  3533. static void __init enable_swap_cgroup(void)
  3534. {
  3535. }
  3536. #endif
  3537. static int mem_cgroup_soft_limit_tree_init(void)
  3538. {
  3539. struct mem_cgroup_tree_per_node *rtpn;
  3540. struct mem_cgroup_tree_per_zone *rtpz;
  3541. int tmp, node, zone;
  3542. for_each_node_state(node, N_POSSIBLE) {
  3543. tmp = node;
  3544. if (!node_state(node, N_NORMAL_MEMORY))
  3545. tmp = -1;
  3546. rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, tmp);
  3547. if (!rtpn)
  3548. return 1;
  3549. soft_limit_tree.rb_tree_per_node[node] = rtpn;
  3550. for (zone = 0; zone < MAX_NR_ZONES; zone++) {
  3551. rtpz = &rtpn->rb_tree_per_zone[zone];
  3552. rtpz->rb_root = RB_ROOT;
  3553. spin_lock_init(&rtpz->lock);
  3554. }
  3555. }
  3556. return 0;
  3557. }
  3558. static struct cgroup_subsys_state * __ref
  3559. mem_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cont)
  3560. {
  3561. struct mem_cgroup *mem, *parent;
  3562. long error = -ENOMEM;
  3563. int node;
  3564. mem = mem_cgroup_alloc();
  3565. if (!mem)
  3566. return ERR_PTR(error);
  3567. for_each_node_state(node, N_POSSIBLE)
  3568. if (alloc_mem_cgroup_per_zone_info(mem, node))
  3569. goto free_out;
  3570. /* root ? */
  3571. if (cont->parent == NULL) {
  3572. int cpu;
  3573. enable_swap_cgroup();
  3574. parent = NULL;
  3575. root_mem_cgroup = mem;
  3576. if (mem_cgroup_soft_limit_tree_init())
  3577. goto free_out;
  3578. for_each_possible_cpu(cpu) {
  3579. struct memcg_stock_pcp *stock =
  3580. &per_cpu(memcg_stock, cpu);
  3581. INIT_WORK(&stock->work, drain_local_stock);
  3582. }
  3583. hotcpu_notifier(memcg_stock_cpu_callback, 0);
  3584. } else {
  3585. parent = mem_cgroup_from_cont(cont->parent);
  3586. mem->use_hierarchy = parent->use_hierarchy;
  3587. mem->oom_kill_disable = parent->oom_kill_disable;
  3588. }
  3589. if (parent && parent->use_hierarchy) {
  3590. res_counter_init(&mem->res, &parent->res);
  3591. res_counter_init(&mem->memsw, &parent->memsw);
  3592. /*
  3593. * We increment refcnt of the parent to ensure that we can
  3594. * safely access it on res_counter_charge/uncharge.
  3595. * This refcnt will be decremented when freeing this
  3596. * mem_cgroup(see mem_cgroup_put).
  3597. */
  3598. mem_cgroup_get(parent);
  3599. } else {
  3600. res_counter_init(&mem->res, NULL);
  3601. res_counter_init(&mem->memsw, NULL);
  3602. }
  3603. mem->last_scanned_child = 0;
  3604. spin_lock_init(&mem->reclaim_param_lock);
  3605. INIT_LIST_HEAD(&mem->oom_notify);
  3606. if (parent)
  3607. mem->swappiness = get_swappiness(parent);
  3608. atomic_set(&mem->refcnt, 1);
  3609. mem->move_charge_at_immigrate = 0;
  3610. mutex_init(&mem->thresholds_lock);
  3611. return &mem->css;
  3612. free_out:
  3613. __mem_cgroup_free(mem);
  3614. root_mem_cgroup = NULL;
  3615. return ERR_PTR(error);
  3616. }
  3617. static int mem_cgroup_pre_destroy(struct cgroup_subsys *ss,
  3618. struct cgroup *cont)
  3619. {
  3620. struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
  3621. return mem_cgroup_force_empty(mem, false);
  3622. }
  3623. static void mem_cgroup_destroy(struct cgroup_subsys *ss,
  3624. struct cgroup *cont)
  3625. {
  3626. struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
  3627. mem_cgroup_put(mem);
  3628. }
  3629. static int mem_cgroup_populate(struct cgroup_subsys *ss,
  3630. struct cgroup *cont)
  3631. {
  3632. int ret;
  3633. ret = cgroup_add_files(cont, ss, mem_cgroup_files,
  3634. ARRAY_SIZE(mem_cgroup_files));
  3635. if (!ret)
  3636. ret = register_memsw_files(cont, ss);
  3637. return ret;
  3638. }
  3639. #ifdef CONFIG_MMU
  3640. /* Handlers for move charge at task migration. */
  3641. #define PRECHARGE_COUNT_AT_ONCE 256
  3642. static int mem_cgroup_do_precharge(unsigned long count)
  3643. {
  3644. int ret = 0;
  3645. int batch_count = PRECHARGE_COUNT_AT_ONCE;
  3646. struct mem_cgroup *mem = mc.to;
  3647. if (mem_cgroup_is_root(mem)) {
  3648. mc.precharge += count;
  3649. /* we don't need css_get for root */
  3650. return ret;
  3651. }
  3652. /* try to charge at once */
  3653. if (count > 1) {
  3654. struct res_counter *dummy;
  3655. /*
  3656. * "mem" cannot be under rmdir() because we've already checked
  3657. * by cgroup_lock_live_cgroup() that it is not removed and we
  3658. * are still under the same cgroup_mutex. So we can postpone
  3659. * css_get().
  3660. */
  3661. if (res_counter_charge(&mem->res, PAGE_SIZE * count, &dummy))
  3662. goto one_by_one;
  3663. if (do_swap_account && res_counter_charge(&mem->memsw,
  3664. PAGE_SIZE * count, &dummy)) {
  3665. res_counter_uncharge(&mem->res, PAGE_SIZE * count);
  3666. goto one_by_one;
  3667. }
  3668. mc.precharge += count;
  3669. VM_BUG_ON(test_bit(CSS_ROOT, &mem->css.flags));
  3670. WARN_ON_ONCE(count > INT_MAX);
  3671. __css_get(&mem->css, (int)count);
  3672. return ret;
  3673. }
  3674. one_by_one:
  3675. /* fall back to one by one charge */
  3676. while (count--) {
  3677. if (signal_pending(current)) {
  3678. ret = -EINTR;
  3679. break;
  3680. }
  3681. if (!batch_count--) {
  3682. batch_count = PRECHARGE_COUNT_AT_ONCE;
  3683. cond_resched();
  3684. }
  3685. ret = __mem_cgroup_try_charge(NULL, GFP_KERNEL, &mem, false);
  3686. if (ret || !mem)
  3687. /* mem_cgroup_clear_mc() will do uncharge later */
  3688. return -ENOMEM;
  3689. mc.precharge++;
  3690. }
  3691. return ret;
  3692. }
  3693. /**
  3694. * is_target_pte_for_mc - check a pte whether it is valid for move charge
  3695. * @vma: the vma the pte to be checked belongs
  3696. * @addr: the address corresponding to the pte to be checked
  3697. * @ptent: the pte to be checked
  3698. * @target: the pointer the target page or swap ent will be stored(can be NULL)
  3699. *
  3700. * Returns
  3701. * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
  3702. * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
  3703. * move charge. if @target is not NULL, the page is stored in target->page
  3704. * with extra refcnt got(Callers should handle it).
  3705. * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
  3706. * target for charge migration. if @target is not NULL, the entry is stored
  3707. * in target->ent.
  3708. *
  3709. * Called with pte lock held.
  3710. */
  3711. union mc_target {
  3712. struct page *page;
  3713. swp_entry_t ent;
  3714. };
  3715. enum mc_target_type {
  3716. MC_TARGET_NONE, /* not used */
  3717. MC_TARGET_PAGE,
  3718. MC_TARGET_SWAP,
  3719. };
  3720. static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
  3721. unsigned long addr, pte_t ptent)
  3722. {
  3723. struct page *page = vm_normal_page(vma, addr, ptent);
  3724. if (!page || !page_mapped(page))
  3725. return NULL;
  3726. if (PageAnon(page)) {
  3727. /* we don't move shared anon */
  3728. if (!move_anon() || page_mapcount(page) > 2)
  3729. return NULL;
  3730. } else if (!move_file())
  3731. /* we ignore mapcount for file pages */
  3732. return NULL;
  3733. if (!get_page_unless_zero(page))
  3734. return NULL;
  3735. return page;
  3736. }
  3737. static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
  3738. unsigned long addr, pte_t ptent, swp_entry_t *entry)
  3739. {
  3740. int usage_count;
  3741. struct page *page = NULL;
  3742. swp_entry_t ent = pte_to_swp_entry(ptent);
  3743. if (!move_anon() || non_swap_entry(ent))
  3744. return NULL;
  3745. usage_count = mem_cgroup_count_swap_user(ent, &page);
  3746. if (usage_count > 1) { /* we don't move shared anon */
  3747. if (page)
  3748. put_page(page);
  3749. return NULL;
  3750. }
  3751. if (do_swap_account)
  3752. entry->val = ent.val;
  3753. return page;
  3754. }
  3755. static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
  3756. unsigned long addr, pte_t ptent, swp_entry_t *entry)
  3757. {
  3758. struct page *page = NULL;
  3759. struct inode *inode;
  3760. struct address_space *mapping;
  3761. pgoff_t pgoff;
  3762. if (!vma->vm_file) /* anonymous vma */
  3763. return NULL;
  3764. if (!move_file())
  3765. return NULL;
  3766. inode = vma->vm_file->f_path.dentry->d_inode;
  3767. mapping = vma->vm_file->f_mapping;
  3768. if (pte_none(ptent))
  3769. pgoff = linear_page_index(vma, addr);
  3770. else /* pte_file(ptent) is true */
  3771. pgoff = pte_to_pgoff(ptent);
  3772. /* page is moved even if it's not RSS of this task(page-faulted). */
  3773. if (!mapping_cap_swap_backed(mapping)) { /* normal file */
  3774. page = find_get_page(mapping, pgoff);
  3775. } else { /* shmem/tmpfs file. we should take account of swap too. */
  3776. swp_entry_t ent;
  3777. mem_cgroup_get_shmem_target(inode, pgoff, &page, &ent);
  3778. if (do_swap_account)
  3779. entry->val = ent.val;
  3780. }
  3781. return page;
  3782. }
  3783. static int is_target_pte_for_mc(struct vm_area_struct *vma,
  3784. unsigned long addr, pte_t ptent, union mc_target *target)
  3785. {
  3786. struct page *page = NULL;
  3787. struct page_cgroup *pc;
  3788. int ret = 0;
  3789. swp_entry_t ent = { .val = 0 };
  3790. if (pte_present(ptent))
  3791. page = mc_handle_present_pte(vma, addr, ptent);
  3792. else if (is_swap_pte(ptent))
  3793. page = mc_handle_swap_pte(vma, addr, ptent, &ent);
  3794. else if (pte_none(ptent) || pte_file(ptent))
  3795. page = mc_handle_file_pte(vma, addr, ptent, &ent);
  3796. if (!page && !ent.val)
  3797. return 0;
  3798. if (page) {
  3799. pc = lookup_page_cgroup(page);
  3800. /*
  3801. * Do only loose check w/o page_cgroup lock.
  3802. * mem_cgroup_move_account() checks the pc is valid or not under
  3803. * the lock.
  3804. */
  3805. if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
  3806. ret = MC_TARGET_PAGE;
  3807. if (target)
  3808. target->page = page;
  3809. }
  3810. if (!ret || !target)
  3811. put_page(page);
  3812. }
  3813. /* There is a swap entry and a page doesn't exist or isn't charged */
  3814. if (ent.val && !ret &&
  3815. css_id(&mc.from->css) == lookup_swap_cgroup(ent)) {
  3816. ret = MC_TARGET_SWAP;
  3817. if (target)
  3818. target->ent = ent;
  3819. }
  3820. return ret;
  3821. }
  3822. static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
  3823. unsigned long addr, unsigned long end,
  3824. struct mm_walk *walk)
  3825. {
  3826. struct vm_area_struct *vma = walk->private;
  3827. pte_t *pte;
  3828. spinlock_t *ptl;
  3829. pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
  3830. for (; addr != end; pte++, addr += PAGE_SIZE)
  3831. if (is_target_pte_for_mc(vma, addr, *pte, NULL))
  3832. mc.precharge++; /* increment precharge temporarily */
  3833. pte_unmap_unlock(pte - 1, ptl);
  3834. cond_resched();
  3835. return 0;
  3836. }
  3837. static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
  3838. {
  3839. unsigned long precharge;
  3840. struct vm_area_struct *vma;
  3841. down_read(&mm->mmap_sem);
  3842. for (vma = mm->mmap; vma; vma = vma->vm_next) {
  3843. struct mm_walk mem_cgroup_count_precharge_walk = {
  3844. .pmd_entry = mem_cgroup_count_precharge_pte_range,
  3845. .mm = mm,
  3846. .private = vma,
  3847. };
  3848. if (is_vm_hugetlb_page(vma))
  3849. continue;
  3850. walk_page_range(vma->vm_start, vma->vm_end,
  3851. &mem_cgroup_count_precharge_walk);
  3852. }
  3853. up_read(&mm->mmap_sem);
  3854. precharge = mc.precharge;
  3855. mc.precharge = 0;
  3856. return precharge;
  3857. }
  3858. static int mem_cgroup_precharge_mc(struct mm_struct *mm)
  3859. {
  3860. return mem_cgroup_do_precharge(mem_cgroup_count_precharge(mm));
  3861. }
  3862. static void mem_cgroup_clear_mc(void)
  3863. {
  3864. /* we must uncharge all the leftover precharges from mc.to */
  3865. if (mc.precharge) {
  3866. __mem_cgroup_cancel_charge(mc.to, mc.precharge);
  3867. mc.precharge = 0;
  3868. memcg_oom_recover(mc.to);
  3869. }
  3870. /*
  3871. * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
  3872. * we must uncharge here.
  3873. */
  3874. if (mc.moved_charge) {
  3875. __mem_cgroup_cancel_charge(mc.from, mc.moved_charge);
  3876. mc.moved_charge = 0;
  3877. memcg_oom_recover(mc.from);
  3878. }
  3879. /* we must fixup refcnts and charges */
  3880. if (mc.moved_swap) {
  3881. WARN_ON_ONCE(mc.moved_swap > INT_MAX);
  3882. /* uncharge swap account from the old cgroup */
  3883. if (!mem_cgroup_is_root(mc.from))
  3884. res_counter_uncharge(&mc.from->memsw,
  3885. PAGE_SIZE * mc.moved_swap);
  3886. __mem_cgroup_put(mc.from, mc.moved_swap);
  3887. if (!mem_cgroup_is_root(mc.to)) {
  3888. /*
  3889. * we charged both to->res and to->memsw, so we should
  3890. * uncharge to->res.
  3891. */
  3892. res_counter_uncharge(&mc.to->res,
  3893. PAGE_SIZE * mc.moved_swap);
  3894. VM_BUG_ON(test_bit(CSS_ROOT, &mc.to->css.flags));
  3895. __css_put(&mc.to->css, mc.moved_swap);
  3896. }
  3897. /* we've already done mem_cgroup_get(mc.to) */
  3898. mc.moved_swap = 0;
  3899. }
  3900. mc.from = NULL;
  3901. mc.to = NULL;
  3902. mc.moving_task = NULL;
  3903. wake_up_all(&mc.waitq);
  3904. }
  3905. static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
  3906. struct cgroup *cgroup,
  3907. struct task_struct *p,
  3908. bool threadgroup)
  3909. {
  3910. int ret = 0;
  3911. struct mem_cgroup *mem = mem_cgroup_from_cont(cgroup);
  3912. if (mem->move_charge_at_immigrate) {
  3913. struct mm_struct *mm;
  3914. struct mem_cgroup *from = mem_cgroup_from_task(p);
  3915. VM_BUG_ON(from == mem);
  3916. mm = get_task_mm(p);
  3917. if (!mm)
  3918. return 0;
  3919. /* We move charges only when we move a owner of the mm */
  3920. if (mm->owner == p) {
  3921. VM_BUG_ON(mc.from);
  3922. VM_BUG_ON(mc.to);
  3923. VM_BUG_ON(mc.precharge);
  3924. VM_BUG_ON(mc.moved_charge);
  3925. VM_BUG_ON(mc.moved_swap);
  3926. VM_BUG_ON(mc.moving_task);
  3927. mc.from = from;
  3928. mc.to = mem;
  3929. mc.precharge = 0;
  3930. mc.moved_charge = 0;
  3931. mc.moved_swap = 0;
  3932. mc.moving_task = current;
  3933. ret = mem_cgroup_precharge_mc(mm);
  3934. if (ret)
  3935. mem_cgroup_clear_mc();
  3936. }
  3937. mmput(mm);
  3938. }
  3939. return ret;
  3940. }
  3941. static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
  3942. struct cgroup *cgroup,
  3943. struct task_struct *p,
  3944. bool threadgroup)
  3945. {
  3946. mem_cgroup_clear_mc();
  3947. }
  3948. static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
  3949. unsigned long addr, unsigned long end,
  3950. struct mm_walk *walk)
  3951. {
  3952. int ret = 0;
  3953. struct vm_area_struct *vma = walk->private;
  3954. pte_t *pte;
  3955. spinlock_t *ptl;
  3956. retry:
  3957. pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
  3958. for (; addr != end; addr += PAGE_SIZE) {
  3959. pte_t ptent = *(pte++);
  3960. union mc_target target;
  3961. int type;
  3962. struct page *page;
  3963. struct page_cgroup *pc;
  3964. swp_entry_t ent;
  3965. if (!mc.precharge)
  3966. break;
  3967. type = is_target_pte_for_mc(vma, addr, ptent, &target);
  3968. switch (type) {
  3969. case MC_TARGET_PAGE:
  3970. page = target.page;
  3971. if (isolate_lru_page(page))
  3972. goto put;
  3973. pc = lookup_page_cgroup(page);
  3974. if (!mem_cgroup_move_account(pc,
  3975. mc.from, mc.to, false)) {
  3976. mc.precharge--;
  3977. /* we uncharge from mc.from later. */
  3978. mc.moved_charge++;
  3979. }
  3980. putback_lru_page(page);
  3981. put: /* is_target_pte_for_mc() gets the page */
  3982. put_page(page);
  3983. break;
  3984. case MC_TARGET_SWAP:
  3985. ent = target.ent;
  3986. if (!mem_cgroup_move_swap_account(ent,
  3987. mc.from, mc.to, false)) {
  3988. mc.precharge--;
  3989. /* we fixup refcnts and charges later. */
  3990. mc.moved_swap++;
  3991. }
  3992. break;
  3993. default:
  3994. break;
  3995. }
  3996. }
  3997. pte_unmap_unlock(pte - 1, ptl);
  3998. cond_resched();
  3999. if (addr != end) {
  4000. /*
  4001. * We have consumed all precharges we got in can_attach().
  4002. * We try charge one by one, but don't do any additional
  4003. * charges to mc.to if we have failed in charge once in attach()
  4004. * phase.
  4005. */
  4006. ret = mem_cgroup_do_precharge(1);
  4007. if (!ret)
  4008. goto retry;
  4009. }
  4010. return ret;
  4011. }
  4012. static void mem_cgroup_move_charge(struct mm_struct *mm)
  4013. {
  4014. struct vm_area_struct *vma;
  4015. lru_add_drain_all();
  4016. down_read(&mm->mmap_sem);
  4017. for (vma = mm->mmap; vma; vma = vma->vm_next) {
  4018. int ret;
  4019. struct mm_walk mem_cgroup_move_charge_walk = {
  4020. .pmd_entry = mem_cgroup_move_charge_pte_range,
  4021. .mm = mm,
  4022. .private = vma,
  4023. };
  4024. if (is_vm_hugetlb_page(vma))
  4025. continue;
  4026. ret = walk_page_range(vma->vm_start, vma->vm_end,
  4027. &mem_cgroup_move_charge_walk);
  4028. if (ret)
  4029. /*
  4030. * means we have consumed all precharges and failed in
  4031. * doing additional charge. Just abandon here.
  4032. */
  4033. break;
  4034. }
  4035. up_read(&mm->mmap_sem);
  4036. }
  4037. static void mem_cgroup_move_task(struct cgroup_subsys *ss,
  4038. struct cgroup *cont,
  4039. struct cgroup *old_cont,
  4040. struct task_struct *p,
  4041. bool threadgroup)
  4042. {
  4043. struct mm_struct *mm;
  4044. if (!mc.to)
  4045. /* no need to move charge */
  4046. return;
  4047. mm = get_task_mm(p);
  4048. if (mm) {
  4049. mem_cgroup_move_charge(mm);
  4050. mmput(mm);
  4051. }
  4052. mem_cgroup_clear_mc();
  4053. }
  4054. #else /* !CONFIG_MMU */
  4055. static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
  4056. struct cgroup *cgroup,
  4057. struct task_struct *p,
  4058. bool threadgroup)
  4059. {
  4060. return 0;
  4061. }
  4062. static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
  4063. struct cgroup *cgroup,
  4064. struct task_struct *p,
  4065. bool threadgroup)
  4066. {
  4067. }
  4068. static void mem_cgroup_move_task(struct cgroup_subsys *ss,
  4069. struct cgroup *cont,
  4070. struct cgroup *old_cont,
  4071. struct task_struct *p,
  4072. bool threadgroup)
  4073. {
  4074. }
  4075. #endif
  4076. struct cgroup_subsys mem_cgroup_subsys = {
  4077. .name = "memory",
  4078. .subsys_id = mem_cgroup_subsys_id,
  4079. .create = mem_cgroup_create,
  4080. .pre_destroy = mem_cgroup_pre_destroy,
  4081. .destroy = mem_cgroup_destroy,
  4082. .populate = mem_cgroup_populate,
  4083. .can_attach = mem_cgroup_can_attach,
  4084. .cancel_attach = mem_cgroup_cancel_attach,
  4085. .attach = mem_cgroup_move_task,
  4086. .early_init = 0,
  4087. .use_id = 1,
  4088. };
  4089. #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
  4090. static int __init disable_swap_account(char *s)
  4091. {
  4092. really_do_swap_account = 0;
  4093. return 1;
  4094. }
  4095. __setup("noswapaccount", disable_swap_account);
  4096. #endif