memcontrol.c 132 KB

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