memcontrol.c 128 KB

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