memcontrol.c 159 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114
  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. * Kernel Memory Controller
  14. * Copyright (C) 2012 Parallels Inc. and Google Inc.
  15. * Authors: Glauber Costa and Suleiman Souhlal
  16. *
  17. * This program is free software; you can redistribute it and/or modify
  18. * it under the terms of the GNU General Public License as published by
  19. * the Free Software Foundation; either version 2 of the License, or
  20. * (at your option) any later version.
  21. *
  22. * This program is distributed in the hope that it will be useful,
  23. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  24. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  25. * GNU General Public License for more details.
  26. */
  27. #include <linux/res_counter.h>
  28. #include <linux/memcontrol.h>
  29. #include <linux/cgroup.h>
  30. #include <linux/mm.h>
  31. #include <linux/hugetlb.h>
  32. #include <linux/pagemap.h>
  33. #include <linux/smp.h>
  34. #include <linux/page-flags.h>
  35. #include <linux/backing-dev.h>
  36. #include <linux/bit_spinlock.h>
  37. #include <linux/rcupdate.h>
  38. #include <linux/limits.h>
  39. #include <linux/export.h>
  40. #include <linux/mutex.h>
  41. #include <linux/rbtree.h>
  42. #include <linux/slab.h>
  43. #include <linux/swap.h>
  44. #include <linux/swapops.h>
  45. #include <linux/spinlock.h>
  46. #include <linux/eventfd.h>
  47. #include <linux/sort.h>
  48. #include <linux/fs.h>
  49. #include <linux/seq_file.h>
  50. #include <linux/vmalloc.h>
  51. #include <linux/vmpressure.h>
  52. #include <linux/mm_inline.h>
  53. #include <linux/page_cgroup.h>
  54. #include <linux/cpu.h>
  55. #include <linux/oom.h>
  56. #include "internal.h"
  57. #include <net/sock.h>
  58. #include <net/tcp_memcontrol.h>
  59. #include <asm/uaccess.h>
  60. #include <trace/events/vmscan.h>
  61. struct cgroup_subsys mem_cgroup_subsys __read_mostly;
  62. #define MEM_CGROUP_RECLAIM_RETRIES 5
  63. static struct mem_cgroup *root_mem_cgroup __read_mostly;
  64. #ifdef CONFIG_MEMCG_SWAP
  65. /* Turned on only when memory cgroup is enabled && really_do_swap_account = 1 */
  66. int do_swap_account __read_mostly;
  67. /* for remember boot option*/
  68. #ifdef CONFIG_MEMCG_SWAP_ENABLED
  69. static int really_do_swap_account __initdata = 1;
  70. #else
  71. static int really_do_swap_account __initdata = 0;
  72. #endif
  73. #else
  74. #define do_swap_account 0
  75. #endif
  76. /*
  77. * Statistics for memory cgroup.
  78. */
  79. enum mem_cgroup_stat_index {
  80. /*
  81. * For MEM_CONTAINER_TYPE_ALL, usage = pagecache + rss.
  82. */
  83. MEM_CGROUP_STAT_CACHE, /* # of pages charged as cache */
  84. MEM_CGROUP_STAT_RSS, /* # of pages charged as anon rss */
  85. MEM_CGROUP_STAT_FILE_MAPPED, /* # of pages charged as file rss */
  86. MEM_CGROUP_STAT_SWAP, /* # of pages, swapped out */
  87. MEM_CGROUP_STAT_NSTATS,
  88. };
  89. static const char * const mem_cgroup_stat_names[] = {
  90. "cache",
  91. "rss",
  92. "mapped_file",
  93. "swap",
  94. };
  95. enum mem_cgroup_events_index {
  96. MEM_CGROUP_EVENTS_PGPGIN, /* # of pages paged in */
  97. MEM_CGROUP_EVENTS_PGPGOUT, /* # of pages paged out */
  98. MEM_CGROUP_EVENTS_PGFAULT, /* # of page-faults */
  99. MEM_CGROUP_EVENTS_PGMAJFAULT, /* # of major page-faults */
  100. MEM_CGROUP_EVENTS_NSTATS,
  101. };
  102. static const char * const mem_cgroup_events_names[] = {
  103. "pgpgin",
  104. "pgpgout",
  105. "pgfault",
  106. "pgmajfault",
  107. };
  108. /*
  109. * Per memcg event counter is incremented at every pagein/pageout. With THP,
  110. * it will be incremated by the number of pages. This counter is used for
  111. * for trigger some periodic events. This is straightforward and better
  112. * than using jiffies etc. to handle periodic memcg event.
  113. */
  114. enum mem_cgroup_events_target {
  115. MEM_CGROUP_TARGET_THRESH,
  116. MEM_CGROUP_TARGET_SOFTLIMIT,
  117. MEM_CGROUP_TARGET_NUMAINFO,
  118. MEM_CGROUP_NTARGETS,
  119. };
  120. #define THRESHOLDS_EVENTS_TARGET 128
  121. #define SOFTLIMIT_EVENTS_TARGET 1024
  122. #define NUMAINFO_EVENTS_TARGET 1024
  123. struct mem_cgroup_stat_cpu {
  124. long count[MEM_CGROUP_STAT_NSTATS];
  125. unsigned long events[MEM_CGROUP_EVENTS_NSTATS];
  126. unsigned long nr_page_events;
  127. unsigned long targets[MEM_CGROUP_NTARGETS];
  128. };
  129. struct mem_cgroup_reclaim_iter {
  130. /* css_id of the last scanned hierarchy member */
  131. int position;
  132. /* scan generation, increased every round-trip */
  133. unsigned int generation;
  134. };
  135. /*
  136. * per-zone information in memory controller.
  137. */
  138. struct mem_cgroup_per_zone {
  139. struct lruvec lruvec;
  140. unsigned long lru_size[NR_LRU_LISTS];
  141. struct mem_cgroup_reclaim_iter reclaim_iter[DEF_PRIORITY + 1];
  142. struct rb_node tree_node; /* RB tree node */
  143. unsigned long long usage_in_excess;/* Set to the value by which */
  144. /* the soft limit is exceeded*/
  145. bool on_tree;
  146. struct mem_cgroup *memcg; /* Back pointer, we cannot */
  147. /* use container_of */
  148. };
  149. struct mem_cgroup_per_node {
  150. struct mem_cgroup_per_zone zoneinfo[MAX_NR_ZONES];
  151. };
  152. struct mem_cgroup_lru_info {
  153. struct mem_cgroup_per_node *nodeinfo[MAX_NUMNODES];
  154. };
  155. /*
  156. * Cgroups above their limits are maintained in a RB-Tree, independent of
  157. * their hierarchy representation
  158. */
  159. struct mem_cgroup_tree_per_zone {
  160. struct rb_root rb_root;
  161. spinlock_t lock;
  162. };
  163. struct mem_cgroup_tree_per_node {
  164. struct mem_cgroup_tree_per_zone rb_tree_per_zone[MAX_NR_ZONES];
  165. };
  166. struct mem_cgroup_tree {
  167. struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
  168. };
  169. static struct mem_cgroup_tree soft_limit_tree __read_mostly;
  170. struct mem_cgroup_threshold {
  171. struct eventfd_ctx *eventfd;
  172. u64 threshold;
  173. };
  174. /* For threshold */
  175. struct mem_cgroup_threshold_ary {
  176. /* An array index points to threshold just below or equal to usage. */
  177. int current_threshold;
  178. /* Size of entries[] */
  179. unsigned int size;
  180. /* Array of thresholds */
  181. struct mem_cgroup_threshold entries[0];
  182. };
  183. struct mem_cgroup_thresholds {
  184. /* Primary thresholds array */
  185. struct mem_cgroup_threshold_ary *primary;
  186. /*
  187. * Spare threshold array.
  188. * This is needed to make mem_cgroup_unregister_event() "never fail".
  189. * It must be able to store at least primary->size - 1 entries.
  190. */
  191. struct mem_cgroup_threshold_ary *spare;
  192. };
  193. /* for OOM */
  194. struct mem_cgroup_eventfd_list {
  195. struct list_head list;
  196. struct eventfd_ctx *eventfd;
  197. };
  198. static void mem_cgroup_threshold(struct mem_cgroup *memcg);
  199. static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
  200. /*
  201. * The memory controller data structure. The memory controller controls both
  202. * page cache and RSS per cgroup. We would eventually like to provide
  203. * statistics based on the statistics developed by Rik Van Riel for clock-pro,
  204. * to help the administrator determine what knobs to tune.
  205. *
  206. * TODO: Add a water mark for the memory controller. Reclaim will begin when
  207. * we hit the water mark. May be even add a low water mark, such that
  208. * no reclaim occurs from a cgroup at it's low water mark, this is
  209. * a feature that will be implemented much later in the future.
  210. */
  211. struct mem_cgroup {
  212. struct cgroup_subsys_state css;
  213. /*
  214. * the counter to account for memory usage
  215. */
  216. struct res_counter res;
  217. /* vmpressure notifications */
  218. struct vmpressure vmpressure;
  219. union {
  220. /*
  221. * the counter to account for mem+swap usage.
  222. */
  223. struct res_counter memsw;
  224. /*
  225. * rcu_freeing is used only when freeing struct mem_cgroup,
  226. * so put it into a union to avoid wasting more memory.
  227. * It must be disjoint from the css field. It could be
  228. * in a union with the res field, but res plays a much
  229. * larger part in mem_cgroup life than memsw, and might
  230. * be of interest, even at time of free, when debugging.
  231. * So share rcu_head with the less interesting memsw.
  232. */
  233. struct rcu_head rcu_freeing;
  234. /*
  235. * We also need some space for a worker in deferred freeing.
  236. * By the time we call it, rcu_freeing is no longer in use.
  237. */
  238. struct work_struct work_freeing;
  239. };
  240. /*
  241. * the counter to account for kernel memory usage.
  242. */
  243. struct res_counter kmem;
  244. /*
  245. * Per cgroup active and inactive list, similar to the
  246. * per zone LRU lists.
  247. */
  248. struct mem_cgroup_lru_info info;
  249. int last_scanned_node;
  250. #if MAX_NUMNODES > 1
  251. nodemask_t scan_nodes;
  252. atomic_t numainfo_events;
  253. atomic_t numainfo_updating;
  254. #endif
  255. /*
  256. * Should the accounting and control be hierarchical, per subtree?
  257. */
  258. bool use_hierarchy;
  259. unsigned long kmem_account_flags; /* See KMEM_ACCOUNTED_*, below */
  260. bool oom_lock;
  261. atomic_t under_oom;
  262. atomic_t refcnt;
  263. int swappiness;
  264. /* OOM-Killer disable */
  265. int oom_kill_disable;
  266. /* set when res.limit == memsw.limit */
  267. bool memsw_is_minimum;
  268. /* protect arrays of thresholds */
  269. struct mutex thresholds_lock;
  270. /* thresholds for memory usage. RCU-protected */
  271. struct mem_cgroup_thresholds thresholds;
  272. /* thresholds for mem+swap usage. RCU-protected */
  273. struct mem_cgroup_thresholds memsw_thresholds;
  274. /* For oom notifier event fd */
  275. struct list_head oom_notify;
  276. /*
  277. * Should we move charges of a task when a task is moved into this
  278. * mem_cgroup ? And what type of charges should we move ?
  279. */
  280. unsigned long move_charge_at_immigrate;
  281. /*
  282. * set > 0 if pages under this cgroup are moving to other cgroup.
  283. */
  284. atomic_t moving_account;
  285. /* taken only while moving_account > 0 */
  286. spinlock_t move_lock;
  287. /*
  288. * percpu counter.
  289. */
  290. struct mem_cgroup_stat_cpu __percpu *stat;
  291. /*
  292. * used when a cpu is offlined or other synchronizations
  293. * See mem_cgroup_read_stat().
  294. */
  295. struct mem_cgroup_stat_cpu nocpu_base;
  296. spinlock_t pcp_counter_lock;
  297. #ifdef CONFIG_INET
  298. struct tcp_memcontrol tcp_mem;
  299. #endif
  300. };
  301. /* internal only representation about the status of kmem accounting. */
  302. enum {
  303. KMEM_ACCOUNTED_ACTIVE = 0, /* accounted by this cgroup itself */
  304. KMEM_ACCOUNTED_ACTIVATED, /* static key enabled. */
  305. KMEM_ACCOUNTED_DEAD, /* dead memcg with pending kmem charges */
  306. };
  307. /* We account when limit is on, but only after call sites are patched */
  308. #define KMEM_ACCOUNTED_MASK \
  309. ((1 << KMEM_ACCOUNTED_ACTIVE) | (1 << KMEM_ACCOUNTED_ACTIVATED))
  310. #ifdef CONFIG_MEMCG_KMEM
  311. static inline void memcg_kmem_set_active(struct mem_cgroup *memcg)
  312. {
  313. set_bit(KMEM_ACCOUNTED_ACTIVE, &memcg->kmem_account_flags);
  314. }
  315. static bool memcg_kmem_is_active(struct mem_cgroup *memcg)
  316. {
  317. return test_bit(KMEM_ACCOUNTED_ACTIVE, &memcg->kmem_account_flags);
  318. }
  319. static void memcg_kmem_set_activated(struct mem_cgroup *memcg)
  320. {
  321. set_bit(KMEM_ACCOUNTED_ACTIVATED, &memcg->kmem_account_flags);
  322. }
  323. static void memcg_kmem_mark_dead(struct mem_cgroup *memcg)
  324. {
  325. if (test_bit(KMEM_ACCOUNTED_ACTIVE, &memcg->kmem_account_flags))
  326. set_bit(KMEM_ACCOUNTED_DEAD, &memcg->kmem_account_flags);
  327. }
  328. static bool memcg_kmem_test_and_clear_dead(struct mem_cgroup *memcg)
  329. {
  330. return test_and_clear_bit(KMEM_ACCOUNTED_DEAD,
  331. &memcg->kmem_account_flags);
  332. }
  333. #endif
  334. /* Stuffs for move charges at task migration. */
  335. /*
  336. * Types of charges to be moved. "move_charge_at_immitgrate" is treated as a
  337. * left-shifted bitmap of these types.
  338. */
  339. enum move_type {
  340. MOVE_CHARGE_TYPE_ANON, /* private anonymous page and swap of it */
  341. MOVE_CHARGE_TYPE_FILE, /* file page(including tmpfs) and swap of it */
  342. NR_MOVE_TYPE,
  343. };
  344. /* "mc" and its members are protected by cgroup_mutex */
  345. static struct move_charge_struct {
  346. spinlock_t lock; /* for from, to */
  347. struct mem_cgroup *from;
  348. struct mem_cgroup *to;
  349. unsigned long precharge;
  350. unsigned long moved_charge;
  351. unsigned long moved_swap;
  352. struct task_struct *moving_task; /* a task moving charges */
  353. wait_queue_head_t waitq; /* a waitq for other context */
  354. } mc = {
  355. .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
  356. .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
  357. };
  358. static bool move_anon(void)
  359. {
  360. return test_bit(MOVE_CHARGE_TYPE_ANON,
  361. &mc.to->move_charge_at_immigrate);
  362. }
  363. static bool move_file(void)
  364. {
  365. return test_bit(MOVE_CHARGE_TYPE_FILE,
  366. &mc.to->move_charge_at_immigrate);
  367. }
  368. /*
  369. * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
  370. * limit reclaim to prevent infinite loops, if they ever occur.
  371. */
  372. #define MEM_CGROUP_MAX_RECLAIM_LOOPS 100
  373. #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS 2
  374. enum charge_type {
  375. MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
  376. MEM_CGROUP_CHARGE_TYPE_ANON,
  377. MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
  378. MEM_CGROUP_CHARGE_TYPE_DROP, /* a page was unused swap cache */
  379. NR_CHARGE_TYPE,
  380. };
  381. /* for encoding cft->private value on file */
  382. enum res_type {
  383. _MEM,
  384. _MEMSWAP,
  385. _OOM_TYPE,
  386. _KMEM,
  387. };
  388. #define MEMFILE_PRIVATE(x, val) ((x) << 16 | (val))
  389. #define MEMFILE_TYPE(val) ((val) >> 16 & 0xffff)
  390. #define MEMFILE_ATTR(val) ((val) & 0xffff)
  391. /* Used for OOM nofiier */
  392. #define OOM_CONTROL (0)
  393. /*
  394. * Reclaim flags for mem_cgroup_hierarchical_reclaim
  395. */
  396. #define MEM_CGROUP_RECLAIM_NOSWAP_BIT 0x0
  397. #define MEM_CGROUP_RECLAIM_NOSWAP (1 << MEM_CGROUP_RECLAIM_NOSWAP_BIT)
  398. #define MEM_CGROUP_RECLAIM_SHRINK_BIT 0x1
  399. #define MEM_CGROUP_RECLAIM_SHRINK (1 << MEM_CGROUP_RECLAIM_SHRINK_BIT)
  400. static void mem_cgroup_get(struct mem_cgroup *memcg);
  401. static void mem_cgroup_put(struct mem_cgroup *memcg);
  402. /* Some nice accessors for the vmpressure. */
  403. struct vmpressure *memcg_to_vmpressure(struct mem_cgroup *memcg)
  404. {
  405. if (!memcg)
  406. memcg = root_mem_cgroup;
  407. return &memcg->vmpressure;
  408. }
  409. struct cgroup_subsys_state *vmpressure_to_css(struct vmpressure *vmpr)
  410. {
  411. return &container_of(vmpr, struct mem_cgroup, vmpressure)->css;
  412. }
  413. struct vmpressure *css_to_vmpressure(struct cgroup_subsys_state *css)
  414. {
  415. struct mem_cgroup *memcg = container_of(css, struct mem_cgroup, css);
  416. return &memcg->vmpressure;
  417. }
  418. static inline
  419. struct mem_cgroup *mem_cgroup_from_css(struct cgroup_subsys_state *s)
  420. {
  421. return container_of(s, struct mem_cgroup, css);
  422. }
  423. /* Writing them here to avoid exposing memcg's inner layout */
  424. #ifdef CONFIG_MEMCG_KMEM
  425. #include <net/sock.h>
  426. #include <net/ip.h>
  427. static bool mem_cgroup_is_root(struct mem_cgroup *memcg);
  428. void sock_update_memcg(struct sock *sk)
  429. {
  430. if (mem_cgroup_sockets_enabled) {
  431. struct mem_cgroup *memcg;
  432. struct cg_proto *cg_proto;
  433. BUG_ON(!sk->sk_prot->proto_cgroup);
  434. /* Socket cloning can throw us here with sk_cgrp already
  435. * filled. It won't however, necessarily happen from
  436. * process context. So the test for root memcg given
  437. * the current task's memcg won't help us in this case.
  438. *
  439. * Respecting the original socket's memcg is a better
  440. * decision in this case.
  441. */
  442. if (sk->sk_cgrp) {
  443. BUG_ON(mem_cgroup_is_root(sk->sk_cgrp->memcg));
  444. mem_cgroup_get(sk->sk_cgrp->memcg);
  445. return;
  446. }
  447. rcu_read_lock();
  448. memcg = mem_cgroup_from_task(current);
  449. cg_proto = sk->sk_prot->proto_cgroup(memcg);
  450. if (!mem_cgroup_is_root(memcg) && memcg_proto_active(cg_proto)) {
  451. mem_cgroup_get(memcg);
  452. sk->sk_cgrp = cg_proto;
  453. }
  454. rcu_read_unlock();
  455. }
  456. }
  457. EXPORT_SYMBOL(sock_update_memcg);
  458. void sock_release_memcg(struct sock *sk)
  459. {
  460. if (mem_cgroup_sockets_enabled && sk->sk_cgrp) {
  461. struct mem_cgroup *memcg;
  462. WARN_ON(!sk->sk_cgrp->memcg);
  463. memcg = sk->sk_cgrp->memcg;
  464. mem_cgroup_put(memcg);
  465. }
  466. }
  467. #ifdef CONFIG_INET
  468. struct cg_proto *tcp_proto_cgroup(struct mem_cgroup *memcg)
  469. {
  470. if (!memcg || mem_cgroup_is_root(memcg))
  471. return NULL;
  472. return &memcg->tcp_mem.cg_proto;
  473. }
  474. EXPORT_SYMBOL(tcp_proto_cgroup);
  475. #endif /* CONFIG_INET */
  476. #endif /* CONFIG_MEMCG_KMEM */
  477. #if defined(CONFIG_INET) && defined(CONFIG_MEMCG_KMEM)
  478. static void disarm_sock_keys(struct mem_cgroup *memcg)
  479. {
  480. if (!memcg_proto_activated(&memcg->tcp_mem.cg_proto))
  481. return;
  482. static_key_slow_dec(&memcg_socket_limit_enabled);
  483. }
  484. #else
  485. static void disarm_sock_keys(struct mem_cgroup *memcg)
  486. {
  487. }
  488. #endif
  489. #ifdef CONFIG_MEMCG_KMEM
  490. struct static_key memcg_kmem_enabled_key;
  491. static void disarm_kmem_keys(struct mem_cgroup *memcg)
  492. {
  493. if (memcg_kmem_is_active(memcg))
  494. static_key_slow_dec(&memcg_kmem_enabled_key);
  495. }
  496. #else
  497. static void disarm_kmem_keys(struct mem_cgroup *memcg)
  498. {
  499. }
  500. #endif /* CONFIG_MEMCG_KMEM */
  501. static void disarm_static_keys(struct mem_cgroup *memcg)
  502. {
  503. disarm_sock_keys(memcg);
  504. disarm_kmem_keys(memcg);
  505. }
  506. static void drain_all_stock_async(struct mem_cgroup *memcg);
  507. static struct mem_cgroup_per_zone *
  508. mem_cgroup_zoneinfo(struct mem_cgroup *memcg, int nid, int zid)
  509. {
  510. return &memcg->info.nodeinfo[nid]->zoneinfo[zid];
  511. }
  512. struct cgroup_subsys_state *mem_cgroup_css(struct mem_cgroup *memcg)
  513. {
  514. return &memcg->css;
  515. }
  516. static struct mem_cgroup_per_zone *
  517. page_cgroup_zoneinfo(struct mem_cgroup *memcg, struct page *page)
  518. {
  519. int nid = page_to_nid(page);
  520. int zid = page_zonenum(page);
  521. return mem_cgroup_zoneinfo(memcg, nid, zid);
  522. }
  523. static struct mem_cgroup_tree_per_zone *
  524. soft_limit_tree_node_zone(int nid, int zid)
  525. {
  526. return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
  527. }
  528. static struct mem_cgroup_tree_per_zone *
  529. soft_limit_tree_from_page(struct page *page)
  530. {
  531. int nid = page_to_nid(page);
  532. int zid = page_zonenum(page);
  533. return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
  534. }
  535. static void
  536. __mem_cgroup_insert_exceeded(struct mem_cgroup *memcg,
  537. struct mem_cgroup_per_zone *mz,
  538. struct mem_cgroup_tree_per_zone *mctz,
  539. unsigned long long new_usage_in_excess)
  540. {
  541. struct rb_node **p = &mctz->rb_root.rb_node;
  542. struct rb_node *parent = NULL;
  543. struct mem_cgroup_per_zone *mz_node;
  544. if (mz->on_tree)
  545. return;
  546. mz->usage_in_excess = new_usage_in_excess;
  547. if (!mz->usage_in_excess)
  548. return;
  549. while (*p) {
  550. parent = *p;
  551. mz_node = rb_entry(parent, struct mem_cgroup_per_zone,
  552. tree_node);
  553. if (mz->usage_in_excess < mz_node->usage_in_excess)
  554. p = &(*p)->rb_left;
  555. /*
  556. * We can't avoid mem cgroups that are over their soft
  557. * limit by the same amount
  558. */
  559. else if (mz->usage_in_excess >= mz_node->usage_in_excess)
  560. p = &(*p)->rb_right;
  561. }
  562. rb_link_node(&mz->tree_node, parent, p);
  563. rb_insert_color(&mz->tree_node, &mctz->rb_root);
  564. mz->on_tree = true;
  565. }
  566. static void
  567. __mem_cgroup_remove_exceeded(struct mem_cgroup *memcg,
  568. struct mem_cgroup_per_zone *mz,
  569. struct mem_cgroup_tree_per_zone *mctz)
  570. {
  571. if (!mz->on_tree)
  572. return;
  573. rb_erase(&mz->tree_node, &mctz->rb_root);
  574. mz->on_tree = false;
  575. }
  576. static void
  577. mem_cgroup_remove_exceeded(struct mem_cgroup *memcg,
  578. struct mem_cgroup_per_zone *mz,
  579. struct mem_cgroup_tree_per_zone *mctz)
  580. {
  581. spin_lock(&mctz->lock);
  582. __mem_cgroup_remove_exceeded(memcg, mz, mctz);
  583. spin_unlock(&mctz->lock);
  584. }
  585. static void mem_cgroup_update_tree(struct mem_cgroup *memcg, struct page *page)
  586. {
  587. unsigned long long excess;
  588. struct mem_cgroup_per_zone *mz;
  589. struct mem_cgroup_tree_per_zone *mctz;
  590. int nid = page_to_nid(page);
  591. int zid = page_zonenum(page);
  592. mctz = soft_limit_tree_from_page(page);
  593. /*
  594. * Necessary to update all ancestors when hierarchy is used.
  595. * because their event counter is not touched.
  596. */
  597. for (; memcg; memcg = parent_mem_cgroup(memcg)) {
  598. mz = mem_cgroup_zoneinfo(memcg, nid, zid);
  599. excess = res_counter_soft_limit_excess(&memcg->res);
  600. /*
  601. * We have to update the tree if mz is on RB-tree or
  602. * mem is over its softlimit.
  603. */
  604. if (excess || mz->on_tree) {
  605. spin_lock(&mctz->lock);
  606. /* if on-tree, remove it */
  607. if (mz->on_tree)
  608. __mem_cgroup_remove_exceeded(memcg, mz, mctz);
  609. /*
  610. * Insert again. mz->usage_in_excess will be updated.
  611. * If excess is 0, no tree ops.
  612. */
  613. __mem_cgroup_insert_exceeded(memcg, mz, mctz, excess);
  614. spin_unlock(&mctz->lock);
  615. }
  616. }
  617. }
  618. static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
  619. {
  620. int node, zone;
  621. struct mem_cgroup_per_zone *mz;
  622. struct mem_cgroup_tree_per_zone *mctz;
  623. for_each_node(node) {
  624. for (zone = 0; zone < MAX_NR_ZONES; zone++) {
  625. mz = mem_cgroup_zoneinfo(memcg, node, zone);
  626. mctz = soft_limit_tree_node_zone(node, zone);
  627. mem_cgroup_remove_exceeded(memcg, mz, mctz);
  628. }
  629. }
  630. }
  631. static struct mem_cgroup_per_zone *
  632. __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
  633. {
  634. struct rb_node *rightmost = NULL;
  635. struct mem_cgroup_per_zone *mz;
  636. retry:
  637. mz = NULL;
  638. rightmost = rb_last(&mctz->rb_root);
  639. if (!rightmost)
  640. goto done; /* Nothing to reclaim from */
  641. mz = rb_entry(rightmost, struct mem_cgroup_per_zone, tree_node);
  642. /*
  643. * Remove the node now but someone else can add it back,
  644. * we will to add it back at the end of reclaim to its correct
  645. * position in the tree.
  646. */
  647. __mem_cgroup_remove_exceeded(mz->memcg, mz, mctz);
  648. if (!res_counter_soft_limit_excess(&mz->memcg->res) ||
  649. !css_tryget(&mz->memcg->css))
  650. goto retry;
  651. done:
  652. return mz;
  653. }
  654. static struct mem_cgroup_per_zone *
  655. mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
  656. {
  657. struct mem_cgroup_per_zone *mz;
  658. spin_lock(&mctz->lock);
  659. mz = __mem_cgroup_largest_soft_limit_node(mctz);
  660. spin_unlock(&mctz->lock);
  661. return mz;
  662. }
  663. /*
  664. * Implementation Note: reading percpu statistics for memcg.
  665. *
  666. * Both of vmstat[] and percpu_counter has threshold and do periodic
  667. * synchronization to implement "quick" read. There are trade-off between
  668. * reading cost and precision of value. Then, we may have a chance to implement
  669. * a periodic synchronizion of counter in memcg's counter.
  670. *
  671. * But this _read() function is used for user interface now. The user accounts
  672. * memory usage by memory cgroup and he _always_ requires exact value because
  673. * he accounts memory. Even if we provide quick-and-fuzzy read, we always
  674. * have to visit all online cpus and make sum. So, for now, unnecessary
  675. * synchronization is not implemented. (just implemented for cpu hotplug)
  676. *
  677. * If there are kernel internal actions which can make use of some not-exact
  678. * value, and reading all cpu value can be performance bottleneck in some
  679. * common workload, threashold and synchonization as vmstat[] should be
  680. * implemented.
  681. */
  682. static long mem_cgroup_read_stat(struct mem_cgroup *memcg,
  683. enum mem_cgroup_stat_index idx)
  684. {
  685. long val = 0;
  686. int cpu;
  687. get_online_cpus();
  688. for_each_online_cpu(cpu)
  689. val += per_cpu(memcg->stat->count[idx], cpu);
  690. #ifdef CONFIG_HOTPLUG_CPU
  691. spin_lock(&memcg->pcp_counter_lock);
  692. val += memcg->nocpu_base.count[idx];
  693. spin_unlock(&memcg->pcp_counter_lock);
  694. #endif
  695. put_online_cpus();
  696. return val;
  697. }
  698. static void mem_cgroup_swap_statistics(struct mem_cgroup *memcg,
  699. bool charge)
  700. {
  701. int val = (charge) ? 1 : -1;
  702. this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_SWAP], val);
  703. }
  704. static unsigned long mem_cgroup_read_events(struct mem_cgroup *memcg,
  705. enum mem_cgroup_events_index idx)
  706. {
  707. unsigned long val = 0;
  708. int cpu;
  709. for_each_online_cpu(cpu)
  710. val += per_cpu(memcg->stat->events[idx], cpu);
  711. #ifdef CONFIG_HOTPLUG_CPU
  712. spin_lock(&memcg->pcp_counter_lock);
  713. val += memcg->nocpu_base.events[idx];
  714. spin_unlock(&memcg->pcp_counter_lock);
  715. #endif
  716. return val;
  717. }
  718. static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
  719. bool anon, int nr_pages)
  720. {
  721. preempt_disable();
  722. /*
  723. * Here, RSS means 'mapped anon' and anon's SwapCache. Shmem/tmpfs is
  724. * counted as CACHE even if it's on ANON LRU.
  725. */
  726. if (anon)
  727. __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_RSS],
  728. nr_pages);
  729. else
  730. __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_CACHE],
  731. nr_pages);
  732. /* pagein of a big page is an event. So, ignore page size */
  733. if (nr_pages > 0)
  734. __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGIN]);
  735. else {
  736. __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGOUT]);
  737. nr_pages = -nr_pages; /* for event */
  738. }
  739. __this_cpu_add(memcg->stat->nr_page_events, nr_pages);
  740. preempt_enable();
  741. }
  742. unsigned long
  743. mem_cgroup_zone_nr_lru_pages(struct mem_cgroup *memcg, int nid, int zid,
  744. unsigned int lru_mask)
  745. {
  746. struct mem_cgroup_per_zone *mz;
  747. enum lru_list lru;
  748. unsigned long ret = 0;
  749. mz = mem_cgroup_zoneinfo(memcg, nid, zid);
  750. for_each_lru(lru) {
  751. if (BIT(lru) & lru_mask)
  752. ret += mz->lru_size[lru];
  753. }
  754. return ret;
  755. }
  756. static unsigned long
  757. mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
  758. int nid, unsigned int lru_mask)
  759. {
  760. u64 total = 0;
  761. int zid;
  762. for (zid = 0; zid < MAX_NR_ZONES; zid++)
  763. total += mem_cgroup_zone_nr_lru_pages(memcg,
  764. nid, zid, lru_mask);
  765. return total;
  766. }
  767. static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
  768. unsigned int lru_mask)
  769. {
  770. int nid;
  771. u64 total = 0;
  772. for_each_node_state(nid, N_HIGH_MEMORY)
  773. total += mem_cgroup_node_nr_lru_pages(memcg, nid, lru_mask);
  774. return total;
  775. }
  776. static bool mem_cgroup_event_ratelimit(struct mem_cgroup *memcg,
  777. enum mem_cgroup_events_target target)
  778. {
  779. unsigned long val, next;
  780. val = __this_cpu_read(memcg->stat->nr_page_events);
  781. next = __this_cpu_read(memcg->stat->targets[target]);
  782. /* from time_after() in jiffies.h */
  783. if ((long)next - (long)val < 0) {
  784. switch (target) {
  785. case MEM_CGROUP_TARGET_THRESH:
  786. next = val + THRESHOLDS_EVENTS_TARGET;
  787. break;
  788. case MEM_CGROUP_TARGET_SOFTLIMIT:
  789. next = val + SOFTLIMIT_EVENTS_TARGET;
  790. break;
  791. case MEM_CGROUP_TARGET_NUMAINFO:
  792. next = val + NUMAINFO_EVENTS_TARGET;
  793. break;
  794. default:
  795. break;
  796. }
  797. __this_cpu_write(memcg->stat->targets[target], next);
  798. return true;
  799. }
  800. return false;
  801. }
  802. /*
  803. * Check events in order.
  804. *
  805. */
  806. static void memcg_check_events(struct mem_cgroup *memcg, struct page *page)
  807. {
  808. preempt_disable();
  809. /* threshold event is triggered in finer grain than soft limit */
  810. if (unlikely(mem_cgroup_event_ratelimit(memcg,
  811. MEM_CGROUP_TARGET_THRESH))) {
  812. bool do_softlimit;
  813. bool do_numainfo __maybe_unused;
  814. do_softlimit = mem_cgroup_event_ratelimit(memcg,
  815. MEM_CGROUP_TARGET_SOFTLIMIT);
  816. #if MAX_NUMNODES > 1
  817. do_numainfo = mem_cgroup_event_ratelimit(memcg,
  818. MEM_CGROUP_TARGET_NUMAINFO);
  819. #endif
  820. preempt_enable();
  821. mem_cgroup_threshold(memcg);
  822. if (unlikely(do_softlimit))
  823. mem_cgroup_update_tree(memcg, page);
  824. #if MAX_NUMNODES > 1
  825. if (unlikely(do_numainfo))
  826. atomic_inc(&memcg->numainfo_events);
  827. #endif
  828. } else
  829. preempt_enable();
  830. }
  831. struct mem_cgroup *mem_cgroup_from_cont(struct cgroup *cont)
  832. {
  833. return mem_cgroup_from_css(
  834. cgroup_subsys_state(cont, mem_cgroup_subsys_id));
  835. }
  836. struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
  837. {
  838. /*
  839. * mm_update_next_owner() may clear mm->owner to NULL
  840. * if it races with swapoff, page migration, etc.
  841. * So this can be called with p == NULL.
  842. */
  843. if (unlikely(!p))
  844. return NULL;
  845. return mem_cgroup_from_css(task_subsys_state(p, mem_cgroup_subsys_id));
  846. }
  847. struct mem_cgroup *try_get_mem_cgroup_from_mm(struct mm_struct *mm)
  848. {
  849. struct mem_cgroup *memcg = NULL;
  850. if (!mm)
  851. return NULL;
  852. /*
  853. * Because we have no locks, mm->owner's may be being moved to other
  854. * cgroup. We use css_tryget() here even if this looks
  855. * pessimistic (rather than adding locks here).
  856. */
  857. rcu_read_lock();
  858. do {
  859. memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
  860. if (unlikely(!memcg))
  861. break;
  862. } while (!css_tryget(&memcg->css));
  863. rcu_read_unlock();
  864. return memcg;
  865. }
  866. /**
  867. * mem_cgroup_iter - iterate over memory cgroup hierarchy
  868. * @root: hierarchy root
  869. * @prev: previously returned memcg, NULL on first invocation
  870. * @reclaim: cookie for shared reclaim walks, NULL for full walks
  871. *
  872. * Returns references to children of the hierarchy below @root, or
  873. * @root itself, or %NULL after a full round-trip.
  874. *
  875. * Caller must pass the return value in @prev on subsequent
  876. * invocations for reference counting, or use mem_cgroup_iter_break()
  877. * to cancel a hierarchy walk before the round-trip is complete.
  878. *
  879. * Reclaimers can specify a zone and a priority level in @reclaim to
  880. * divide up the memcgs in the hierarchy among all concurrent
  881. * reclaimers operating on the same zone and priority.
  882. */
  883. struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
  884. struct mem_cgroup *prev,
  885. struct mem_cgroup_reclaim_cookie *reclaim)
  886. {
  887. struct mem_cgroup *memcg = NULL;
  888. int id = 0;
  889. if (mem_cgroup_disabled())
  890. return NULL;
  891. if (!root)
  892. root = root_mem_cgroup;
  893. if (prev && !reclaim)
  894. id = css_id(&prev->css);
  895. if (prev && prev != root)
  896. css_put(&prev->css);
  897. if (!root->use_hierarchy && root != root_mem_cgroup) {
  898. if (prev)
  899. return NULL;
  900. return root;
  901. }
  902. while (!memcg) {
  903. struct mem_cgroup_reclaim_iter *uninitialized_var(iter);
  904. struct cgroup_subsys_state *css;
  905. if (reclaim) {
  906. int nid = zone_to_nid(reclaim->zone);
  907. int zid = zone_idx(reclaim->zone);
  908. struct mem_cgroup_per_zone *mz;
  909. mz = mem_cgroup_zoneinfo(root, nid, zid);
  910. iter = &mz->reclaim_iter[reclaim->priority];
  911. if (prev && reclaim->generation != iter->generation)
  912. return NULL;
  913. id = iter->position;
  914. }
  915. rcu_read_lock();
  916. css = css_get_next(&mem_cgroup_subsys, id + 1, &root->css, &id);
  917. if (css) {
  918. if (css == &root->css || css_tryget(css))
  919. memcg = mem_cgroup_from_css(css);
  920. } else
  921. id = 0;
  922. rcu_read_unlock();
  923. if (reclaim) {
  924. iter->position = id;
  925. if (!css)
  926. iter->generation++;
  927. else if (!prev && memcg)
  928. reclaim->generation = iter->generation;
  929. }
  930. if (prev && !css)
  931. return NULL;
  932. }
  933. return memcg;
  934. }
  935. /**
  936. * mem_cgroup_iter_break - abort a hierarchy walk prematurely
  937. * @root: hierarchy root
  938. * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
  939. */
  940. void mem_cgroup_iter_break(struct mem_cgroup *root,
  941. struct mem_cgroup *prev)
  942. {
  943. if (!root)
  944. root = root_mem_cgroup;
  945. if (prev && prev != root)
  946. css_put(&prev->css);
  947. }
  948. /*
  949. * Iteration constructs for visiting all cgroups (under a tree). If
  950. * loops are exited prematurely (break), mem_cgroup_iter_break() must
  951. * be used for reference counting.
  952. */
  953. #define for_each_mem_cgroup_tree(iter, root) \
  954. for (iter = mem_cgroup_iter(root, NULL, NULL); \
  955. iter != NULL; \
  956. iter = mem_cgroup_iter(root, iter, NULL))
  957. #define for_each_mem_cgroup(iter) \
  958. for (iter = mem_cgroup_iter(NULL, NULL, NULL); \
  959. iter != NULL; \
  960. iter = mem_cgroup_iter(NULL, iter, NULL))
  961. static inline bool mem_cgroup_is_root(struct mem_cgroup *memcg)
  962. {
  963. return (memcg == root_mem_cgroup);
  964. }
  965. void mem_cgroup_count_vm_event(struct mm_struct *mm, enum vm_event_item idx)
  966. {
  967. struct mem_cgroup *memcg;
  968. if (!mm)
  969. return;
  970. rcu_read_lock();
  971. memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
  972. if (unlikely(!memcg))
  973. goto out;
  974. switch (idx) {
  975. case PGFAULT:
  976. this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGFAULT]);
  977. break;
  978. case PGMAJFAULT:
  979. this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGMAJFAULT]);
  980. break;
  981. default:
  982. BUG();
  983. }
  984. out:
  985. rcu_read_unlock();
  986. }
  987. EXPORT_SYMBOL(mem_cgroup_count_vm_event);
  988. /**
  989. * mem_cgroup_zone_lruvec - get the lru list vector for a zone and memcg
  990. * @zone: zone of the wanted lruvec
  991. * @mem: memcg of the wanted lruvec
  992. *
  993. * Returns the lru list vector holding pages for the given @zone and
  994. * @mem. This can be the global zone lruvec, if the memory controller
  995. * is disabled.
  996. */
  997. struct lruvec *mem_cgroup_zone_lruvec(struct zone *zone,
  998. struct mem_cgroup *memcg)
  999. {
  1000. struct mem_cgroup_per_zone *mz;
  1001. if (mem_cgroup_disabled())
  1002. return &zone->lruvec;
  1003. mz = mem_cgroup_zoneinfo(memcg, zone_to_nid(zone), zone_idx(zone));
  1004. return &mz->lruvec;
  1005. }
  1006. /*
  1007. * Following LRU functions are allowed to be used without PCG_LOCK.
  1008. * Operations are called by routine of global LRU independently from memcg.
  1009. * What we have to take care of here is validness of pc->mem_cgroup.
  1010. *
  1011. * Changes to pc->mem_cgroup happens when
  1012. * 1. charge
  1013. * 2. moving account
  1014. * In typical case, "charge" is done before add-to-lru. Exception is SwapCache.
  1015. * It is added to LRU before charge.
  1016. * If PCG_USED bit is not set, page_cgroup is not added to this private LRU.
  1017. * When moving account, the page is not on LRU. It's isolated.
  1018. */
  1019. /**
  1020. * mem_cgroup_lru_add_list - account for adding an lru page and return lruvec
  1021. * @zone: zone of the page
  1022. * @page: the page
  1023. * @lru: current lru
  1024. *
  1025. * This function accounts for @page being added to @lru, and returns
  1026. * the lruvec for the given @zone and the memcg @page is charged to.
  1027. *
  1028. * The callsite is then responsible for physically linking the page to
  1029. * the returned lruvec->lists[@lru].
  1030. */
  1031. struct lruvec *mem_cgroup_lru_add_list(struct zone *zone, struct page *page,
  1032. enum lru_list lru)
  1033. {
  1034. struct mem_cgroup_per_zone *mz;
  1035. struct mem_cgroup *memcg;
  1036. struct page_cgroup *pc;
  1037. if (mem_cgroup_disabled())
  1038. return &zone->lruvec;
  1039. pc = lookup_page_cgroup(page);
  1040. memcg = pc->mem_cgroup;
  1041. /*
  1042. * Surreptitiously switch any uncharged page to root:
  1043. * an uncharged page off lru does nothing to secure
  1044. * its former mem_cgroup from sudden removal.
  1045. *
  1046. * Our caller holds lru_lock, and PageCgroupUsed is updated
  1047. * under page_cgroup lock: between them, they make all uses
  1048. * of pc->mem_cgroup safe.
  1049. */
  1050. if (!PageCgroupUsed(pc) && memcg != root_mem_cgroup)
  1051. pc->mem_cgroup = memcg = root_mem_cgroup;
  1052. mz = page_cgroup_zoneinfo(memcg, page);
  1053. /* compound_order() is stabilized through lru_lock */
  1054. mz->lru_size[lru] += 1 << compound_order(page);
  1055. return &mz->lruvec;
  1056. }
  1057. /**
  1058. * mem_cgroup_lru_del_list - account for removing an lru page
  1059. * @page: the page
  1060. * @lru: target lru
  1061. *
  1062. * This function accounts for @page being removed from @lru.
  1063. *
  1064. * The callsite is then responsible for physically unlinking
  1065. * @page->lru.
  1066. */
  1067. void mem_cgroup_lru_del_list(struct page *page, enum lru_list lru)
  1068. {
  1069. struct mem_cgroup_per_zone *mz;
  1070. struct mem_cgroup *memcg;
  1071. struct page_cgroup *pc;
  1072. if (mem_cgroup_disabled())
  1073. return;
  1074. pc = lookup_page_cgroup(page);
  1075. memcg = pc->mem_cgroup;
  1076. VM_BUG_ON(!memcg);
  1077. mz = page_cgroup_zoneinfo(memcg, page);
  1078. /* huge page split is done under lru_lock. so, we have no races. */
  1079. VM_BUG_ON(mz->lru_size[lru] < (1 << compound_order(page)));
  1080. mz->lru_size[lru] -= 1 << compound_order(page);
  1081. }
  1082. /**
  1083. * mem_cgroup_lru_move_lists - account for moving a page between lrus
  1084. * @zone: zone of the page
  1085. * @page: the page
  1086. * @from: current lru
  1087. * @to: target lru
  1088. *
  1089. * This function accounts for @page being moved between the lrus @from
  1090. * and @to, and returns the lruvec for the given @zone and the memcg
  1091. * @page is charged to.
  1092. *
  1093. * The callsite is then responsible for physically relinking
  1094. * @page->lru to the returned lruvec->lists[@to].
  1095. */
  1096. struct lruvec *mem_cgroup_lru_move_lists(struct zone *zone,
  1097. struct page *page,
  1098. enum lru_list from,
  1099. enum lru_list to)
  1100. {
  1101. /* XXX: Optimize this, especially for @from == @to */
  1102. mem_cgroup_lru_del_list(page, from);
  1103. return mem_cgroup_lru_add_list(zone, page, to);
  1104. }
  1105. /*
  1106. * Checks whether given mem is same or in the root_mem_cgroup's
  1107. * hierarchy subtree
  1108. */
  1109. bool __mem_cgroup_same_or_subtree(const struct mem_cgroup *root_memcg,
  1110. struct mem_cgroup *memcg)
  1111. {
  1112. if (root_memcg == memcg)
  1113. return true;
  1114. if (!root_memcg->use_hierarchy || !memcg)
  1115. return false;
  1116. return css_is_ancestor(&memcg->css, &root_memcg->css);
  1117. }
  1118. static bool mem_cgroup_same_or_subtree(const struct mem_cgroup *root_memcg,
  1119. struct mem_cgroup *memcg)
  1120. {
  1121. bool ret;
  1122. rcu_read_lock();
  1123. ret = __mem_cgroup_same_or_subtree(root_memcg, memcg);
  1124. rcu_read_unlock();
  1125. return ret;
  1126. }
  1127. int task_in_mem_cgroup(struct task_struct *task, const struct mem_cgroup *memcg)
  1128. {
  1129. int ret;
  1130. struct mem_cgroup *curr = NULL;
  1131. struct task_struct *p;
  1132. p = find_lock_task_mm(task);
  1133. if (p) {
  1134. curr = try_get_mem_cgroup_from_mm(p->mm);
  1135. task_unlock(p);
  1136. } else {
  1137. /*
  1138. * All threads may have already detached their mm's, but the oom
  1139. * killer still needs to detect if they have already been oom
  1140. * killed to prevent needlessly killing additional tasks.
  1141. */
  1142. task_lock(task);
  1143. curr = mem_cgroup_from_task(task);
  1144. if (curr)
  1145. css_get(&curr->css);
  1146. task_unlock(task);
  1147. }
  1148. if (!curr)
  1149. return 0;
  1150. /*
  1151. * We should check use_hierarchy of "memcg" not "curr". Because checking
  1152. * use_hierarchy of "curr" here make this function true if hierarchy is
  1153. * enabled in "curr" and "curr" is a child of "memcg" in *cgroup*
  1154. * hierarchy(even if use_hierarchy is disabled in "memcg").
  1155. */
  1156. ret = mem_cgroup_same_or_subtree(memcg, curr);
  1157. css_put(&curr->css);
  1158. return ret;
  1159. }
  1160. int mem_cgroup_inactive_anon_is_low(struct mem_cgroup *memcg, struct zone *zone)
  1161. {
  1162. unsigned long inactive_ratio;
  1163. int nid = zone_to_nid(zone);
  1164. int zid = zone_idx(zone);
  1165. unsigned long inactive;
  1166. unsigned long active;
  1167. unsigned long gb;
  1168. inactive = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid,
  1169. BIT(LRU_INACTIVE_ANON));
  1170. active = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid,
  1171. BIT(LRU_ACTIVE_ANON));
  1172. gb = (inactive + active) >> (30 - PAGE_SHIFT);
  1173. if (gb)
  1174. inactive_ratio = int_sqrt(10 * gb);
  1175. else
  1176. inactive_ratio = 1;
  1177. return inactive * inactive_ratio < active;
  1178. }
  1179. int mem_cgroup_inactive_file_is_low(struct mem_cgroup *memcg, struct zone *zone)
  1180. {
  1181. unsigned long active;
  1182. unsigned long inactive;
  1183. int zid = zone_idx(zone);
  1184. int nid = zone_to_nid(zone);
  1185. inactive = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid,
  1186. BIT(LRU_INACTIVE_FILE));
  1187. active = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid,
  1188. BIT(LRU_ACTIVE_FILE));
  1189. return (active > inactive);
  1190. }
  1191. struct zone_reclaim_stat *
  1192. mem_cgroup_get_reclaim_stat_from_page(struct page *page)
  1193. {
  1194. struct page_cgroup *pc;
  1195. struct mem_cgroup_per_zone *mz;
  1196. if (mem_cgroup_disabled())
  1197. return NULL;
  1198. pc = lookup_page_cgroup(page);
  1199. if (!PageCgroupUsed(pc))
  1200. return NULL;
  1201. /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
  1202. smp_rmb();
  1203. mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
  1204. return &mz->lruvec.reclaim_stat;
  1205. }
  1206. #define mem_cgroup_from_res_counter(counter, member) \
  1207. container_of(counter, struct mem_cgroup, member)
  1208. /**
  1209. * mem_cgroup_margin - calculate chargeable space of a memory cgroup
  1210. * @memcg: the memory cgroup
  1211. *
  1212. * Returns the maximum amount of memory @mem can be charged with, in
  1213. * pages.
  1214. */
  1215. static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
  1216. {
  1217. unsigned long long margin;
  1218. margin = res_counter_margin(&memcg->res);
  1219. if (do_swap_account)
  1220. margin = min(margin, res_counter_margin(&memcg->memsw));
  1221. return margin >> PAGE_SHIFT;
  1222. }
  1223. int mem_cgroup_swappiness(struct mem_cgroup *memcg)
  1224. {
  1225. struct cgroup *cgrp = memcg->css.cgroup;
  1226. /* root ? */
  1227. if (cgrp->parent == NULL)
  1228. return vm_swappiness;
  1229. return memcg->swappiness;
  1230. }
  1231. /*
  1232. * memcg->moving_account is used for checking possibility that some thread is
  1233. * calling move_account(). When a thread on CPU-A starts moving pages under
  1234. * a memcg, other threads should check memcg->moving_account under
  1235. * rcu_read_lock(), like this:
  1236. *
  1237. * CPU-A CPU-B
  1238. * rcu_read_lock()
  1239. * memcg->moving_account+1 if (memcg->mocing_account)
  1240. * take heavy locks.
  1241. * synchronize_rcu() update something.
  1242. * rcu_read_unlock()
  1243. * start move here.
  1244. */
  1245. /* for quick checking without looking up memcg */
  1246. atomic_t memcg_moving __read_mostly;
  1247. static void mem_cgroup_start_move(struct mem_cgroup *memcg)
  1248. {
  1249. atomic_inc(&memcg_moving);
  1250. atomic_inc(&memcg->moving_account);
  1251. synchronize_rcu();
  1252. }
  1253. static void mem_cgroup_end_move(struct mem_cgroup *memcg)
  1254. {
  1255. /*
  1256. * Now, mem_cgroup_clear_mc() may call this function with NULL.
  1257. * We check NULL in callee rather than caller.
  1258. */
  1259. if (memcg) {
  1260. atomic_dec(&memcg_moving);
  1261. atomic_dec(&memcg->moving_account);
  1262. }
  1263. }
  1264. /*
  1265. * 2 routines for checking "mem" is under move_account() or not.
  1266. *
  1267. * mem_cgroup_stolen() - checking whether a cgroup is mc.from or not. This
  1268. * is used for avoiding races in accounting. If true,
  1269. * pc->mem_cgroup may be overwritten.
  1270. *
  1271. * mem_cgroup_under_move() - checking a cgroup is mc.from or mc.to or
  1272. * under hierarchy of moving cgroups. This is for
  1273. * waiting at hith-memory prressure caused by "move".
  1274. */
  1275. static bool mem_cgroup_stolen(struct mem_cgroup *memcg)
  1276. {
  1277. VM_BUG_ON(!rcu_read_lock_held());
  1278. return atomic_read(&memcg->moving_account) > 0;
  1279. }
  1280. static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
  1281. {
  1282. struct mem_cgroup *from;
  1283. struct mem_cgroup *to;
  1284. bool ret = false;
  1285. /*
  1286. * Unlike task_move routines, we access mc.to, mc.from not under
  1287. * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
  1288. */
  1289. spin_lock(&mc.lock);
  1290. from = mc.from;
  1291. to = mc.to;
  1292. if (!from)
  1293. goto unlock;
  1294. ret = mem_cgroup_same_or_subtree(memcg, from)
  1295. || mem_cgroup_same_or_subtree(memcg, to);
  1296. unlock:
  1297. spin_unlock(&mc.lock);
  1298. return ret;
  1299. }
  1300. static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
  1301. {
  1302. if (mc.moving_task && current != mc.moving_task) {
  1303. if (mem_cgroup_under_move(memcg)) {
  1304. DEFINE_WAIT(wait);
  1305. prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
  1306. /* moving charge context might have finished. */
  1307. if (mc.moving_task)
  1308. schedule();
  1309. finish_wait(&mc.waitq, &wait);
  1310. return true;
  1311. }
  1312. }
  1313. return false;
  1314. }
  1315. /*
  1316. * Take this lock when
  1317. * - a code tries to modify page's memcg while it's USED.
  1318. * - a code tries to modify page state accounting in a memcg.
  1319. * see mem_cgroup_stolen(), too.
  1320. */
  1321. static void move_lock_mem_cgroup(struct mem_cgroup *memcg,
  1322. unsigned long *flags)
  1323. {
  1324. spin_lock_irqsave(&memcg->move_lock, *flags);
  1325. }
  1326. static void move_unlock_mem_cgroup(struct mem_cgroup *memcg,
  1327. unsigned long *flags)
  1328. {
  1329. spin_unlock_irqrestore(&memcg->move_lock, *flags);
  1330. }
  1331. /**
  1332. * mem_cgroup_print_oom_info: Called from OOM with tasklist_lock held in read mode.
  1333. * @memcg: The memory cgroup that went over limit
  1334. * @p: Task that is going to be killed
  1335. *
  1336. * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
  1337. * enabled
  1338. */
  1339. void mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p)
  1340. {
  1341. struct cgroup *task_cgrp;
  1342. struct cgroup *mem_cgrp;
  1343. /*
  1344. * Need a buffer in BSS, can't rely on allocations. The code relies
  1345. * on the assumption that OOM is serialized for memory controller.
  1346. * If this assumption is broken, revisit this code.
  1347. */
  1348. static char memcg_name[PATH_MAX];
  1349. int ret;
  1350. if (!memcg || !p)
  1351. return;
  1352. rcu_read_lock();
  1353. mem_cgrp = memcg->css.cgroup;
  1354. task_cgrp = task_cgroup(p, mem_cgroup_subsys_id);
  1355. ret = cgroup_path(task_cgrp, memcg_name, PATH_MAX);
  1356. if (ret < 0) {
  1357. /*
  1358. * Unfortunately, we are unable to convert to a useful name
  1359. * But we'll still print out the usage information
  1360. */
  1361. rcu_read_unlock();
  1362. goto done;
  1363. }
  1364. rcu_read_unlock();
  1365. printk(KERN_INFO "Task in %s killed", memcg_name);
  1366. rcu_read_lock();
  1367. ret = cgroup_path(mem_cgrp, memcg_name, PATH_MAX);
  1368. if (ret < 0) {
  1369. rcu_read_unlock();
  1370. goto done;
  1371. }
  1372. rcu_read_unlock();
  1373. /*
  1374. * Continues from above, so we don't need an KERN_ level
  1375. */
  1376. printk(KERN_CONT " as a result of limit of %s\n", memcg_name);
  1377. done:
  1378. printk(KERN_INFO "memory: usage %llukB, limit %llukB, failcnt %llu\n",
  1379. res_counter_read_u64(&memcg->res, RES_USAGE) >> 10,
  1380. res_counter_read_u64(&memcg->res, RES_LIMIT) >> 10,
  1381. res_counter_read_u64(&memcg->res, RES_FAILCNT));
  1382. printk(KERN_INFO "memory+swap: usage %llukB, limit %llukB, "
  1383. "failcnt %llu\n",
  1384. res_counter_read_u64(&memcg->memsw, RES_USAGE) >> 10,
  1385. res_counter_read_u64(&memcg->memsw, RES_LIMIT) >> 10,
  1386. res_counter_read_u64(&memcg->memsw, RES_FAILCNT));
  1387. printk(KERN_INFO "kmem: usage %llukB, limit %llukB, failcnt %llu\n",
  1388. res_counter_read_u64(&memcg->kmem, RES_USAGE) >> 10,
  1389. res_counter_read_u64(&memcg->kmem, RES_LIMIT) >> 10,
  1390. res_counter_read_u64(&memcg->kmem, RES_FAILCNT));
  1391. }
  1392. /*
  1393. * This function returns the number of memcg under hierarchy tree. Returns
  1394. * 1(self count) if no children.
  1395. */
  1396. static int mem_cgroup_count_children(struct mem_cgroup *memcg)
  1397. {
  1398. int num = 0;
  1399. struct mem_cgroup *iter;
  1400. for_each_mem_cgroup_tree(iter, memcg)
  1401. num++;
  1402. return num;
  1403. }
  1404. /*
  1405. * Return the memory (and swap, if configured) limit for a memcg.
  1406. */
  1407. u64 mem_cgroup_get_limit(struct mem_cgroup *memcg)
  1408. {
  1409. u64 limit;
  1410. limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
  1411. /*
  1412. * Do not consider swap space if we cannot swap due to swappiness
  1413. */
  1414. if (mem_cgroup_swappiness(memcg)) {
  1415. u64 memsw;
  1416. limit += total_swap_pages << PAGE_SHIFT;
  1417. memsw = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
  1418. /*
  1419. * If memsw is finite and limits the amount of swap space
  1420. * available to this memcg, return that limit.
  1421. */
  1422. limit = min(limit, memsw);
  1423. }
  1424. return limit;
  1425. }
  1426. static unsigned long mem_cgroup_reclaim(struct mem_cgroup *memcg,
  1427. gfp_t gfp_mask,
  1428. unsigned long flags)
  1429. {
  1430. unsigned long total = 0;
  1431. bool noswap = false;
  1432. int loop;
  1433. if (flags & MEM_CGROUP_RECLAIM_NOSWAP)
  1434. noswap = true;
  1435. if (!(flags & MEM_CGROUP_RECLAIM_SHRINK) && memcg->memsw_is_minimum)
  1436. noswap = true;
  1437. for (loop = 0; loop < MEM_CGROUP_MAX_RECLAIM_LOOPS; loop++) {
  1438. if (loop)
  1439. drain_all_stock_async(memcg);
  1440. total += try_to_free_mem_cgroup_pages(memcg, gfp_mask, noswap);
  1441. /*
  1442. * Allow limit shrinkers, which are triggered directly
  1443. * by userspace, to catch signals and stop reclaim
  1444. * after minimal progress, regardless of the margin.
  1445. */
  1446. if (total && (flags & MEM_CGROUP_RECLAIM_SHRINK))
  1447. break;
  1448. if (mem_cgroup_margin(memcg))
  1449. break;
  1450. /*
  1451. * If nothing was reclaimed after two attempts, there
  1452. * may be no reclaimable pages in this hierarchy.
  1453. */
  1454. if (loop && !total)
  1455. break;
  1456. }
  1457. return total;
  1458. }
  1459. /**
  1460. * test_mem_cgroup_node_reclaimable
  1461. * @memcg: the target memcg
  1462. * @nid: the node ID to be checked.
  1463. * @noswap : specify true here if the user wants flle only information.
  1464. *
  1465. * This function returns whether the specified memcg contains any
  1466. * reclaimable pages on a node. Returns true if there are any reclaimable
  1467. * pages in the node.
  1468. */
  1469. static bool test_mem_cgroup_node_reclaimable(struct mem_cgroup *memcg,
  1470. int nid, bool noswap)
  1471. {
  1472. if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_FILE))
  1473. return true;
  1474. if (noswap || !total_swap_pages)
  1475. return false;
  1476. if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_ANON))
  1477. return true;
  1478. return false;
  1479. }
  1480. #if MAX_NUMNODES > 1
  1481. /*
  1482. * Always updating the nodemask is not very good - even if we have an empty
  1483. * list or the wrong list here, we can start from some node and traverse all
  1484. * nodes based on the zonelist. So update the list loosely once per 10 secs.
  1485. *
  1486. */
  1487. static void mem_cgroup_may_update_nodemask(struct mem_cgroup *memcg)
  1488. {
  1489. int nid;
  1490. /*
  1491. * numainfo_events > 0 means there was at least NUMAINFO_EVENTS_TARGET
  1492. * pagein/pageout changes since the last update.
  1493. */
  1494. if (!atomic_read(&memcg->numainfo_events))
  1495. return;
  1496. if (atomic_inc_return(&memcg->numainfo_updating) > 1)
  1497. return;
  1498. /* make a nodemask where this memcg uses memory from */
  1499. memcg->scan_nodes = node_states[N_HIGH_MEMORY];
  1500. for_each_node_mask(nid, node_states[N_HIGH_MEMORY]) {
  1501. if (!test_mem_cgroup_node_reclaimable(memcg, nid, false))
  1502. node_clear(nid, memcg->scan_nodes);
  1503. }
  1504. atomic_set(&memcg->numainfo_events, 0);
  1505. atomic_set(&memcg->numainfo_updating, 0);
  1506. }
  1507. /*
  1508. * Selecting a node where we start reclaim from. Because what we need is just
  1509. * reducing usage counter, start from anywhere is O,K. Considering
  1510. * memory reclaim from current node, there are pros. and cons.
  1511. *
  1512. * Freeing memory from current node means freeing memory from a node which
  1513. * we'll use or we've used. So, it may make LRU bad. And if several threads
  1514. * hit limits, it will see a contention on a node. But freeing from remote
  1515. * node means more costs for memory reclaim because of memory latency.
  1516. *
  1517. * Now, we use round-robin. Better algorithm is welcomed.
  1518. */
  1519. int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
  1520. {
  1521. int node;
  1522. mem_cgroup_may_update_nodemask(memcg);
  1523. node = memcg->last_scanned_node;
  1524. node = next_node(node, memcg->scan_nodes);
  1525. if (node == MAX_NUMNODES)
  1526. node = first_node(memcg->scan_nodes);
  1527. /*
  1528. * We call this when we hit limit, not when pages are added to LRU.
  1529. * No LRU may hold pages because all pages are UNEVICTABLE or
  1530. * memcg is too small and all pages are not on LRU. In that case,
  1531. * we use curret node.
  1532. */
  1533. if (unlikely(node == MAX_NUMNODES))
  1534. node = numa_node_id();
  1535. memcg->last_scanned_node = node;
  1536. return node;
  1537. }
  1538. /*
  1539. * Check all nodes whether it contains reclaimable pages or not.
  1540. * For quick scan, we make use of scan_nodes. This will allow us to skip
  1541. * unused nodes. But scan_nodes is lazily updated and may not cotain
  1542. * enough new information. We need to do double check.
  1543. */
  1544. static bool mem_cgroup_reclaimable(struct mem_cgroup *memcg, bool noswap)
  1545. {
  1546. int nid;
  1547. /*
  1548. * quick check...making use of scan_node.
  1549. * We can skip unused nodes.
  1550. */
  1551. if (!nodes_empty(memcg->scan_nodes)) {
  1552. for (nid = first_node(memcg->scan_nodes);
  1553. nid < MAX_NUMNODES;
  1554. nid = next_node(nid, memcg->scan_nodes)) {
  1555. if (test_mem_cgroup_node_reclaimable(memcg, nid, noswap))
  1556. return true;
  1557. }
  1558. }
  1559. /*
  1560. * Check rest of nodes.
  1561. */
  1562. for_each_node_state(nid, N_HIGH_MEMORY) {
  1563. if (node_isset(nid, memcg->scan_nodes))
  1564. continue;
  1565. if (test_mem_cgroup_node_reclaimable(memcg, nid, noswap))
  1566. return true;
  1567. }
  1568. return false;
  1569. }
  1570. #else
  1571. int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
  1572. {
  1573. return 0;
  1574. }
  1575. static bool mem_cgroup_reclaimable(struct mem_cgroup *memcg, bool noswap)
  1576. {
  1577. return test_mem_cgroup_node_reclaimable(memcg, 0, noswap);
  1578. }
  1579. #endif
  1580. static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg,
  1581. struct zone *zone,
  1582. gfp_t gfp_mask,
  1583. unsigned long *total_scanned)
  1584. {
  1585. struct mem_cgroup *victim = NULL;
  1586. int total = 0;
  1587. int loop = 0;
  1588. unsigned long excess;
  1589. unsigned long nr_scanned;
  1590. struct mem_cgroup_reclaim_cookie reclaim = {
  1591. .zone = zone,
  1592. .priority = 0,
  1593. };
  1594. excess = res_counter_soft_limit_excess(&root_memcg->res) >> PAGE_SHIFT;
  1595. while (1) {
  1596. victim = mem_cgroup_iter(root_memcg, victim, &reclaim);
  1597. if (!victim) {
  1598. loop++;
  1599. if (loop >= 2) {
  1600. /*
  1601. * If we have not been able to reclaim
  1602. * anything, it might because there are
  1603. * no reclaimable pages under this hierarchy
  1604. */
  1605. if (!total)
  1606. break;
  1607. /*
  1608. * We want to do more targeted reclaim.
  1609. * excess >> 2 is not to excessive so as to
  1610. * reclaim too much, nor too less that we keep
  1611. * coming back to reclaim from this cgroup
  1612. */
  1613. if (total >= (excess >> 2) ||
  1614. (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS))
  1615. break;
  1616. }
  1617. continue;
  1618. }
  1619. if (!mem_cgroup_reclaimable(victim, false))
  1620. continue;
  1621. total += mem_cgroup_shrink_node_zone(victim, gfp_mask, false,
  1622. zone, &nr_scanned);
  1623. *total_scanned += nr_scanned;
  1624. if (!res_counter_soft_limit_excess(&root_memcg->res))
  1625. break;
  1626. }
  1627. mem_cgroup_iter_break(root_memcg, victim);
  1628. return total;
  1629. }
  1630. /*
  1631. * Check OOM-Killer is already running under our hierarchy.
  1632. * If someone is running, return false.
  1633. * Has to be called with memcg_oom_lock
  1634. */
  1635. static bool mem_cgroup_oom_lock(struct mem_cgroup *memcg)
  1636. {
  1637. struct mem_cgroup *iter, *failed = NULL;
  1638. for_each_mem_cgroup_tree(iter, memcg) {
  1639. if (iter->oom_lock) {
  1640. /*
  1641. * this subtree of our hierarchy is already locked
  1642. * so we cannot give a lock.
  1643. */
  1644. failed = iter;
  1645. mem_cgroup_iter_break(memcg, iter);
  1646. break;
  1647. } else
  1648. iter->oom_lock = true;
  1649. }
  1650. if (!failed)
  1651. return true;
  1652. /*
  1653. * OK, we failed to lock the whole subtree so we have to clean up
  1654. * what we set up to the failing subtree
  1655. */
  1656. for_each_mem_cgroup_tree(iter, memcg) {
  1657. if (iter == failed) {
  1658. mem_cgroup_iter_break(memcg, iter);
  1659. break;
  1660. }
  1661. iter->oom_lock = false;
  1662. }
  1663. return false;
  1664. }
  1665. /*
  1666. * Has to be called with memcg_oom_lock
  1667. */
  1668. static int mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
  1669. {
  1670. struct mem_cgroup *iter;
  1671. for_each_mem_cgroup_tree(iter, memcg)
  1672. iter->oom_lock = false;
  1673. return 0;
  1674. }
  1675. static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
  1676. {
  1677. struct mem_cgroup *iter;
  1678. for_each_mem_cgroup_tree(iter, memcg)
  1679. atomic_inc(&iter->under_oom);
  1680. }
  1681. static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
  1682. {
  1683. struct mem_cgroup *iter;
  1684. /*
  1685. * When a new child is created while the hierarchy is under oom,
  1686. * mem_cgroup_oom_lock() may not be called. We have to use
  1687. * atomic_add_unless() here.
  1688. */
  1689. for_each_mem_cgroup_tree(iter, memcg)
  1690. atomic_add_unless(&iter->under_oom, -1, 0);
  1691. }
  1692. static DEFINE_SPINLOCK(memcg_oom_lock);
  1693. static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
  1694. struct oom_wait_info {
  1695. struct mem_cgroup *memcg;
  1696. wait_queue_t wait;
  1697. };
  1698. static int memcg_oom_wake_function(wait_queue_t *wait,
  1699. unsigned mode, int sync, void *arg)
  1700. {
  1701. struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg;
  1702. struct mem_cgroup *oom_wait_memcg;
  1703. struct oom_wait_info *oom_wait_info;
  1704. oom_wait_info = container_of(wait, struct oom_wait_info, wait);
  1705. oom_wait_memcg = oom_wait_info->memcg;
  1706. /*
  1707. * Both of oom_wait_info->memcg and wake_memcg are stable under us.
  1708. * Then we can use css_is_ancestor without taking care of RCU.
  1709. */
  1710. if (!mem_cgroup_same_or_subtree(oom_wait_memcg, wake_memcg)
  1711. && !mem_cgroup_same_or_subtree(wake_memcg, oom_wait_memcg))
  1712. return 0;
  1713. return autoremove_wake_function(wait, mode, sync, arg);
  1714. }
  1715. static void memcg_wakeup_oom(struct mem_cgroup *memcg)
  1716. {
  1717. /* for filtering, pass "memcg" as argument. */
  1718. __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
  1719. }
  1720. static void memcg_oom_recover(struct mem_cgroup *memcg)
  1721. {
  1722. if (memcg && atomic_read(&memcg->under_oom))
  1723. memcg_wakeup_oom(memcg);
  1724. }
  1725. /*
  1726. * try to call OOM killer. returns false if we should exit memory-reclaim loop.
  1727. */
  1728. static bool mem_cgroup_handle_oom(struct mem_cgroup *memcg, gfp_t mask,
  1729. int order)
  1730. {
  1731. struct oom_wait_info owait;
  1732. bool locked, need_to_kill;
  1733. owait.memcg = memcg;
  1734. owait.wait.flags = 0;
  1735. owait.wait.func = memcg_oom_wake_function;
  1736. owait.wait.private = current;
  1737. INIT_LIST_HEAD(&owait.wait.task_list);
  1738. need_to_kill = true;
  1739. mem_cgroup_mark_under_oom(memcg);
  1740. /* At first, try to OOM lock hierarchy under memcg.*/
  1741. spin_lock(&memcg_oom_lock);
  1742. locked = mem_cgroup_oom_lock(memcg);
  1743. /*
  1744. * Even if signal_pending(), we can't quit charge() loop without
  1745. * accounting. So, UNINTERRUPTIBLE is appropriate. But SIGKILL
  1746. * under OOM is always welcomed, use TASK_KILLABLE here.
  1747. */
  1748. prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
  1749. if (!locked || memcg->oom_kill_disable)
  1750. need_to_kill = false;
  1751. if (locked)
  1752. mem_cgroup_oom_notify(memcg);
  1753. spin_unlock(&memcg_oom_lock);
  1754. if (need_to_kill) {
  1755. finish_wait(&memcg_oom_waitq, &owait.wait);
  1756. mem_cgroup_out_of_memory(memcg, mask, order);
  1757. } else {
  1758. schedule();
  1759. finish_wait(&memcg_oom_waitq, &owait.wait);
  1760. }
  1761. spin_lock(&memcg_oom_lock);
  1762. if (locked)
  1763. mem_cgroup_oom_unlock(memcg);
  1764. memcg_wakeup_oom(memcg);
  1765. spin_unlock(&memcg_oom_lock);
  1766. mem_cgroup_unmark_under_oom(memcg);
  1767. if (test_thread_flag(TIF_MEMDIE) || fatal_signal_pending(current))
  1768. return false;
  1769. /* Give chance to dying process */
  1770. schedule_timeout_uninterruptible(1);
  1771. return true;
  1772. }
  1773. /*
  1774. * Currently used to update mapped file statistics, but the routine can be
  1775. * generalized to update other statistics as well.
  1776. *
  1777. * Notes: Race condition
  1778. *
  1779. * We usually use page_cgroup_lock() for accessing page_cgroup member but
  1780. * it tends to be costly. But considering some conditions, we doesn't need
  1781. * to do so _always_.
  1782. *
  1783. * Considering "charge", lock_page_cgroup() is not required because all
  1784. * file-stat operations happen after a page is attached to radix-tree. There
  1785. * are no race with "charge".
  1786. *
  1787. * Considering "uncharge", we know that memcg doesn't clear pc->mem_cgroup
  1788. * at "uncharge" intentionally. So, we always see valid pc->mem_cgroup even
  1789. * if there are race with "uncharge". Statistics itself is properly handled
  1790. * by flags.
  1791. *
  1792. * Considering "move", this is an only case we see a race. To make the race
  1793. * small, we check mm->moving_account and detect there are possibility of race
  1794. * If there is, we take a lock.
  1795. */
  1796. void __mem_cgroup_begin_update_page_stat(struct page *page,
  1797. bool *locked, unsigned long *flags)
  1798. {
  1799. struct mem_cgroup *memcg;
  1800. struct page_cgroup *pc;
  1801. pc = lookup_page_cgroup(page);
  1802. again:
  1803. memcg = pc->mem_cgroup;
  1804. if (unlikely(!memcg || !PageCgroupUsed(pc)))
  1805. return;
  1806. /*
  1807. * If this memory cgroup is not under account moving, we don't
  1808. * need to take move_lock_mem_cgroup(). Because we already hold
  1809. * rcu_read_lock(), any calls to move_account will be delayed until
  1810. * rcu_read_unlock() if mem_cgroup_stolen() == true.
  1811. */
  1812. if (!mem_cgroup_stolen(memcg))
  1813. return;
  1814. move_lock_mem_cgroup(memcg, flags);
  1815. if (memcg != pc->mem_cgroup || !PageCgroupUsed(pc)) {
  1816. move_unlock_mem_cgroup(memcg, flags);
  1817. goto again;
  1818. }
  1819. *locked = true;
  1820. }
  1821. void __mem_cgroup_end_update_page_stat(struct page *page, unsigned long *flags)
  1822. {
  1823. struct page_cgroup *pc = lookup_page_cgroup(page);
  1824. /*
  1825. * It's guaranteed that pc->mem_cgroup never changes while
  1826. * lock is held because a routine modifies pc->mem_cgroup
  1827. * should take move_lock_mem_cgroup().
  1828. */
  1829. move_unlock_mem_cgroup(pc->mem_cgroup, flags);
  1830. }
  1831. void mem_cgroup_update_page_stat(struct page *page,
  1832. enum mem_cgroup_page_stat_item idx, int val)
  1833. {
  1834. struct mem_cgroup *memcg;
  1835. struct page_cgroup *pc = lookup_page_cgroup(page);
  1836. unsigned long uninitialized_var(flags);
  1837. if (mem_cgroup_disabled())
  1838. return;
  1839. memcg = pc->mem_cgroup;
  1840. if (unlikely(!memcg || !PageCgroupUsed(pc)))
  1841. return;
  1842. switch (idx) {
  1843. case MEMCG_NR_FILE_MAPPED:
  1844. idx = MEM_CGROUP_STAT_FILE_MAPPED;
  1845. break;
  1846. default:
  1847. BUG();
  1848. }
  1849. this_cpu_add(memcg->stat->count[idx], val);
  1850. }
  1851. /*
  1852. * size of first charge trial. "32" comes from vmscan.c's magic value.
  1853. * TODO: maybe necessary to use big numbers in big irons.
  1854. */
  1855. #define CHARGE_BATCH 32U
  1856. struct memcg_stock_pcp {
  1857. struct mem_cgroup *cached; /* this never be root cgroup */
  1858. unsigned int nr_pages;
  1859. struct work_struct work;
  1860. unsigned long flags;
  1861. #define FLUSHING_CACHED_CHARGE 0
  1862. };
  1863. static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
  1864. static DEFINE_MUTEX(percpu_charge_mutex);
  1865. /**
  1866. * consume_stock: Try to consume stocked charge on this cpu.
  1867. * @memcg: memcg to consume from.
  1868. * @nr_pages: how many pages to charge.
  1869. *
  1870. * The charges will only happen if @memcg matches the current cpu's memcg
  1871. * stock, and at least @nr_pages are available in that stock. Failure to
  1872. * service an allocation will refill the stock.
  1873. *
  1874. * returns true if successful, false otherwise.
  1875. */
  1876. static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
  1877. {
  1878. struct memcg_stock_pcp *stock;
  1879. bool ret = true;
  1880. if (nr_pages > CHARGE_BATCH)
  1881. return false;
  1882. stock = &get_cpu_var(memcg_stock);
  1883. if (memcg == stock->cached && stock->nr_pages >= nr_pages)
  1884. stock->nr_pages -= nr_pages;
  1885. else /* need to call res_counter_charge */
  1886. ret = false;
  1887. put_cpu_var(memcg_stock);
  1888. return ret;
  1889. }
  1890. /*
  1891. * Returns stocks cached in percpu to res_counter and reset cached information.
  1892. */
  1893. static void drain_stock(struct memcg_stock_pcp *stock)
  1894. {
  1895. struct mem_cgroup *old = stock->cached;
  1896. if (stock->nr_pages) {
  1897. unsigned long bytes = stock->nr_pages * PAGE_SIZE;
  1898. res_counter_uncharge(&old->res, bytes);
  1899. if (do_swap_account)
  1900. res_counter_uncharge(&old->memsw, bytes);
  1901. stock->nr_pages = 0;
  1902. }
  1903. stock->cached = NULL;
  1904. }
  1905. /*
  1906. * This must be called under preempt disabled or must be called by
  1907. * a thread which is pinned to local cpu.
  1908. */
  1909. static void drain_local_stock(struct work_struct *dummy)
  1910. {
  1911. struct memcg_stock_pcp *stock = &__get_cpu_var(memcg_stock);
  1912. drain_stock(stock);
  1913. clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
  1914. }
  1915. /*
  1916. * Cache charges(val) which is from res_counter, to local per_cpu area.
  1917. * This will be consumed by consume_stock() function, later.
  1918. */
  1919. static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
  1920. {
  1921. struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock);
  1922. if (stock->cached != memcg) { /* reset if necessary */
  1923. drain_stock(stock);
  1924. stock->cached = memcg;
  1925. }
  1926. stock->nr_pages += nr_pages;
  1927. put_cpu_var(memcg_stock);
  1928. }
  1929. /*
  1930. * Drains all per-CPU charge caches for given root_memcg resp. subtree
  1931. * of the hierarchy under it. sync flag says whether we should block
  1932. * until the work is done.
  1933. */
  1934. static void drain_all_stock(struct mem_cgroup *root_memcg, bool sync)
  1935. {
  1936. int cpu, curcpu;
  1937. /* Notify other cpus that system-wide "drain" is running */
  1938. get_online_cpus();
  1939. curcpu = get_cpu();
  1940. for_each_online_cpu(cpu) {
  1941. struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
  1942. struct mem_cgroup *memcg;
  1943. memcg = stock->cached;
  1944. if (!memcg || !stock->nr_pages)
  1945. continue;
  1946. if (!mem_cgroup_same_or_subtree(root_memcg, memcg))
  1947. continue;
  1948. if (!test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
  1949. if (cpu == curcpu)
  1950. drain_local_stock(&stock->work);
  1951. else
  1952. schedule_work_on(cpu, &stock->work);
  1953. }
  1954. }
  1955. put_cpu();
  1956. if (!sync)
  1957. goto out;
  1958. for_each_online_cpu(cpu) {
  1959. struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
  1960. if (test_bit(FLUSHING_CACHED_CHARGE, &stock->flags))
  1961. flush_work(&stock->work);
  1962. }
  1963. out:
  1964. put_online_cpus();
  1965. }
  1966. /*
  1967. * Tries to drain stocked charges in other cpus. This function is asynchronous
  1968. * and just put a work per cpu for draining localy on each cpu. Caller can
  1969. * expects some charges will be back to res_counter later but cannot wait for
  1970. * it.
  1971. */
  1972. static void drain_all_stock_async(struct mem_cgroup *root_memcg)
  1973. {
  1974. /*
  1975. * If someone calls draining, avoid adding more kworker runs.
  1976. */
  1977. if (!mutex_trylock(&percpu_charge_mutex))
  1978. return;
  1979. drain_all_stock(root_memcg, false);
  1980. mutex_unlock(&percpu_charge_mutex);
  1981. }
  1982. /* This is a synchronous drain interface. */
  1983. static void drain_all_stock_sync(struct mem_cgroup *root_memcg)
  1984. {
  1985. /* called when force_empty is called */
  1986. mutex_lock(&percpu_charge_mutex);
  1987. drain_all_stock(root_memcg, true);
  1988. mutex_unlock(&percpu_charge_mutex);
  1989. }
  1990. /*
  1991. * This function drains percpu counter value from DEAD cpu and
  1992. * move it to local cpu. Note that this function can be preempted.
  1993. */
  1994. static void mem_cgroup_drain_pcp_counter(struct mem_cgroup *memcg, int cpu)
  1995. {
  1996. int i;
  1997. spin_lock(&memcg->pcp_counter_lock);
  1998. for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
  1999. long x = per_cpu(memcg->stat->count[i], cpu);
  2000. per_cpu(memcg->stat->count[i], cpu) = 0;
  2001. memcg->nocpu_base.count[i] += x;
  2002. }
  2003. for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
  2004. unsigned long x = per_cpu(memcg->stat->events[i], cpu);
  2005. per_cpu(memcg->stat->events[i], cpu) = 0;
  2006. memcg->nocpu_base.events[i] += x;
  2007. }
  2008. spin_unlock(&memcg->pcp_counter_lock);
  2009. }
  2010. static int __cpuinit memcg_cpu_hotplug_callback(struct notifier_block *nb,
  2011. unsigned long action,
  2012. void *hcpu)
  2013. {
  2014. int cpu = (unsigned long)hcpu;
  2015. struct memcg_stock_pcp *stock;
  2016. struct mem_cgroup *iter;
  2017. if (action == CPU_ONLINE)
  2018. return NOTIFY_OK;
  2019. if (action != CPU_DEAD && action != CPU_DEAD_FROZEN)
  2020. return NOTIFY_OK;
  2021. for_each_mem_cgroup(iter)
  2022. mem_cgroup_drain_pcp_counter(iter, cpu);
  2023. stock = &per_cpu(memcg_stock, cpu);
  2024. drain_stock(stock);
  2025. return NOTIFY_OK;
  2026. }
  2027. /* See __mem_cgroup_try_charge() for details */
  2028. enum {
  2029. CHARGE_OK, /* success */
  2030. CHARGE_RETRY, /* need to retry but retry is not bad */
  2031. CHARGE_NOMEM, /* we can't do more. return -ENOMEM */
  2032. CHARGE_WOULDBLOCK, /* GFP_WAIT wasn't set and no enough res. */
  2033. CHARGE_OOM_DIE, /* the current is killed because of OOM */
  2034. };
  2035. static int mem_cgroup_do_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
  2036. unsigned int nr_pages, unsigned int min_pages,
  2037. bool oom_check)
  2038. {
  2039. unsigned long csize = nr_pages * PAGE_SIZE;
  2040. struct mem_cgroup *mem_over_limit;
  2041. struct res_counter *fail_res;
  2042. unsigned long flags = 0;
  2043. int ret;
  2044. ret = res_counter_charge(&memcg->res, csize, &fail_res);
  2045. if (likely(!ret)) {
  2046. if (!do_swap_account)
  2047. return CHARGE_OK;
  2048. ret = res_counter_charge(&memcg->memsw, csize, &fail_res);
  2049. if (likely(!ret))
  2050. return CHARGE_OK;
  2051. res_counter_uncharge(&memcg->res, csize);
  2052. mem_over_limit = mem_cgroup_from_res_counter(fail_res, memsw);
  2053. flags |= MEM_CGROUP_RECLAIM_NOSWAP;
  2054. } else
  2055. mem_over_limit = mem_cgroup_from_res_counter(fail_res, res);
  2056. /*
  2057. * Never reclaim on behalf of optional batching, retry with a
  2058. * single page instead.
  2059. */
  2060. if (nr_pages > min_pages)
  2061. return CHARGE_RETRY;
  2062. if (!(gfp_mask & __GFP_WAIT))
  2063. return CHARGE_WOULDBLOCK;
  2064. if (gfp_mask & __GFP_NORETRY)
  2065. return CHARGE_NOMEM;
  2066. ret = mem_cgroup_reclaim(mem_over_limit, gfp_mask, flags);
  2067. if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
  2068. return CHARGE_RETRY;
  2069. /*
  2070. * Even though the limit is exceeded at this point, reclaim
  2071. * may have been able to free some pages. Retry the charge
  2072. * before killing the task.
  2073. *
  2074. * Only for regular pages, though: huge pages are rather
  2075. * unlikely to succeed so close to the limit, and we fall back
  2076. * to regular pages anyway in case of failure.
  2077. */
  2078. if (nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER) && ret)
  2079. return CHARGE_RETRY;
  2080. /*
  2081. * At task move, charge accounts can be doubly counted. So, it's
  2082. * better to wait until the end of task_move if something is going on.
  2083. */
  2084. if (mem_cgroup_wait_acct_move(mem_over_limit))
  2085. return CHARGE_RETRY;
  2086. /* If we don't need to call oom-killer at el, return immediately */
  2087. if (!oom_check)
  2088. return CHARGE_NOMEM;
  2089. /* check OOM */
  2090. if (!mem_cgroup_handle_oom(mem_over_limit, gfp_mask, get_order(csize)))
  2091. return CHARGE_OOM_DIE;
  2092. return CHARGE_RETRY;
  2093. }
  2094. /*
  2095. * __mem_cgroup_try_charge() does
  2096. * 1. detect memcg to be charged against from passed *mm and *ptr,
  2097. * 2. update res_counter
  2098. * 3. call memory reclaim if necessary.
  2099. *
  2100. * In some special case, if the task is fatal, fatal_signal_pending() or
  2101. * has TIF_MEMDIE, this function returns -EINTR while writing root_mem_cgroup
  2102. * to *ptr. There are two reasons for this. 1: fatal threads should quit as soon
  2103. * as possible without any hazards. 2: all pages should have a valid
  2104. * pc->mem_cgroup. If mm is NULL and the caller doesn't pass a valid memcg
  2105. * pointer, that is treated as a charge to root_mem_cgroup.
  2106. *
  2107. * So __mem_cgroup_try_charge() will return
  2108. * 0 ... on success, filling *ptr with a valid memcg pointer.
  2109. * -ENOMEM ... charge failure because of resource limits.
  2110. * -EINTR ... if thread is fatal. *ptr is filled with root_mem_cgroup.
  2111. *
  2112. * Unlike the exported interface, an "oom" parameter is added. if oom==true,
  2113. * the oom-killer can be invoked.
  2114. */
  2115. static int __mem_cgroup_try_charge(struct mm_struct *mm,
  2116. gfp_t gfp_mask,
  2117. unsigned int nr_pages,
  2118. struct mem_cgroup **ptr,
  2119. bool oom)
  2120. {
  2121. unsigned int batch = max(CHARGE_BATCH, nr_pages);
  2122. int nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
  2123. struct mem_cgroup *memcg = NULL;
  2124. int ret;
  2125. /*
  2126. * Unlike gloval-vm's OOM-kill, we're not in memory shortage
  2127. * in system level. So, allow to go ahead dying process in addition to
  2128. * MEMDIE process.
  2129. */
  2130. if (unlikely(test_thread_flag(TIF_MEMDIE)
  2131. || fatal_signal_pending(current)))
  2132. goto bypass;
  2133. /*
  2134. * We always charge the cgroup the mm_struct belongs to.
  2135. * The mm_struct's mem_cgroup changes on task migration if the
  2136. * thread group leader migrates. It's possible that mm is not
  2137. * set, if so charge the root memcg (happens for pagecache usage).
  2138. */
  2139. if (!*ptr && !mm)
  2140. *ptr = root_mem_cgroup;
  2141. again:
  2142. if (*ptr) { /* css should be a valid one */
  2143. memcg = *ptr;
  2144. VM_BUG_ON(css_is_removed(&memcg->css));
  2145. if (mem_cgroup_is_root(memcg))
  2146. goto done;
  2147. if (consume_stock(memcg, nr_pages))
  2148. goto done;
  2149. css_get(&memcg->css);
  2150. } else {
  2151. struct task_struct *p;
  2152. rcu_read_lock();
  2153. p = rcu_dereference(mm->owner);
  2154. /*
  2155. * Because we don't have task_lock(), "p" can exit.
  2156. * In that case, "memcg" can point to root or p can be NULL with
  2157. * race with swapoff. Then, we have small risk of mis-accouning.
  2158. * But such kind of mis-account by race always happens because
  2159. * we don't have cgroup_mutex(). It's overkill and we allo that
  2160. * small race, here.
  2161. * (*) swapoff at el will charge against mm-struct not against
  2162. * task-struct. So, mm->owner can be NULL.
  2163. */
  2164. memcg = mem_cgroup_from_task(p);
  2165. if (!memcg)
  2166. memcg = root_mem_cgroup;
  2167. if (mem_cgroup_is_root(memcg)) {
  2168. rcu_read_unlock();
  2169. goto done;
  2170. }
  2171. if (consume_stock(memcg, nr_pages)) {
  2172. /*
  2173. * It seems dagerous to access memcg without css_get().
  2174. * But considering how consume_stok works, it's not
  2175. * necessary. If consume_stock success, some charges
  2176. * from this memcg are cached on this cpu. So, we
  2177. * don't need to call css_get()/css_tryget() before
  2178. * calling consume_stock().
  2179. */
  2180. rcu_read_unlock();
  2181. goto done;
  2182. }
  2183. /* after here, we may be blocked. we need to get refcnt */
  2184. if (!css_tryget(&memcg->css)) {
  2185. rcu_read_unlock();
  2186. goto again;
  2187. }
  2188. rcu_read_unlock();
  2189. }
  2190. do {
  2191. bool oom_check;
  2192. /* If killed, bypass charge */
  2193. if (fatal_signal_pending(current)) {
  2194. css_put(&memcg->css);
  2195. goto bypass;
  2196. }
  2197. oom_check = false;
  2198. if (oom && !nr_oom_retries) {
  2199. oom_check = true;
  2200. nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
  2201. }
  2202. ret = mem_cgroup_do_charge(memcg, gfp_mask, batch, nr_pages,
  2203. oom_check);
  2204. switch (ret) {
  2205. case CHARGE_OK:
  2206. break;
  2207. case CHARGE_RETRY: /* not in OOM situation but retry */
  2208. batch = nr_pages;
  2209. css_put(&memcg->css);
  2210. memcg = NULL;
  2211. goto again;
  2212. case CHARGE_WOULDBLOCK: /* !__GFP_WAIT */
  2213. css_put(&memcg->css);
  2214. goto nomem;
  2215. case CHARGE_NOMEM: /* OOM routine works */
  2216. if (!oom) {
  2217. css_put(&memcg->css);
  2218. goto nomem;
  2219. }
  2220. /* If oom, we never return -ENOMEM */
  2221. nr_oom_retries--;
  2222. break;
  2223. case CHARGE_OOM_DIE: /* Killed by OOM Killer */
  2224. css_put(&memcg->css);
  2225. goto bypass;
  2226. }
  2227. } while (ret != CHARGE_OK);
  2228. if (batch > nr_pages)
  2229. refill_stock(memcg, batch - nr_pages);
  2230. css_put(&memcg->css);
  2231. done:
  2232. *ptr = memcg;
  2233. return 0;
  2234. nomem:
  2235. *ptr = NULL;
  2236. return -ENOMEM;
  2237. bypass:
  2238. *ptr = root_mem_cgroup;
  2239. return -EINTR;
  2240. }
  2241. /*
  2242. * Somemtimes we have to undo a charge we got by try_charge().
  2243. * This function is for that and do uncharge, put css's refcnt.
  2244. * gotten by try_charge().
  2245. */
  2246. static void __mem_cgroup_cancel_charge(struct mem_cgroup *memcg,
  2247. unsigned int nr_pages)
  2248. {
  2249. if (!mem_cgroup_is_root(memcg)) {
  2250. unsigned long bytes = nr_pages * PAGE_SIZE;
  2251. res_counter_uncharge(&memcg->res, bytes);
  2252. if (do_swap_account)
  2253. res_counter_uncharge(&memcg->memsw, bytes);
  2254. }
  2255. }
  2256. /*
  2257. * Cancel chrages in this cgroup....doesn't propagate to parent cgroup.
  2258. * This is useful when moving usage to parent cgroup.
  2259. */
  2260. static void __mem_cgroup_cancel_local_charge(struct mem_cgroup *memcg,
  2261. unsigned int nr_pages)
  2262. {
  2263. unsigned long bytes = nr_pages * PAGE_SIZE;
  2264. if (mem_cgroup_is_root(memcg))
  2265. return;
  2266. res_counter_uncharge_until(&memcg->res, memcg->res.parent, bytes);
  2267. if (do_swap_account)
  2268. res_counter_uncharge_until(&memcg->memsw,
  2269. memcg->memsw.parent, bytes);
  2270. }
  2271. /*
  2272. * A helper function to get mem_cgroup from ID. must be called under
  2273. * rcu_read_lock(). The caller must check css_is_removed() or some if
  2274. * it's concern. (dropping refcnt from swap can be called against removed
  2275. * memcg.)
  2276. */
  2277. static struct mem_cgroup *mem_cgroup_lookup(unsigned short id)
  2278. {
  2279. struct cgroup_subsys_state *css;
  2280. /* ID 0 is unused ID */
  2281. if (!id)
  2282. return NULL;
  2283. css = css_lookup(&mem_cgroup_subsys, id);
  2284. if (!css)
  2285. return NULL;
  2286. return mem_cgroup_from_css(css);
  2287. }
  2288. struct mem_cgroup *try_get_mem_cgroup_from_page(struct page *page)
  2289. {
  2290. struct mem_cgroup *memcg = NULL;
  2291. struct page_cgroup *pc;
  2292. unsigned short id;
  2293. swp_entry_t ent;
  2294. VM_BUG_ON(!PageLocked(page));
  2295. pc = lookup_page_cgroup(page);
  2296. lock_page_cgroup(pc);
  2297. if (PageCgroupUsed(pc)) {
  2298. memcg = pc->mem_cgroup;
  2299. if (memcg && !css_tryget(&memcg->css))
  2300. memcg = NULL;
  2301. } else if (PageSwapCache(page)) {
  2302. ent.val = page_private(page);
  2303. id = lookup_swap_cgroup_id(ent);
  2304. rcu_read_lock();
  2305. memcg = mem_cgroup_lookup(id);
  2306. if (memcg && !css_tryget(&memcg->css))
  2307. memcg = NULL;
  2308. rcu_read_unlock();
  2309. }
  2310. unlock_page_cgroup(pc);
  2311. return memcg;
  2312. }
  2313. static void __mem_cgroup_commit_charge(struct mem_cgroup *memcg,
  2314. struct page *page,
  2315. unsigned int nr_pages,
  2316. enum charge_type ctype,
  2317. bool lrucare)
  2318. {
  2319. struct page_cgroup *pc = lookup_page_cgroup(page);
  2320. struct zone *uninitialized_var(zone);
  2321. bool was_on_lru = false;
  2322. bool anon;
  2323. lock_page_cgroup(pc);
  2324. VM_BUG_ON(PageCgroupUsed(pc));
  2325. /*
  2326. * we don't need page_cgroup_lock about tail pages, becase they are not
  2327. * accessed by any other context at this point.
  2328. */
  2329. /*
  2330. * In some cases, SwapCache and FUSE(splice_buf->radixtree), the page
  2331. * may already be on some other mem_cgroup's LRU. Take care of it.
  2332. */
  2333. if (lrucare) {
  2334. zone = page_zone(page);
  2335. spin_lock_irq(&zone->lru_lock);
  2336. if (PageLRU(page)) {
  2337. ClearPageLRU(page);
  2338. del_page_from_lru_list(zone, page, page_lru(page));
  2339. was_on_lru = true;
  2340. }
  2341. }
  2342. pc->mem_cgroup = memcg;
  2343. /*
  2344. * We access a page_cgroup asynchronously without lock_page_cgroup().
  2345. * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
  2346. * is accessed after testing USED bit. To make pc->mem_cgroup visible
  2347. * before USED bit, we need memory barrier here.
  2348. * See mem_cgroup_add_lru_list(), etc.
  2349. */
  2350. smp_wmb();
  2351. SetPageCgroupUsed(pc);
  2352. if (lrucare) {
  2353. if (was_on_lru) {
  2354. VM_BUG_ON(PageLRU(page));
  2355. SetPageLRU(page);
  2356. add_page_to_lru_list(zone, page, page_lru(page));
  2357. }
  2358. spin_unlock_irq(&zone->lru_lock);
  2359. }
  2360. if (ctype == MEM_CGROUP_CHARGE_TYPE_ANON)
  2361. anon = true;
  2362. else
  2363. anon = false;
  2364. mem_cgroup_charge_statistics(memcg, anon, nr_pages);
  2365. unlock_page_cgroup(pc);
  2366. /*
  2367. * "charge_statistics" updated event counter. Then, check it.
  2368. * Insert ancestor (and ancestor's ancestors), to softlimit RB-tree.
  2369. * if they exceeds softlimit.
  2370. */
  2371. memcg_check_events(memcg, page);
  2372. }
  2373. #ifdef CONFIG_MEMCG_KMEM
  2374. static inline bool memcg_can_account_kmem(struct mem_cgroup *memcg)
  2375. {
  2376. return !mem_cgroup_disabled() && !mem_cgroup_is_root(memcg) &&
  2377. (memcg->kmem_account_flags & KMEM_ACCOUNTED_MASK);
  2378. }
  2379. static int memcg_charge_kmem(struct mem_cgroup *memcg, gfp_t gfp, u64 size)
  2380. {
  2381. struct res_counter *fail_res;
  2382. struct mem_cgroup *_memcg;
  2383. int ret = 0;
  2384. bool may_oom;
  2385. ret = res_counter_charge(&memcg->kmem, size, &fail_res);
  2386. if (ret)
  2387. return ret;
  2388. /*
  2389. * Conditions under which we can wait for the oom_killer. Those are
  2390. * the same conditions tested by the core page allocator
  2391. */
  2392. may_oom = (gfp & __GFP_FS) && !(gfp & __GFP_NORETRY);
  2393. _memcg = memcg;
  2394. ret = __mem_cgroup_try_charge(NULL, gfp, size >> PAGE_SHIFT,
  2395. &_memcg, may_oom);
  2396. if (ret == -EINTR) {
  2397. /*
  2398. * __mem_cgroup_try_charge() chosed to bypass to root due to
  2399. * OOM kill or fatal signal. Since our only options are to
  2400. * either fail the allocation or charge it to this cgroup, do
  2401. * it as a temporary condition. But we can't fail. From a
  2402. * kmem/slab perspective, the cache has already been selected,
  2403. * by mem_cgroup_kmem_get_cache(), so it is too late to change
  2404. * our minds.
  2405. *
  2406. * This condition will only trigger if the task entered
  2407. * memcg_charge_kmem in a sane state, but was OOM-killed during
  2408. * __mem_cgroup_try_charge() above. Tasks that were already
  2409. * dying when the allocation triggers should have been already
  2410. * directed to the root cgroup in memcontrol.h
  2411. */
  2412. res_counter_charge_nofail(&memcg->res, size, &fail_res);
  2413. if (do_swap_account)
  2414. res_counter_charge_nofail(&memcg->memsw, size,
  2415. &fail_res);
  2416. ret = 0;
  2417. } else if (ret)
  2418. res_counter_uncharge(&memcg->kmem, size);
  2419. return ret;
  2420. }
  2421. static void memcg_uncharge_kmem(struct mem_cgroup *memcg, u64 size)
  2422. {
  2423. res_counter_uncharge(&memcg->res, size);
  2424. if (do_swap_account)
  2425. res_counter_uncharge(&memcg->memsw, size);
  2426. /* Not down to 0 */
  2427. if (res_counter_uncharge(&memcg->kmem, size))
  2428. return;
  2429. if (memcg_kmem_test_and_clear_dead(memcg))
  2430. mem_cgroup_put(memcg);
  2431. }
  2432. /*
  2433. * We need to verify if the allocation against current->mm->owner's memcg is
  2434. * possible for the given order. But the page is not allocated yet, so we'll
  2435. * need a further commit step to do the final arrangements.
  2436. *
  2437. * It is possible for the task to switch cgroups in this mean time, so at
  2438. * commit time, we can't rely on task conversion any longer. We'll then use
  2439. * the handle argument to return to the caller which cgroup we should commit
  2440. * against. We could also return the memcg directly and avoid the pointer
  2441. * passing, but a boolean return value gives better semantics considering
  2442. * the compiled-out case as well.
  2443. *
  2444. * Returning true means the allocation is possible.
  2445. */
  2446. bool
  2447. __memcg_kmem_newpage_charge(gfp_t gfp, struct mem_cgroup **_memcg, int order)
  2448. {
  2449. struct mem_cgroup *memcg;
  2450. int ret;
  2451. *_memcg = NULL;
  2452. memcg = try_get_mem_cgroup_from_mm(current->mm);
  2453. /*
  2454. * very rare case described in mem_cgroup_from_task. Unfortunately there
  2455. * isn't much we can do without complicating this too much, and it would
  2456. * be gfp-dependent anyway. Just let it go
  2457. */
  2458. if (unlikely(!memcg))
  2459. return true;
  2460. if (!memcg_can_account_kmem(memcg)) {
  2461. css_put(&memcg->css);
  2462. return true;
  2463. }
  2464. ret = memcg_charge_kmem(memcg, gfp, PAGE_SIZE << order);
  2465. if (!ret)
  2466. *_memcg = memcg;
  2467. css_put(&memcg->css);
  2468. return (ret == 0);
  2469. }
  2470. void __memcg_kmem_commit_charge(struct page *page, struct mem_cgroup *memcg,
  2471. int order)
  2472. {
  2473. struct page_cgroup *pc;
  2474. VM_BUG_ON(mem_cgroup_is_root(memcg));
  2475. /* The page allocation failed. Revert */
  2476. if (!page) {
  2477. memcg_uncharge_kmem(memcg, PAGE_SIZE << order);
  2478. return;
  2479. }
  2480. pc = lookup_page_cgroup(page);
  2481. lock_page_cgroup(pc);
  2482. pc->mem_cgroup = memcg;
  2483. SetPageCgroupUsed(pc);
  2484. unlock_page_cgroup(pc);
  2485. }
  2486. void __memcg_kmem_uncharge_pages(struct page *page, int order)
  2487. {
  2488. struct mem_cgroup *memcg = NULL;
  2489. struct page_cgroup *pc;
  2490. pc = lookup_page_cgroup(page);
  2491. /*
  2492. * Fast unlocked return. Theoretically might have changed, have to
  2493. * check again after locking.
  2494. */
  2495. if (!PageCgroupUsed(pc))
  2496. return;
  2497. lock_page_cgroup(pc);
  2498. if (PageCgroupUsed(pc)) {
  2499. memcg = pc->mem_cgroup;
  2500. ClearPageCgroupUsed(pc);
  2501. }
  2502. unlock_page_cgroup(pc);
  2503. /*
  2504. * We trust that only if there is a memcg associated with the page, it
  2505. * is a valid allocation
  2506. */
  2507. if (!memcg)
  2508. return;
  2509. VM_BUG_ON(mem_cgroup_is_root(memcg));
  2510. memcg_uncharge_kmem(memcg, PAGE_SIZE << order);
  2511. }
  2512. #endif /* CONFIG_MEMCG_KMEM */
  2513. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  2514. #define PCGF_NOCOPY_AT_SPLIT (1 << PCG_LOCK | 1 << PCG_MIGRATION)
  2515. /*
  2516. * Because tail pages are not marked as "used", set it. We're under
  2517. * zone->lru_lock, 'splitting on pmd' and compound_lock.
  2518. * charge/uncharge will be never happen and move_account() is done under
  2519. * compound_lock(), so we don't have to take care of races.
  2520. */
  2521. void mem_cgroup_split_huge_fixup(struct page *head)
  2522. {
  2523. struct page_cgroup *head_pc = lookup_page_cgroup(head);
  2524. struct page_cgroup *pc;
  2525. int i;
  2526. if (mem_cgroup_disabled())
  2527. return;
  2528. for (i = 1; i < HPAGE_PMD_NR; i++) {
  2529. pc = head_pc + i;
  2530. pc->mem_cgroup = head_pc->mem_cgroup;
  2531. smp_wmb();/* see __commit_charge() */
  2532. pc->flags = head_pc->flags & ~PCGF_NOCOPY_AT_SPLIT;
  2533. }
  2534. }
  2535. #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
  2536. /**
  2537. * mem_cgroup_move_account - move account of the page
  2538. * @page: the page
  2539. * @nr_pages: number of regular pages (>1 for huge pages)
  2540. * @pc: page_cgroup of the page.
  2541. * @from: mem_cgroup which the page is moved from.
  2542. * @to: mem_cgroup which the page is moved to. @from != @to.
  2543. *
  2544. * The caller must confirm following.
  2545. * - page is not on LRU (isolate_page() is useful.)
  2546. * - compound_lock is held when nr_pages > 1
  2547. *
  2548. * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
  2549. * from old cgroup.
  2550. */
  2551. static int mem_cgroup_move_account(struct page *page,
  2552. unsigned int nr_pages,
  2553. struct page_cgroup *pc,
  2554. struct mem_cgroup *from,
  2555. struct mem_cgroup *to)
  2556. {
  2557. unsigned long flags;
  2558. int ret;
  2559. bool anon = PageAnon(page);
  2560. VM_BUG_ON(from == to);
  2561. VM_BUG_ON(PageLRU(page));
  2562. /*
  2563. * The page is isolated from LRU. So, collapse function
  2564. * will not handle this page. But page splitting can happen.
  2565. * Do this check under compound_page_lock(). The caller should
  2566. * hold it.
  2567. */
  2568. ret = -EBUSY;
  2569. if (nr_pages > 1 && !PageTransHuge(page))
  2570. goto out;
  2571. lock_page_cgroup(pc);
  2572. ret = -EINVAL;
  2573. if (!PageCgroupUsed(pc) || pc->mem_cgroup != from)
  2574. goto unlock;
  2575. move_lock_mem_cgroup(from, &flags);
  2576. if (!anon && page_mapped(page)) {
  2577. /* Update mapped_file data for mem_cgroup */
  2578. preempt_disable();
  2579. __this_cpu_dec(from->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
  2580. __this_cpu_inc(to->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
  2581. preempt_enable();
  2582. }
  2583. mem_cgroup_charge_statistics(from, anon, -nr_pages);
  2584. /* caller should have done css_get */
  2585. pc->mem_cgroup = to;
  2586. mem_cgroup_charge_statistics(to, anon, nr_pages);
  2587. /*
  2588. * We charges against "to" which may not have any tasks. Then, "to"
  2589. * can be under rmdir(). But in current implementation, caller of
  2590. * this function is just force_empty() and move charge, so it's
  2591. * guaranteed that "to" is never removed. So, we don't check rmdir
  2592. * status here.
  2593. */
  2594. move_unlock_mem_cgroup(from, &flags);
  2595. ret = 0;
  2596. unlock:
  2597. unlock_page_cgroup(pc);
  2598. /*
  2599. * check events
  2600. */
  2601. memcg_check_events(to, page);
  2602. memcg_check_events(from, page);
  2603. out:
  2604. return ret;
  2605. }
  2606. /**
  2607. * mem_cgroup_move_parent - moves page to the parent group
  2608. * @page: the page to move
  2609. * @pc: page_cgroup of the page
  2610. * @child: page's cgroup
  2611. *
  2612. * move charges to its parent or the root cgroup if the group has no
  2613. * parent (aka use_hierarchy==0).
  2614. * Although this might fail (get_page_unless_zero, isolate_lru_page or
  2615. * mem_cgroup_move_account fails) the failure is always temporary and
  2616. * it signals a race with a page removal/uncharge or migration. In the
  2617. * first case the page is on the way out and it will vanish from the LRU
  2618. * on the next attempt and the call should be retried later.
  2619. * Isolation from the LRU fails only if page has been isolated from
  2620. * the LRU since we looked at it and that usually means either global
  2621. * reclaim or migration going on. The page will either get back to the
  2622. * LRU or vanish.
  2623. * Finaly mem_cgroup_move_account fails only if the page got uncharged
  2624. * (!PageCgroupUsed) or moved to a different group. The page will
  2625. * disappear in the next attempt.
  2626. */
  2627. static int mem_cgroup_move_parent(struct page *page,
  2628. struct page_cgroup *pc,
  2629. struct mem_cgroup *child)
  2630. {
  2631. struct mem_cgroup *parent;
  2632. unsigned int nr_pages;
  2633. unsigned long uninitialized_var(flags);
  2634. int ret;
  2635. VM_BUG_ON(mem_cgroup_is_root(child));
  2636. ret = -EBUSY;
  2637. if (!get_page_unless_zero(page))
  2638. goto out;
  2639. if (isolate_lru_page(page))
  2640. goto put;
  2641. nr_pages = hpage_nr_pages(page);
  2642. parent = parent_mem_cgroup(child);
  2643. /*
  2644. * If no parent, move charges to root cgroup.
  2645. */
  2646. if (!parent)
  2647. parent = root_mem_cgroup;
  2648. if (nr_pages > 1) {
  2649. VM_BUG_ON(!PageTransHuge(page));
  2650. flags = compound_lock_irqsave(page);
  2651. }
  2652. ret = mem_cgroup_move_account(page, nr_pages,
  2653. pc, child, parent);
  2654. if (!ret)
  2655. __mem_cgroup_cancel_local_charge(child, nr_pages);
  2656. if (nr_pages > 1)
  2657. compound_unlock_irqrestore(page, flags);
  2658. putback_lru_page(page);
  2659. put:
  2660. put_page(page);
  2661. out:
  2662. return ret;
  2663. }
  2664. /*
  2665. * Charge the memory controller for page usage.
  2666. * Return
  2667. * 0 if the charge was successful
  2668. * < 0 if the cgroup is over its limit
  2669. */
  2670. static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
  2671. gfp_t gfp_mask, enum charge_type ctype)
  2672. {
  2673. struct mem_cgroup *memcg = NULL;
  2674. unsigned int nr_pages = 1;
  2675. bool oom = true;
  2676. int ret;
  2677. if (PageTransHuge(page)) {
  2678. nr_pages <<= compound_order(page);
  2679. VM_BUG_ON(!PageTransHuge(page));
  2680. /*
  2681. * Never OOM-kill a process for a huge page. The
  2682. * fault handler will fall back to regular pages.
  2683. */
  2684. oom = false;
  2685. }
  2686. ret = __mem_cgroup_try_charge(mm, gfp_mask, nr_pages, &memcg, oom);
  2687. if (ret == -ENOMEM)
  2688. return ret;
  2689. __mem_cgroup_commit_charge(memcg, page, nr_pages, ctype, false);
  2690. return 0;
  2691. }
  2692. int mem_cgroup_newpage_charge(struct page *page,
  2693. struct mm_struct *mm, gfp_t gfp_mask)
  2694. {
  2695. if (mem_cgroup_disabled())
  2696. return 0;
  2697. VM_BUG_ON(page_mapped(page));
  2698. VM_BUG_ON(page->mapping && !PageAnon(page));
  2699. VM_BUG_ON(!mm);
  2700. return mem_cgroup_charge_common(page, mm, gfp_mask,
  2701. MEM_CGROUP_CHARGE_TYPE_ANON);
  2702. }
  2703. /*
  2704. * While swap-in, try_charge -> commit or cancel, the page is locked.
  2705. * And when try_charge() successfully returns, one refcnt to memcg without
  2706. * struct page_cgroup is acquired. This refcnt will be consumed by
  2707. * "commit()" or removed by "cancel()"
  2708. */
  2709. static int __mem_cgroup_try_charge_swapin(struct mm_struct *mm,
  2710. struct page *page,
  2711. gfp_t mask,
  2712. struct mem_cgroup **memcgp)
  2713. {
  2714. struct mem_cgroup *memcg;
  2715. struct page_cgroup *pc;
  2716. int ret;
  2717. pc = lookup_page_cgroup(page);
  2718. /*
  2719. * Every swap fault against a single page tries to charge the
  2720. * page, bail as early as possible. shmem_unuse() encounters
  2721. * already charged pages, too. The USED bit is protected by
  2722. * the page lock, which serializes swap cache removal, which
  2723. * in turn serializes uncharging.
  2724. */
  2725. if (PageCgroupUsed(pc))
  2726. return 0;
  2727. if (!do_swap_account)
  2728. goto charge_cur_mm;
  2729. memcg = try_get_mem_cgroup_from_page(page);
  2730. if (!memcg)
  2731. goto charge_cur_mm;
  2732. *memcgp = memcg;
  2733. ret = __mem_cgroup_try_charge(NULL, mask, 1, memcgp, true);
  2734. css_put(&memcg->css);
  2735. if (ret == -EINTR)
  2736. ret = 0;
  2737. return ret;
  2738. charge_cur_mm:
  2739. ret = __mem_cgroup_try_charge(mm, mask, 1, memcgp, true);
  2740. if (ret == -EINTR)
  2741. ret = 0;
  2742. return ret;
  2743. }
  2744. int mem_cgroup_try_charge_swapin(struct mm_struct *mm, struct page *page,
  2745. gfp_t gfp_mask, struct mem_cgroup **memcgp)
  2746. {
  2747. *memcgp = NULL;
  2748. if (mem_cgroup_disabled())
  2749. return 0;
  2750. /*
  2751. * A racing thread's fault, or swapoff, may have already
  2752. * updated the pte, and even removed page from swap cache: in
  2753. * those cases unuse_pte()'s pte_same() test will fail; but
  2754. * there's also a KSM case which does need to charge the page.
  2755. */
  2756. if (!PageSwapCache(page)) {
  2757. int ret;
  2758. ret = __mem_cgroup_try_charge(mm, gfp_mask, 1, memcgp, true);
  2759. if (ret == -EINTR)
  2760. ret = 0;
  2761. return ret;
  2762. }
  2763. return __mem_cgroup_try_charge_swapin(mm, page, gfp_mask, memcgp);
  2764. }
  2765. void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *memcg)
  2766. {
  2767. if (mem_cgroup_disabled())
  2768. return;
  2769. if (!memcg)
  2770. return;
  2771. __mem_cgroup_cancel_charge(memcg, 1);
  2772. }
  2773. static void
  2774. __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *memcg,
  2775. enum charge_type ctype)
  2776. {
  2777. if (mem_cgroup_disabled())
  2778. return;
  2779. if (!memcg)
  2780. return;
  2781. cgroup_exclude_rmdir(&memcg->css);
  2782. __mem_cgroup_commit_charge(memcg, page, 1, ctype, true);
  2783. /*
  2784. * Now swap is on-memory. This means this page may be
  2785. * counted both as mem and swap....double count.
  2786. * Fix it by uncharging from memsw. Basically, this SwapCache is stable
  2787. * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
  2788. * may call delete_from_swap_cache() before reach here.
  2789. */
  2790. if (do_swap_account && PageSwapCache(page)) {
  2791. swp_entry_t ent = {.val = page_private(page)};
  2792. mem_cgroup_uncharge_swap(ent);
  2793. }
  2794. /*
  2795. * At swapin, we may charge account against cgroup which has no tasks.
  2796. * So, rmdir()->pre_destroy() can be called while we do this charge.
  2797. * In that case, we need to call pre_destroy() again. check it here.
  2798. */
  2799. cgroup_release_and_wakeup_rmdir(&memcg->css);
  2800. }
  2801. void mem_cgroup_commit_charge_swapin(struct page *page,
  2802. struct mem_cgroup *memcg)
  2803. {
  2804. __mem_cgroup_commit_charge_swapin(page, memcg,
  2805. MEM_CGROUP_CHARGE_TYPE_ANON);
  2806. }
  2807. int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
  2808. gfp_t gfp_mask)
  2809. {
  2810. struct mem_cgroup *memcg = NULL;
  2811. enum charge_type type = MEM_CGROUP_CHARGE_TYPE_CACHE;
  2812. int ret;
  2813. if (mem_cgroup_disabled())
  2814. return 0;
  2815. if (PageCompound(page))
  2816. return 0;
  2817. if (!PageSwapCache(page))
  2818. ret = mem_cgroup_charge_common(page, mm, gfp_mask, type);
  2819. else { /* page is swapcache/shmem */
  2820. ret = __mem_cgroup_try_charge_swapin(mm, page,
  2821. gfp_mask, &memcg);
  2822. if (!ret)
  2823. __mem_cgroup_commit_charge_swapin(page, memcg, type);
  2824. }
  2825. return ret;
  2826. }
  2827. static void mem_cgroup_do_uncharge(struct mem_cgroup *memcg,
  2828. unsigned int nr_pages,
  2829. const enum charge_type ctype)
  2830. {
  2831. struct memcg_batch_info *batch = NULL;
  2832. bool uncharge_memsw = true;
  2833. /* If swapout, usage of swap doesn't decrease */
  2834. if (!do_swap_account || ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
  2835. uncharge_memsw = false;
  2836. batch = &current->memcg_batch;
  2837. /*
  2838. * In usual, we do css_get() when we remember memcg pointer.
  2839. * But in this case, we keep res->usage until end of a series of
  2840. * uncharges. Then, it's ok to ignore memcg's refcnt.
  2841. */
  2842. if (!batch->memcg)
  2843. batch->memcg = memcg;
  2844. /*
  2845. * do_batch > 0 when unmapping pages or inode invalidate/truncate.
  2846. * In those cases, all pages freed continuously can be expected to be in
  2847. * the same cgroup and we have chance to coalesce uncharges.
  2848. * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE)
  2849. * because we want to do uncharge as soon as possible.
  2850. */
  2851. if (!batch->do_batch || test_thread_flag(TIF_MEMDIE))
  2852. goto direct_uncharge;
  2853. if (nr_pages > 1)
  2854. goto direct_uncharge;
  2855. /*
  2856. * In typical case, batch->memcg == mem. This means we can
  2857. * merge a series of uncharges to an uncharge of res_counter.
  2858. * If not, we uncharge res_counter ony by one.
  2859. */
  2860. if (batch->memcg != memcg)
  2861. goto direct_uncharge;
  2862. /* remember freed charge and uncharge it later */
  2863. batch->nr_pages++;
  2864. if (uncharge_memsw)
  2865. batch->memsw_nr_pages++;
  2866. return;
  2867. direct_uncharge:
  2868. res_counter_uncharge(&memcg->res, nr_pages * PAGE_SIZE);
  2869. if (uncharge_memsw)
  2870. res_counter_uncharge(&memcg->memsw, nr_pages * PAGE_SIZE);
  2871. if (unlikely(batch->memcg != memcg))
  2872. memcg_oom_recover(memcg);
  2873. }
  2874. /*
  2875. * uncharge if !page_mapped(page)
  2876. */
  2877. static struct mem_cgroup *
  2878. __mem_cgroup_uncharge_common(struct page *page, enum charge_type ctype,
  2879. bool end_migration)
  2880. {
  2881. struct mem_cgroup *memcg = NULL;
  2882. unsigned int nr_pages = 1;
  2883. struct page_cgroup *pc;
  2884. bool anon;
  2885. if (mem_cgroup_disabled())
  2886. return NULL;
  2887. VM_BUG_ON(PageSwapCache(page));
  2888. if (PageTransHuge(page)) {
  2889. nr_pages <<= compound_order(page);
  2890. VM_BUG_ON(!PageTransHuge(page));
  2891. }
  2892. /*
  2893. * Check if our page_cgroup is valid
  2894. */
  2895. pc = lookup_page_cgroup(page);
  2896. if (unlikely(!PageCgroupUsed(pc)))
  2897. return NULL;
  2898. lock_page_cgroup(pc);
  2899. memcg = pc->mem_cgroup;
  2900. if (!PageCgroupUsed(pc))
  2901. goto unlock_out;
  2902. anon = PageAnon(page);
  2903. switch (ctype) {
  2904. case MEM_CGROUP_CHARGE_TYPE_ANON:
  2905. /*
  2906. * Generally PageAnon tells if it's the anon statistics to be
  2907. * updated; but sometimes e.g. mem_cgroup_uncharge_page() is
  2908. * used before page reached the stage of being marked PageAnon.
  2909. */
  2910. anon = true;
  2911. /* fallthrough */
  2912. case MEM_CGROUP_CHARGE_TYPE_DROP:
  2913. /* See mem_cgroup_prepare_migration() */
  2914. if (page_mapped(page))
  2915. goto unlock_out;
  2916. /*
  2917. * Pages under migration may not be uncharged. But
  2918. * end_migration() /must/ be the one uncharging the
  2919. * unused post-migration page and so it has to call
  2920. * here with the migration bit still set. See the
  2921. * res_counter handling below.
  2922. */
  2923. if (!end_migration && PageCgroupMigration(pc))
  2924. goto unlock_out;
  2925. break;
  2926. case MEM_CGROUP_CHARGE_TYPE_SWAPOUT:
  2927. if (!PageAnon(page)) { /* Shared memory */
  2928. if (page->mapping && !page_is_file_cache(page))
  2929. goto unlock_out;
  2930. } else if (page_mapped(page)) /* Anon */
  2931. goto unlock_out;
  2932. break;
  2933. default:
  2934. break;
  2935. }
  2936. mem_cgroup_charge_statistics(memcg, anon, -nr_pages);
  2937. ClearPageCgroupUsed(pc);
  2938. /*
  2939. * pc->mem_cgroup is not cleared here. It will be accessed when it's
  2940. * freed from LRU. This is safe because uncharged page is expected not
  2941. * to be reused (freed soon). Exception is SwapCache, it's handled by
  2942. * special functions.
  2943. */
  2944. unlock_page_cgroup(pc);
  2945. /*
  2946. * even after unlock, we have memcg->res.usage here and this memcg
  2947. * will never be freed.
  2948. */
  2949. memcg_check_events(memcg, page);
  2950. if (do_swap_account && ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT) {
  2951. mem_cgroup_swap_statistics(memcg, true);
  2952. mem_cgroup_get(memcg);
  2953. }
  2954. /*
  2955. * Migration does not charge the res_counter for the
  2956. * replacement page, so leave it alone when phasing out the
  2957. * page that is unused after the migration.
  2958. */
  2959. if (!end_migration && !mem_cgroup_is_root(memcg))
  2960. mem_cgroup_do_uncharge(memcg, nr_pages, ctype);
  2961. return memcg;
  2962. unlock_out:
  2963. unlock_page_cgroup(pc);
  2964. return NULL;
  2965. }
  2966. void mem_cgroup_uncharge_page(struct page *page)
  2967. {
  2968. /* early check. */
  2969. if (page_mapped(page))
  2970. return;
  2971. VM_BUG_ON(page->mapping && !PageAnon(page));
  2972. if (PageSwapCache(page))
  2973. return;
  2974. __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_ANON, false);
  2975. }
  2976. void mem_cgroup_uncharge_cache_page(struct page *page)
  2977. {
  2978. VM_BUG_ON(page_mapped(page));
  2979. VM_BUG_ON(page->mapping);
  2980. __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_CACHE, false);
  2981. }
  2982. /*
  2983. * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate.
  2984. * In that cases, pages are freed continuously and we can expect pages
  2985. * are in the same memcg. All these calls itself limits the number of
  2986. * pages freed at once, then uncharge_start/end() is called properly.
  2987. * This may be called prural(2) times in a context,
  2988. */
  2989. void mem_cgroup_uncharge_start(void)
  2990. {
  2991. current->memcg_batch.do_batch++;
  2992. /* We can do nest. */
  2993. if (current->memcg_batch.do_batch == 1) {
  2994. current->memcg_batch.memcg = NULL;
  2995. current->memcg_batch.nr_pages = 0;
  2996. current->memcg_batch.memsw_nr_pages = 0;
  2997. }
  2998. }
  2999. void mem_cgroup_uncharge_end(void)
  3000. {
  3001. struct memcg_batch_info *batch = &current->memcg_batch;
  3002. if (!batch->do_batch)
  3003. return;
  3004. batch->do_batch--;
  3005. if (batch->do_batch) /* If stacked, do nothing. */
  3006. return;
  3007. if (!batch->memcg)
  3008. return;
  3009. /*
  3010. * This "batch->memcg" is valid without any css_get/put etc...
  3011. * bacause we hide charges behind us.
  3012. */
  3013. if (batch->nr_pages)
  3014. res_counter_uncharge(&batch->memcg->res,
  3015. batch->nr_pages * PAGE_SIZE);
  3016. if (batch->memsw_nr_pages)
  3017. res_counter_uncharge(&batch->memcg->memsw,
  3018. batch->memsw_nr_pages * PAGE_SIZE);
  3019. memcg_oom_recover(batch->memcg);
  3020. /* forget this pointer (for sanity check) */
  3021. batch->memcg = NULL;
  3022. }
  3023. #ifdef CONFIG_SWAP
  3024. /*
  3025. * called after __delete_from_swap_cache() and drop "page" account.
  3026. * memcg information is recorded to swap_cgroup of "ent"
  3027. */
  3028. void
  3029. mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout)
  3030. {
  3031. struct mem_cgroup *memcg;
  3032. int ctype = MEM_CGROUP_CHARGE_TYPE_SWAPOUT;
  3033. if (!swapout) /* this was a swap cache but the swap is unused ! */
  3034. ctype = MEM_CGROUP_CHARGE_TYPE_DROP;
  3035. memcg = __mem_cgroup_uncharge_common(page, ctype, false);
  3036. /*
  3037. * record memcg information, if swapout && memcg != NULL,
  3038. * mem_cgroup_get() was called in uncharge().
  3039. */
  3040. if (do_swap_account && swapout && memcg)
  3041. swap_cgroup_record(ent, css_id(&memcg->css));
  3042. }
  3043. #endif
  3044. #ifdef CONFIG_MEMCG_SWAP
  3045. /*
  3046. * called from swap_entry_free(). remove record in swap_cgroup and
  3047. * uncharge "memsw" account.
  3048. */
  3049. void mem_cgroup_uncharge_swap(swp_entry_t ent)
  3050. {
  3051. struct mem_cgroup *memcg;
  3052. unsigned short id;
  3053. if (!do_swap_account)
  3054. return;
  3055. id = swap_cgroup_record(ent, 0);
  3056. rcu_read_lock();
  3057. memcg = mem_cgroup_lookup(id);
  3058. if (memcg) {
  3059. /*
  3060. * We uncharge this because swap is freed.
  3061. * This memcg can be obsolete one. We avoid calling css_tryget
  3062. */
  3063. if (!mem_cgroup_is_root(memcg))
  3064. res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
  3065. mem_cgroup_swap_statistics(memcg, false);
  3066. mem_cgroup_put(memcg);
  3067. }
  3068. rcu_read_unlock();
  3069. }
  3070. /**
  3071. * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
  3072. * @entry: swap entry to be moved
  3073. * @from: mem_cgroup which the entry is moved from
  3074. * @to: mem_cgroup which the entry is moved to
  3075. *
  3076. * It succeeds only when the swap_cgroup's record for this entry is the same
  3077. * as the mem_cgroup's id of @from.
  3078. *
  3079. * Returns 0 on success, -EINVAL on failure.
  3080. *
  3081. * The caller must have charged to @to, IOW, called res_counter_charge() about
  3082. * both res and memsw, and called css_get().
  3083. */
  3084. static int mem_cgroup_move_swap_account(swp_entry_t entry,
  3085. struct mem_cgroup *from, struct mem_cgroup *to)
  3086. {
  3087. unsigned short old_id, new_id;
  3088. old_id = css_id(&from->css);
  3089. new_id = css_id(&to->css);
  3090. if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
  3091. mem_cgroup_swap_statistics(from, false);
  3092. mem_cgroup_swap_statistics(to, true);
  3093. /*
  3094. * This function is only called from task migration context now.
  3095. * It postpones res_counter and refcount handling till the end
  3096. * of task migration(mem_cgroup_clear_mc()) for performance
  3097. * improvement. But we cannot postpone mem_cgroup_get(to)
  3098. * because if the process that has been moved to @to does
  3099. * swap-in, the refcount of @to might be decreased to 0.
  3100. */
  3101. mem_cgroup_get(to);
  3102. return 0;
  3103. }
  3104. return -EINVAL;
  3105. }
  3106. #else
  3107. static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
  3108. struct mem_cgroup *from, struct mem_cgroup *to)
  3109. {
  3110. return -EINVAL;
  3111. }
  3112. #endif
  3113. /*
  3114. * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
  3115. * page belongs to.
  3116. */
  3117. void mem_cgroup_prepare_migration(struct page *page, struct page *newpage,
  3118. struct mem_cgroup **memcgp)
  3119. {
  3120. struct mem_cgroup *memcg = NULL;
  3121. struct page_cgroup *pc;
  3122. enum charge_type ctype;
  3123. *memcgp = NULL;
  3124. VM_BUG_ON(PageTransHuge(page));
  3125. if (mem_cgroup_disabled())
  3126. return;
  3127. pc = lookup_page_cgroup(page);
  3128. lock_page_cgroup(pc);
  3129. if (PageCgroupUsed(pc)) {
  3130. memcg = pc->mem_cgroup;
  3131. css_get(&memcg->css);
  3132. /*
  3133. * At migrating an anonymous page, its mapcount goes down
  3134. * to 0 and uncharge() will be called. But, even if it's fully
  3135. * unmapped, migration may fail and this page has to be
  3136. * charged again. We set MIGRATION flag here and delay uncharge
  3137. * until end_migration() is called
  3138. *
  3139. * Corner Case Thinking
  3140. * A)
  3141. * When the old page was mapped as Anon and it's unmap-and-freed
  3142. * while migration was ongoing.
  3143. * If unmap finds the old page, uncharge() of it will be delayed
  3144. * until end_migration(). If unmap finds a new page, it's
  3145. * uncharged when it make mapcount to be 1->0. If unmap code
  3146. * finds swap_migration_entry, the new page will not be mapped
  3147. * and end_migration() will find it(mapcount==0).
  3148. *
  3149. * B)
  3150. * When the old page was mapped but migraion fails, the kernel
  3151. * remaps it. A charge for it is kept by MIGRATION flag even
  3152. * if mapcount goes down to 0. We can do remap successfully
  3153. * without charging it again.
  3154. *
  3155. * C)
  3156. * The "old" page is under lock_page() until the end of
  3157. * migration, so, the old page itself will not be swapped-out.
  3158. * If the new page is swapped out before end_migraton, our
  3159. * hook to usual swap-out path will catch the event.
  3160. */
  3161. if (PageAnon(page))
  3162. SetPageCgroupMigration(pc);
  3163. }
  3164. unlock_page_cgroup(pc);
  3165. /*
  3166. * If the page is not charged at this point,
  3167. * we return here.
  3168. */
  3169. if (!memcg)
  3170. return;
  3171. *memcgp = memcg;
  3172. /*
  3173. * We charge new page before it's used/mapped. So, even if unlock_page()
  3174. * is called before end_migration, we can catch all events on this new
  3175. * page. In the case new page is migrated but not remapped, new page's
  3176. * mapcount will be finally 0 and we call uncharge in end_migration().
  3177. */
  3178. if (PageAnon(page))
  3179. ctype = MEM_CGROUP_CHARGE_TYPE_ANON;
  3180. else
  3181. ctype = MEM_CGROUP_CHARGE_TYPE_CACHE;
  3182. /*
  3183. * The page is committed to the memcg, but it's not actually
  3184. * charged to the res_counter since we plan on replacing the
  3185. * old one and only one page is going to be left afterwards.
  3186. */
  3187. __mem_cgroup_commit_charge(memcg, newpage, 1, ctype, false);
  3188. }
  3189. /* remove redundant charge if migration failed*/
  3190. void mem_cgroup_end_migration(struct mem_cgroup *memcg,
  3191. struct page *oldpage, struct page *newpage, bool migration_ok)
  3192. {
  3193. struct page *used, *unused;
  3194. struct page_cgroup *pc;
  3195. bool anon;
  3196. if (!memcg)
  3197. return;
  3198. /* blocks rmdir() */
  3199. cgroup_exclude_rmdir(&memcg->css);
  3200. if (!migration_ok) {
  3201. used = oldpage;
  3202. unused = newpage;
  3203. } else {
  3204. used = newpage;
  3205. unused = oldpage;
  3206. }
  3207. anon = PageAnon(used);
  3208. __mem_cgroup_uncharge_common(unused,
  3209. anon ? MEM_CGROUP_CHARGE_TYPE_ANON
  3210. : MEM_CGROUP_CHARGE_TYPE_CACHE,
  3211. true);
  3212. css_put(&memcg->css);
  3213. /*
  3214. * We disallowed uncharge of pages under migration because mapcount
  3215. * of the page goes down to zero, temporarly.
  3216. * Clear the flag and check the page should be charged.
  3217. */
  3218. pc = lookup_page_cgroup(oldpage);
  3219. lock_page_cgroup(pc);
  3220. ClearPageCgroupMigration(pc);
  3221. unlock_page_cgroup(pc);
  3222. /*
  3223. * If a page is a file cache, radix-tree replacement is very atomic
  3224. * and we can skip this check. When it was an Anon page, its mapcount
  3225. * goes down to 0. But because we added MIGRATION flage, it's not
  3226. * uncharged yet. There are several case but page->mapcount check
  3227. * and USED bit check in mem_cgroup_uncharge_page() will do enough
  3228. * check. (see prepare_charge() also)
  3229. */
  3230. if (anon)
  3231. mem_cgroup_uncharge_page(used);
  3232. /*
  3233. * At migration, we may charge account against cgroup which has no
  3234. * tasks.
  3235. * So, rmdir()->pre_destroy() can be called while we do this charge.
  3236. * In that case, we need to call pre_destroy() again. check it here.
  3237. */
  3238. cgroup_release_and_wakeup_rmdir(&memcg->css);
  3239. }
  3240. /*
  3241. * At replace page cache, newpage is not under any memcg but it's on
  3242. * LRU. So, this function doesn't touch res_counter but handles LRU
  3243. * in correct way. Both pages are locked so we cannot race with uncharge.
  3244. */
  3245. void mem_cgroup_replace_page_cache(struct page *oldpage,
  3246. struct page *newpage)
  3247. {
  3248. struct mem_cgroup *memcg = NULL;
  3249. struct page_cgroup *pc;
  3250. enum charge_type type = MEM_CGROUP_CHARGE_TYPE_CACHE;
  3251. if (mem_cgroup_disabled())
  3252. return;
  3253. pc = lookup_page_cgroup(oldpage);
  3254. /* fix accounting on old pages */
  3255. lock_page_cgroup(pc);
  3256. if (PageCgroupUsed(pc)) {
  3257. memcg = pc->mem_cgroup;
  3258. mem_cgroup_charge_statistics(memcg, false, -1);
  3259. ClearPageCgroupUsed(pc);
  3260. }
  3261. unlock_page_cgroup(pc);
  3262. /*
  3263. * When called from shmem_replace_page(), in some cases the
  3264. * oldpage has already been charged, and in some cases not.
  3265. */
  3266. if (!memcg)
  3267. return;
  3268. /*
  3269. * Even if newpage->mapping was NULL before starting replacement,
  3270. * the newpage may be on LRU(or pagevec for LRU) already. We lock
  3271. * LRU while we overwrite pc->mem_cgroup.
  3272. */
  3273. __mem_cgroup_commit_charge(memcg, newpage, 1, type, true);
  3274. }
  3275. #ifdef CONFIG_DEBUG_VM
  3276. static struct page_cgroup *lookup_page_cgroup_used(struct page *page)
  3277. {
  3278. struct page_cgroup *pc;
  3279. pc = lookup_page_cgroup(page);
  3280. /*
  3281. * Can be NULL while feeding pages into the page allocator for
  3282. * the first time, i.e. during boot or memory hotplug;
  3283. * or when mem_cgroup_disabled().
  3284. */
  3285. if (likely(pc) && PageCgroupUsed(pc))
  3286. return pc;
  3287. return NULL;
  3288. }
  3289. bool mem_cgroup_bad_page_check(struct page *page)
  3290. {
  3291. if (mem_cgroup_disabled())
  3292. return false;
  3293. return lookup_page_cgroup_used(page) != NULL;
  3294. }
  3295. void mem_cgroup_print_bad_page(struct page *page)
  3296. {
  3297. struct page_cgroup *pc;
  3298. pc = lookup_page_cgroup_used(page);
  3299. if (pc) {
  3300. printk(KERN_ALERT "pc:%p pc->flags:%lx pc->mem_cgroup:%p\n",
  3301. pc, pc->flags, pc->mem_cgroup);
  3302. }
  3303. }
  3304. #endif
  3305. static DEFINE_MUTEX(set_limit_mutex);
  3306. static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
  3307. unsigned long long val)
  3308. {
  3309. int retry_count;
  3310. u64 memswlimit, memlimit;
  3311. int ret = 0;
  3312. int children = mem_cgroup_count_children(memcg);
  3313. u64 curusage, oldusage;
  3314. int enlarge;
  3315. /*
  3316. * For keeping hierarchical_reclaim simple, how long we should retry
  3317. * is depends on callers. We set our retry-count to be function
  3318. * of # of children which we should visit in this loop.
  3319. */
  3320. retry_count = MEM_CGROUP_RECLAIM_RETRIES * children;
  3321. oldusage = res_counter_read_u64(&memcg->res, RES_USAGE);
  3322. enlarge = 0;
  3323. while (retry_count) {
  3324. if (signal_pending(current)) {
  3325. ret = -EINTR;
  3326. break;
  3327. }
  3328. /*
  3329. * Rather than hide all in some function, I do this in
  3330. * open coded manner. You see what this really does.
  3331. * We have to guarantee memcg->res.limit <= memcg->memsw.limit.
  3332. */
  3333. mutex_lock(&set_limit_mutex);
  3334. memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
  3335. if (memswlimit < val) {
  3336. ret = -EINVAL;
  3337. mutex_unlock(&set_limit_mutex);
  3338. break;
  3339. }
  3340. memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
  3341. if (memlimit < val)
  3342. enlarge = 1;
  3343. ret = res_counter_set_limit(&memcg->res, val);
  3344. if (!ret) {
  3345. if (memswlimit == val)
  3346. memcg->memsw_is_minimum = true;
  3347. else
  3348. memcg->memsw_is_minimum = false;
  3349. }
  3350. mutex_unlock(&set_limit_mutex);
  3351. if (!ret)
  3352. break;
  3353. mem_cgroup_reclaim(memcg, GFP_KERNEL,
  3354. MEM_CGROUP_RECLAIM_SHRINK);
  3355. curusage = res_counter_read_u64(&memcg->res, RES_USAGE);
  3356. /* Usage is reduced ? */
  3357. if (curusage >= oldusage)
  3358. retry_count--;
  3359. else
  3360. oldusage = curusage;
  3361. }
  3362. if (!ret && enlarge)
  3363. memcg_oom_recover(memcg);
  3364. return ret;
  3365. }
  3366. static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
  3367. unsigned long long val)
  3368. {
  3369. int retry_count;
  3370. u64 memlimit, memswlimit, oldusage, curusage;
  3371. int children = mem_cgroup_count_children(memcg);
  3372. int ret = -EBUSY;
  3373. int enlarge = 0;
  3374. /* see mem_cgroup_resize_res_limit */
  3375. retry_count = children * MEM_CGROUP_RECLAIM_RETRIES;
  3376. oldusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
  3377. while (retry_count) {
  3378. if (signal_pending(current)) {
  3379. ret = -EINTR;
  3380. break;
  3381. }
  3382. /*
  3383. * Rather than hide all in some function, I do this in
  3384. * open coded manner. You see what this really does.
  3385. * We have to guarantee memcg->res.limit <= memcg->memsw.limit.
  3386. */
  3387. mutex_lock(&set_limit_mutex);
  3388. memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
  3389. if (memlimit > val) {
  3390. ret = -EINVAL;
  3391. mutex_unlock(&set_limit_mutex);
  3392. break;
  3393. }
  3394. memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
  3395. if (memswlimit < val)
  3396. enlarge = 1;
  3397. ret = res_counter_set_limit(&memcg->memsw, val);
  3398. if (!ret) {
  3399. if (memlimit == val)
  3400. memcg->memsw_is_minimum = true;
  3401. else
  3402. memcg->memsw_is_minimum = false;
  3403. }
  3404. mutex_unlock(&set_limit_mutex);
  3405. if (!ret)
  3406. break;
  3407. mem_cgroup_reclaim(memcg, GFP_KERNEL,
  3408. MEM_CGROUP_RECLAIM_NOSWAP |
  3409. MEM_CGROUP_RECLAIM_SHRINK);
  3410. curusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
  3411. /* Usage is reduced ? */
  3412. if (curusage >= oldusage)
  3413. retry_count--;
  3414. else
  3415. oldusage = curusage;
  3416. }
  3417. if (!ret && enlarge)
  3418. memcg_oom_recover(memcg);
  3419. return ret;
  3420. }
  3421. unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
  3422. gfp_t gfp_mask,
  3423. unsigned long *total_scanned)
  3424. {
  3425. unsigned long nr_reclaimed = 0;
  3426. struct mem_cgroup_per_zone *mz, *next_mz = NULL;
  3427. unsigned long reclaimed;
  3428. int loop = 0;
  3429. struct mem_cgroup_tree_per_zone *mctz;
  3430. unsigned long long excess;
  3431. unsigned long nr_scanned;
  3432. if (order > 0)
  3433. return 0;
  3434. mctz = soft_limit_tree_node_zone(zone_to_nid(zone), zone_idx(zone));
  3435. /*
  3436. * This loop can run a while, specially if mem_cgroup's continuously
  3437. * keep exceeding their soft limit and putting the system under
  3438. * pressure
  3439. */
  3440. do {
  3441. if (next_mz)
  3442. mz = next_mz;
  3443. else
  3444. mz = mem_cgroup_largest_soft_limit_node(mctz);
  3445. if (!mz)
  3446. break;
  3447. nr_scanned = 0;
  3448. reclaimed = mem_cgroup_soft_reclaim(mz->memcg, zone,
  3449. gfp_mask, &nr_scanned);
  3450. nr_reclaimed += reclaimed;
  3451. *total_scanned += nr_scanned;
  3452. spin_lock(&mctz->lock);
  3453. /*
  3454. * If we failed to reclaim anything from this memory cgroup
  3455. * it is time to move on to the next cgroup
  3456. */
  3457. next_mz = NULL;
  3458. if (!reclaimed) {
  3459. do {
  3460. /*
  3461. * Loop until we find yet another one.
  3462. *
  3463. * By the time we get the soft_limit lock
  3464. * again, someone might have aded the
  3465. * group back on the RB tree. Iterate to
  3466. * make sure we get a different mem.
  3467. * mem_cgroup_largest_soft_limit_node returns
  3468. * NULL if no other cgroup is present on
  3469. * the tree
  3470. */
  3471. next_mz =
  3472. __mem_cgroup_largest_soft_limit_node(mctz);
  3473. if (next_mz == mz)
  3474. css_put(&next_mz->memcg->css);
  3475. else /* next_mz == NULL or other memcg */
  3476. break;
  3477. } while (1);
  3478. }
  3479. __mem_cgroup_remove_exceeded(mz->memcg, mz, mctz);
  3480. excess = res_counter_soft_limit_excess(&mz->memcg->res);
  3481. /*
  3482. * One school of thought says that we should not add
  3483. * back the node to the tree if reclaim returns 0.
  3484. * But our reclaim could return 0, simply because due
  3485. * to priority we are exposing a smaller subset of
  3486. * memory to reclaim from. Consider this as a longer
  3487. * term TODO.
  3488. */
  3489. /* If excess == 0, no tree ops */
  3490. __mem_cgroup_insert_exceeded(mz->memcg, mz, mctz, excess);
  3491. spin_unlock(&mctz->lock);
  3492. css_put(&mz->memcg->css);
  3493. loop++;
  3494. /*
  3495. * Could not reclaim anything and there are no more
  3496. * mem cgroups to try or we seem to be looping without
  3497. * reclaiming anything.
  3498. */
  3499. if (!nr_reclaimed &&
  3500. (next_mz == NULL ||
  3501. loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
  3502. break;
  3503. } while (!nr_reclaimed);
  3504. if (next_mz)
  3505. css_put(&next_mz->memcg->css);
  3506. return nr_reclaimed;
  3507. }
  3508. /**
  3509. * mem_cgroup_force_empty_list - clears LRU of a group
  3510. * @memcg: group to clear
  3511. * @node: NUMA node
  3512. * @zid: zone id
  3513. * @lru: lru to to clear
  3514. *
  3515. * Traverse a specified page_cgroup list and try to drop them all. This doesn't
  3516. * reclaim the pages page themselves - pages are moved to the parent (or root)
  3517. * group.
  3518. */
  3519. static void mem_cgroup_force_empty_list(struct mem_cgroup *memcg,
  3520. int node, int zid, enum lru_list lru)
  3521. {
  3522. struct mem_cgroup_per_zone *mz;
  3523. unsigned long flags;
  3524. struct list_head *list;
  3525. struct page *busy;
  3526. struct zone *zone;
  3527. zone = &NODE_DATA(node)->node_zones[zid];
  3528. mz = mem_cgroup_zoneinfo(memcg, node, zid);
  3529. list = &mz->lruvec.lists[lru];
  3530. busy = NULL;
  3531. do {
  3532. struct page_cgroup *pc;
  3533. struct page *page;
  3534. spin_lock_irqsave(&zone->lru_lock, flags);
  3535. if (list_empty(list)) {
  3536. spin_unlock_irqrestore(&zone->lru_lock, flags);
  3537. break;
  3538. }
  3539. page = list_entry(list->prev, struct page, lru);
  3540. if (busy == page) {
  3541. list_move(&page->lru, list);
  3542. busy = NULL;
  3543. spin_unlock_irqrestore(&zone->lru_lock, flags);
  3544. continue;
  3545. }
  3546. spin_unlock_irqrestore(&zone->lru_lock, flags);
  3547. pc = lookup_page_cgroup(page);
  3548. if (mem_cgroup_move_parent(page, pc, memcg)) {
  3549. /* found lock contention or "pc" is obsolete. */
  3550. busy = page;
  3551. cond_resched();
  3552. } else
  3553. busy = NULL;
  3554. } while (!list_empty(list));
  3555. }
  3556. /*
  3557. * make mem_cgroup's charge to be 0 if there is no task by moving
  3558. * all the charges and pages to the parent.
  3559. * This enables deleting this mem_cgroup.
  3560. *
  3561. * Caller is responsible for holding css reference on the memcg.
  3562. */
  3563. static int mem_cgroup_reparent_charges(struct mem_cgroup *memcg)
  3564. {
  3565. struct cgroup *cgrp = memcg->css.cgroup;
  3566. int node, zid;
  3567. do {
  3568. if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children))
  3569. return -EBUSY;
  3570. /* This is for making all *used* pages to be on LRU. */
  3571. lru_add_drain_all();
  3572. drain_all_stock_sync(memcg);
  3573. mem_cgroup_start_move(memcg);
  3574. for_each_node_state(node, N_HIGH_MEMORY) {
  3575. for (zid = 0; zid < MAX_NR_ZONES; zid++) {
  3576. enum lru_list lru;
  3577. for_each_lru(lru) {
  3578. mem_cgroup_force_empty_list(memcg,
  3579. node, zid, lru);
  3580. }
  3581. }
  3582. }
  3583. mem_cgroup_end_move(memcg);
  3584. memcg_oom_recover(memcg);
  3585. cond_resched();
  3586. /*
  3587. * This is a safety check because mem_cgroup_force_empty_list
  3588. * could have raced with mem_cgroup_replace_page_cache callers
  3589. * so the lru seemed empty but the page could have been added
  3590. * right after the check. RES_USAGE should be safe as we always
  3591. * charge before adding to the LRU.
  3592. */
  3593. } while (res_counter_read_u64(&memcg->res, RES_USAGE) > 0);
  3594. return 0;
  3595. }
  3596. /*
  3597. * Reclaims as many pages from the given memcg as possible and moves
  3598. * the rest to the parent.
  3599. *
  3600. * Caller is responsible for holding css reference for memcg.
  3601. */
  3602. static int mem_cgroup_force_empty(struct mem_cgroup *memcg)
  3603. {
  3604. int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
  3605. struct cgroup *cgrp = memcg->css.cgroup;
  3606. /* returns EBUSY if there is a task or if we come here twice. */
  3607. if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children))
  3608. return -EBUSY;
  3609. /* we call try-to-free pages for make this cgroup empty */
  3610. lru_add_drain_all();
  3611. /* try to free all pages in this cgroup */
  3612. while (nr_retries && res_counter_read_u64(&memcg->res, RES_USAGE) > 0) {
  3613. int progress;
  3614. if (signal_pending(current))
  3615. return -EINTR;
  3616. progress = try_to_free_mem_cgroup_pages(memcg, GFP_KERNEL,
  3617. false);
  3618. if (!progress) {
  3619. nr_retries--;
  3620. /* maybe some writeback is necessary */
  3621. congestion_wait(BLK_RW_ASYNC, HZ/10);
  3622. }
  3623. }
  3624. lru_add_drain();
  3625. return mem_cgroup_reparent_charges(memcg);
  3626. }
  3627. static int mem_cgroup_force_empty_write(struct cgroup *cont, unsigned int event)
  3628. {
  3629. struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
  3630. int ret;
  3631. if (mem_cgroup_is_root(memcg))
  3632. return -EINVAL;
  3633. css_get(&memcg->css);
  3634. ret = mem_cgroup_force_empty(memcg);
  3635. css_put(&memcg->css);
  3636. return ret;
  3637. }
  3638. static u64 mem_cgroup_hierarchy_read(struct cgroup *cont, struct cftype *cft)
  3639. {
  3640. return mem_cgroup_from_cont(cont)->use_hierarchy;
  3641. }
  3642. static int mem_cgroup_hierarchy_write(struct cgroup *cont, struct cftype *cft,
  3643. u64 val)
  3644. {
  3645. int retval = 0;
  3646. struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
  3647. struct cgroup *parent = cont->parent;
  3648. struct mem_cgroup *parent_memcg = NULL;
  3649. if (parent)
  3650. parent_memcg = mem_cgroup_from_cont(parent);
  3651. cgroup_lock();
  3652. if (memcg->use_hierarchy == val)
  3653. goto out;
  3654. /*
  3655. * If parent's use_hierarchy is set, we can't make any modifications
  3656. * in the child subtrees. If it is unset, then the change can
  3657. * occur, provided the current cgroup has no children.
  3658. *
  3659. * For the root cgroup, parent_mem is NULL, we allow value to be
  3660. * set if there are no children.
  3661. */
  3662. if ((!parent_memcg || !parent_memcg->use_hierarchy) &&
  3663. (val == 1 || val == 0)) {
  3664. if (list_empty(&cont->children))
  3665. memcg->use_hierarchy = val;
  3666. else
  3667. retval = -EBUSY;
  3668. } else
  3669. retval = -EINVAL;
  3670. out:
  3671. cgroup_unlock();
  3672. return retval;
  3673. }
  3674. static unsigned long mem_cgroup_recursive_stat(struct mem_cgroup *memcg,
  3675. enum mem_cgroup_stat_index idx)
  3676. {
  3677. struct mem_cgroup *iter;
  3678. long val = 0;
  3679. /* Per-cpu values can be negative, use a signed accumulator */
  3680. for_each_mem_cgroup_tree(iter, memcg)
  3681. val += mem_cgroup_read_stat(iter, idx);
  3682. if (val < 0) /* race ? */
  3683. val = 0;
  3684. return val;
  3685. }
  3686. static inline u64 mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
  3687. {
  3688. u64 val;
  3689. if (!mem_cgroup_is_root(memcg)) {
  3690. if (!swap)
  3691. return res_counter_read_u64(&memcg->res, RES_USAGE);
  3692. else
  3693. return res_counter_read_u64(&memcg->memsw, RES_USAGE);
  3694. }
  3695. val = mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_CACHE);
  3696. val += mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_RSS);
  3697. if (swap)
  3698. val += mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_SWAP);
  3699. return val << PAGE_SHIFT;
  3700. }
  3701. static ssize_t mem_cgroup_read(struct cgroup *cont, struct cftype *cft,
  3702. struct file *file, char __user *buf,
  3703. size_t nbytes, loff_t *ppos)
  3704. {
  3705. struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
  3706. char str[64];
  3707. u64 val;
  3708. int name, len;
  3709. enum res_type type;
  3710. type = MEMFILE_TYPE(cft->private);
  3711. name = MEMFILE_ATTR(cft->private);
  3712. if (!do_swap_account && type == _MEMSWAP)
  3713. return -EOPNOTSUPP;
  3714. switch (type) {
  3715. case _MEM:
  3716. if (name == RES_USAGE)
  3717. val = mem_cgroup_usage(memcg, false);
  3718. else
  3719. val = res_counter_read_u64(&memcg->res, name);
  3720. break;
  3721. case _MEMSWAP:
  3722. if (name == RES_USAGE)
  3723. val = mem_cgroup_usage(memcg, true);
  3724. else
  3725. val = res_counter_read_u64(&memcg->memsw, name);
  3726. break;
  3727. case _KMEM:
  3728. val = res_counter_read_u64(&memcg->kmem, name);
  3729. break;
  3730. default:
  3731. BUG();
  3732. }
  3733. len = scnprintf(str, sizeof(str), "%llu\n", (unsigned long long)val);
  3734. return simple_read_from_buffer(buf, nbytes, ppos, str, len);
  3735. }
  3736. static int memcg_update_kmem_limit(struct cgroup *cont, u64 val)
  3737. {
  3738. int ret = -EINVAL;
  3739. #ifdef CONFIG_MEMCG_KMEM
  3740. bool must_inc_static_branch = false;
  3741. struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
  3742. /*
  3743. * For simplicity, we won't allow this to be disabled. It also can't
  3744. * be changed if the cgroup has children already, or if tasks had
  3745. * already joined.
  3746. *
  3747. * If tasks join before we set the limit, a person looking at
  3748. * kmem.usage_in_bytes will have no way to determine when it took
  3749. * place, which makes the value quite meaningless.
  3750. *
  3751. * After it first became limited, changes in the value of the limit are
  3752. * of course permitted.
  3753. *
  3754. * Taking the cgroup_lock is really offensive, but it is so far the only
  3755. * way to guarantee that no children will appear. There are plenty of
  3756. * other offenders, and they should all go away. Fine grained locking
  3757. * is probably the way to go here. When we are fully hierarchical, we
  3758. * can also get rid of the use_hierarchy check.
  3759. */
  3760. cgroup_lock();
  3761. mutex_lock(&set_limit_mutex);
  3762. if (!memcg->kmem_account_flags && val != RESOURCE_MAX) {
  3763. if (cgroup_task_count(cont) || (memcg->use_hierarchy &&
  3764. !list_empty(&cont->children))) {
  3765. ret = -EBUSY;
  3766. goto out;
  3767. }
  3768. ret = res_counter_set_limit(&memcg->kmem, val);
  3769. VM_BUG_ON(ret);
  3770. /*
  3771. * After this point, kmem_accounted (that we test atomically in
  3772. * the beginning of this conditional), is no longer 0. This
  3773. * guarantees only one process will set the following boolean
  3774. * to true. We don't need test_and_set because we're protected
  3775. * by the set_limit_mutex anyway.
  3776. */
  3777. memcg_kmem_set_activated(memcg);
  3778. must_inc_static_branch = true;
  3779. /*
  3780. * kmem charges can outlive the cgroup. In the case of slab
  3781. * pages, for instance, a page contain objects from various
  3782. * processes, so it is unfeasible to migrate them away. We
  3783. * need to reference count the memcg because of that.
  3784. */
  3785. mem_cgroup_get(memcg);
  3786. } else
  3787. ret = res_counter_set_limit(&memcg->kmem, val);
  3788. out:
  3789. mutex_unlock(&set_limit_mutex);
  3790. cgroup_unlock();
  3791. /*
  3792. * We are by now familiar with the fact that we can't inc the static
  3793. * branch inside cgroup_lock. See disarm functions for details. A
  3794. * worker here is overkill, but also wrong: After the limit is set, we
  3795. * must start accounting right away. Since this operation can't fail,
  3796. * we can safely defer it to here - no rollback will be needed.
  3797. *
  3798. * The boolean used to control this is also safe, because
  3799. * KMEM_ACCOUNTED_ACTIVATED guarantees that only one process will be
  3800. * able to set it to true;
  3801. */
  3802. if (must_inc_static_branch) {
  3803. static_key_slow_inc(&memcg_kmem_enabled_key);
  3804. /*
  3805. * setting the active bit after the inc will guarantee no one
  3806. * starts accounting before all call sites are patched
  3807. */
  3808. memcg_kmem_set_active(memcg);
  3809. }
  3810. #endif
  3811. return ret;
  3812. }
  3813. static void memcg_propagate_kmem(struct mem_cgroup *memcg)
  3814. {
  3815. struct mem_cgroup *parent = parent_mem_cgroup(memcg);
  3816. if (!parent)
  3817. return;
  3818. memcg->kmem_account_flags = parent->kmem_account_flags;
  3819. #ifdef CONFIG_MEMCG_KMEM
  3820. /*
  3821. * When that happen, we need to disable the static branch only on those
  3822. * memcgs that enabled it. To achieve this, we would be forced to
  3823. * complicate the code by keeping track of which memcgs were the ones
  3824. * that actually enabled limits, and which ones got it from its
  3825. * parents.
  3826. *
  3827. * It is a lot simpler just to do static_key_slow_inc() on every child
  3828. * that is accounted.
  3829. */
  3830. if (memcg_kmem_is_active(memcg)) {
  3831. mem_cgroup_get(memcg);
  3832. static_key_slow_inc(&memcg_kmem_enabled_key);
  3833. }
  3834. #endif
  3835. }
  3836. /*
  3837. * The user of this function is...
  3838. * RES_LIMIT.
  3839. */
  3840. static int mem_cgroup_write(struct cgroup *cont, struct cftype *cft,
  3841. const char *buffer)
  3842. {
  3843. struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
  3844. enum res_type type;
  3845. int name;
  3846. unsigned long long val;
  3847. int ret;
  3848. type = MEMFILE_TYPE(cft->private);
  3849. name = MEMFILE_ATTR(cft->private);
  3850. if (!do_swap_account && type == _MEMSWAP)
  3851. return -EOPNOTSUPP;
  3852. switch (name) {
  3853. case RES_LIMIT:
  3854. if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
  3855. ret = -EINVAL;
  3856. break;
  3857. }
  3858. /* This function does all necessary parse...reuse it */
  3859. ret = res_counter_memparse_write_strategy(buffer, &val);
  3860. if (ret)
  3861. break;
  3862. if (type == _MEM)
  3863. ret = mem_cgroup_resize_limit(memcg, val);
  3864. else if (type == _MEMSWAP)
  3865. ret = mem_cgroup_resize_memsw_limit(memcg, val);
  3866. else if (type == _KMEM)
  3867. ret = memcg_update_kmem_limit(cont, val);
  3868. else
  3869. return -EINVAL;
  3870. break;
  3871. case RES_SOFT_LIMIT:
  3872. ret = res_counter_memparse_write_strategy(buffer, &val);
  3873. if (ret)
  3874. break;
  3875. /*
  3876. * For memsw, soft limits are hard to implement in terms
  3877. * of semantics, for now, we support soft limits for
  3878. * control without swap
  3879. */
  3880. if (type == _MEM)
  3881. ret = res_counter_set_soft_limit(&memcg->res, val);
  3882. else
  3883. ret = -EINVAL;
  3884. break;
  3885. default:
  3886. ret = -EINVAL; /* should be BUG() ? */
  3887. break;
  3888. }
  3889. return ret;
  3890. }
  3891. static void memcg_get_hierarchical_limit(struct mem_cgroup *memcg,
  3892. unsigned long long *mem_limit, unsigned long long *memsw_limit)
  3893. {
  3894. struct cgroup *cgroup;
  3895. unsigned long long min_limit, min_memsw_limit, tmp;
  3896. min_limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
  3897. min_memsw_limit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
  3898. cgroup = memcg->css.cgroup;
  3899. if (!memcg->use_hierarchy)
  3900. goto out;
  3901. while (cgroup->parent) {
  3902. cgroup = cgroup->parent;
  3903. memcg = mem_cgroup_from_cont(cgroup);
  3904. if (!memcg->use_hierarchy)
  3905. break;
  3906. tmp = res_counter_read_u64(&memcg->res, RES_LIMIT);
  3907. min_limit = min(min_limit, tmp);
  3908. tmp = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
  3909. min_memsw_limit = min(min_memsw_limit, tmp);
  3910. }
  3911. out:
  3912. *mem_limit = min_limit;
  3913. *memsw_limit = min_memsw_limit;
  3914. }
  3915. static int mem_cgroup_reset(struct cgroup *cont, unsigned int event)
  3916. {
  3917. struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
  3918. int name;
  3919. enum res_type type;
  3920. type = MEMFILE_TYPE(event);
  3921. name = MEMFILE_ATTR(event);
  3922. if (!do_swap_account && type == _MEMSWAP)
  3923. return -EOPNOTSUPP;
  3924. switch (name) {
  3925. case RES_MAX_USAGE:
  3926. if (type == _MEM)
  3927. res_counter_reset_max(&memcg->res);
  3928. else if (type == _MEMSWAP)
  3929. res_counter_reset_max(&memcg->memsw);
  3930. else if (type == _KMEM)
  3931. res_counter_reset_max(&memcg->kmem);
  3932. else
  3933. return -EINVAL;
  3934. break;
  3935. case RES_FAILCNT:
  3936. if (type == _MEM)
  3937. res_counter_reset_failcnt(&memcg->res);
  3938. else if (type == _MEMSWAP)
  3939. res_counter_reset_failcnt(&memcg->memsw);
  3940. else if (type == _KMEM)
  3941. res_counter_reset_failcnt(&memcg->kmem);
  3942. else
  3943. return -EINVAL;
  3944. break;
  3945. }
  3946. return 0;
  3947. }
  3948. static u64 mem_cgroup_move_charge_read(struct cgroup *cgrp,
  3949. struct cftype *cft)
  3950. {
  3951. return mem_cgroup_from_cont(cgrp)->move_charge_at_immigrate;
  3952. }
  3953. #ifdef CONFIG_MMU
  3954. static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
  3955. struct cftype *cft, u64 val)
  3956. {
  3957. struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
  3958. if (val >= (1 << NR_MOVE_TYPE))
  3959. return -EINVAL;
  3960. /*
  3961. * We check this value several times in both in can_attach() and
  3962. * attach(), so we need cgroup lock to prevent this value from being
  3963. * inconsistent.
  3964. */
  3965. cgroup_lock();
  3966. memcg->move_charge_at_immigrate = val;
  3967. cgroup_unlock();
  3968. return 0;
  3969. }
  3970. #else
  3971. static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
  3972. struct cftype *cft, u64 val)
  3973. {
  3974. return -ENOSYS;
  3975. }
  3976. #endif
  3977. #ifdef CONFIG_NUMA
  3978. static int memcg_numa_stat_show(struct cgroup *cont, struct cftype *cft,
  3979. struct seq_file *m)
  3980. {
  3981. int nid;
  3982. unsigned long total_nr, file_nr, anon_nr, unevictable_nr;
  3983. unsigned long node_nr;
  3984. struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
  3985. total_nr = mem_cgroup_nr_lru_pages(memcg, LRU_ALL);
  3986. seq_printf(m, "total=%lu", total_nr);
  3987. for_each_node_state(nid, N_HIGH_MEMORY) {
  3988. node_nr = mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL);
  3989. seq_printf(m, " N%d=%lu", nid, node_nr);
  3990. }
  3991. seq_putc(m, '\n');
  3992. file_nr = mem_cgroup_nr_lru_pages(memcg, LRU_ALL_FILE);
  3993. seq_printf(m, "file=%lu", file_nr);
  3994. for_each_node_state(nid, N_HIGH_MEMORY) {
  3995. node_nr = mem_cgroup_node_nr_lru_pages(memcg, nid,
  3996. LRU_ALL_FILE);
  3997. seq_printf(m, " N%d=%lu", nid, node_nr);
  3998. }
  3999. seq_putc(m, '\n');
  4000. anon_nr = mem_cgroup_nr_lru_pages(memcg, LRU_ALL_ANON);
  4001. seq_printf(m, "anon=%lu", anon_nr);
  4002. for_each_node_state(nid, N_HIGH_MEMORY) {
  4003. node_nr = mem_cgroup_node_nr_lru_pages(memcg, nid,
  4004. LRU_ALL_ANON);
  4005. seq_printf(m, " N%d=%lu", nid, node_nr);
  4006. }
  4007. seq_putc(m, '\n');
  4008. unevictable_nr = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_UNEVICTABLE));
  4009. seq_printf(m, "unevictable=%lu", unevictable_nr);
  4010. for_each_node_state(nid, N_HIGH_MEMORY) {
  4011. node_nr = mem_cgroup_node_nr_lru_pages(memcg, nid,
  4012. BIT(LRU_UNEVICTABLE));
  4013. seq_printf(m, " N%d=%lu", nid, node_nr);
  4014. }
  4015. seq_putc(m, '\n');
  4016. return 0;
  4017. }
  4018. #endif /* CONFIG_NUMA */
  4019. static const char * const mem_cgroup_lru_names[] = {
  4020. "inactive_anon",
  4021. "active_anon",
  4022. "inactive_file",
  4023. "active_file",
  4024. "unevictable",
  4025. };
  4026. static inline void mem_cgroup_lru_names_not_uptodate(void)
  4027. {
  4028. BUILD_BUG_ON(ARRAY_SIZE(mem_cgroup_lru_names) != NR_LRU_LISTS);
  4029. }
  4030. static int memcg_stat_show(struct cgroup *cont, struct cftype *cft,
  4031. struct seq_file *m)
  4032. {
  4033. struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
  4034. struct mem_cgroup *mi;
  4035. unsigned int i;
  4036. for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
  4037. if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
  4038. continue;
  4039. seq_printf(m, "%s %ld\n", mem_cgroup_stat_names[i],
  4040. mem_cgroup_read_stat(memcg, i) * PAGE_SIZE);
  4041. }
  4042. for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++)
  4043. seq_printf(m, "%s %lu\n", mem_cgroup_events_names[i],
  4044. mem_cgroup_read_events(memcg, i));
  4045. for (i = 0; i < NR_LRU_LISTS; i++)
  4046. seq_printf(m, "%s %lu\n", mem_cgroup_lru_names[i],
  4047. mem_cgroup_nr_lru_pages(memcg, BIT(i)) * PAGE_SIZE);
  4048. /* Hierarchical information */
  4049. {
  4050. unsigned long long limit, memsw_limit;
  4051. memcg_get_hierarchical_limit(memcg, &limit, &memsw_limit);
  4052. seq_printf(m, "hierarchical_memory_limit %llu\n", limit);
  4053. if (do_swap_account)
  4054. seq_printf(m, "hierarchical_memsw_limit %llu\n",
  4055. memsw_limit);
  4056. }
  4057. for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
  4058. long long val = 0;
  4059. if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
  4060. continue;
  4061. for_each_mem_cgroup_tree(mi, memcg)
  4062. val += mem_cgroup_read_stat(mi, i) * PAGE_SIZE;
  4063. seq_printf(m, "total_%s %lld\n", mem_cgroup_stat_names[i], val);
  4064. }
  4065. for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
  4066. unsigned long long val = 0;
  4067. for_each_mem_cgroup_tree(mi, memcg)
  4068. val += mem_cgroup_read_events(mi, i);
  4069. seq_printf(m, "total_%s %llu\n",
  4070. mem_cgroup_events_names[i], val);
  4071. }
  4072. for (i = 0; i < NR_LRU_LISTS; i++) {
  4073. unsigned long long val = 0;
  4074. for_each_mem_cgroup_tree(mi, memcg)
  4075. val += mem_cgroup_nr_lru_pages(mi, BIT(i)) * PAGE_SIZE;
  4076. seq_printf(m, "total_%s %llu\n", mem_cgroup_lru_names[i], val);
  4077. }
  4078. #ifdef CONFIG_DEBUG_VM
  4079. {
  4080. int nid, zid;
  4081. struct mem_cgroup_per_zone *mz;
  4082. struct zone_reclaim_stat *rstat;
  4083. unsigned long recent_rotated[2] = {0, 0};
  4084. unsigned long recent_scanned[2] = {0, 0};
  4085. for_each_online_node(nid)
  4086. for (zid = 0; zid < MAX_NR_ZONES; zid++) {
  4087. mz = mem_cgroup_zoneinfo(memcg, nid, zid);
  4088. rstat = &mz->lruvec.reclaim_stat;
  4089. recent_rotated[0] += rstat->recent_rotated[0];
  4090. recent_rotated[1] += rstat->recent_rotated[1];
  4091. recent_scanned[0] += rstat->recent_scanned[0];
  4092. recent_scanned[1] += rstat->recent_scanned[1];
  4093. }
  4094. seq_printf(m, "recent_rotated_anon %lu\n", recent_rotated[0]);
  4095. seq_printf(m, "recent_rotated_file %lu\n", recent_rotated[1]);
  4096. seq_printf(m, "recent_scanned_anon %lu\n", recent_scanned[0]);
  4097. seq_printf(m, "recent_scanned_file %lu\n", recent_scanned[1]);
  4098. }
  4099. #endif
  4100. return 0;
  4101. }
  4102. static u64 mem_cgroup_swappiness_read(struct cgroup *cgrp, struct cftype *cft)
  4103. {
  4104. struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
  4105. return mem_cgroup_swappiness(memcg);
  4106. }
  4107. static int mem_cgroup_swappiness_write(struct cgroup *cgrp, struct cftype *cft,
  4108. u64 val)
  4109. {
  4110. struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
  4111. struct mem_cgroup *parent;
  4112. if (val > 100)
  4113. return -EINVAL;
  4114. if (cgrp->parent == NULL)
  4115. return -EINVAL;
  4116. parent = mem_cgroup_from_cont(cgrp->parent);
  4117. cgroup_lock();
  4118. /* If under hierarchy, only empty-root can set this value */
  4119. if ((parent->use_hierarchy) ||
  4120. (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
  4121. cgroup_unlock();
  4122. return -EINVAL;
  4123. }
  4124. memcg->swappiness = val;
  4125. cgroup_unlock();
  4126. return 0;
  4127. }
  4128. static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
  4129. {
  4130. struct mem_cgroup_threshold_ary *t;
  4131. u64 usage;
  4132. int i;
  4133. rcu_read_lock();
  4134. if (!swap)
  4135. t = rcu_dereference(memcg->thresholds.primary);
  4136. else
  4137. t = rcu_dereference(memcg->memsw_thresholds.primary);
  4138. if (!t)
  4139. goto unlock;
  4140. usage = mem_cgroup_usage(memcg, swap);
  4141. /*
  4142. * current_threshold points to threshold just below or equal to usage.
  4143. * If it's not true, a threshold was crossed after last
  4144. * call of __mem_cgroup_threshold().
  4145. */
  4146. i = t->current_threshold;
  4147. /*
  4148. * Iterate backward over array of thresholds starting from
  4149. * current_threshold and check if a threshold is crossed.
  4150. * If none of thresholds below usage is crossed, we read
  4151. * only one element of the array here.
  4152. */
  4153. for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
  4154. eventfd_signal(t->entries[i].eventfd, 1);
  4155. /* i = current_threshold + 1 */
  4156. i++;
  4157. /*
  4158. * Iterate forward over array of thresholds starting from
  4159. * current_threshold+1 and check if a threshold is crossed.
  4160. * If none of thresholds above usage is crossed, we read
  4161. * only one element of the array here.
  4162. */
  4163. for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
  4164. eventfd_signal(t->entries[i].eventfd, 1);
  4165. /* Update current_threshold */
  4166. t->current_threshold = i - 1;
  4167. unlock:
  4168. rcu_read_unlock();
  4169. }
  4170. static void mem_cgroup_threshold(struct mem_cgroup *memcg)
  4171. {
  4172. while (memcg) {
  4173. __mem_cgroup_threshold(memcg, false);
  4174. if (do_swap_account)
  4175. __mem_cgroup_threshold(memcg, true);
  4176. memcg = parent_mem_cgroup(memcg);
  4177. }
  4178. }
  4179. static int compare_thresholds(const void *a, const void *b)
  4180. {
  4181. const struct mem_cgroup_threshold *_a = a;
  4182. const struct mem_cgroup_threshold *_b = b;
  4183. if (_a->threshold > _b->threshold)
  4184. return 1;
  4185. if (_a->threshold < _b->threshold)
  4186. return -1;
  4187. return 0;
  4188. }
  4189. static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
  4190. {
  4191. struct mem_cgroup_eventfd_list *ev;
  4192. list_for_each_entry(ev, &memcg->oom_notify, list)
  4193. eventfd_signal(ev->eventfd, 1);
  4194. return 0;
  4195. }
  4196. static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
  4197. {
  4198. struct mem_cgroup *iter;
  4199. for_each_mem_cgroup_tree(iter, memcg)
  4200. mem_cgroup_oom_notify_cb(iter);
  4201. }
  4202. static int mem_cgroup_usage_register_event(struct cgroup *cgrp,
  4203. struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
  4204. {
  4205. struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
  4206. struct mem_cgroup_thresholds *thresholds;
  4207. struct mem_cgroup_threshold_ary *new;
  4208. enum res_type type = MEMFILE_TYPE(cft->private);
  4209. u64 threshold, usage;
  4210. int i, size, ret;
  4211. ret = res_counter_memparse_write_strategy(args, &threshold);
  4212. if (ret)
  4213. return ret;
  4214. mutex_lock(&memcg->thresholds_lock);
  4215. if (type == _MEM)
  4216. thresholds = &memcg->thresholds;
  4217. else if (type == _MEMSWAP)
  4218. thresholds = &memcg->memsw_thresholds;
  4219. else
  4220. BUG();
  4221. usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
  4222. /* Check if a threshold crossed before adding a new one */
  4223. if (thresholds->primary)
  4224. __mem_cgroup_threshold(memcg, type == _MEMSWAP);
  4225. size = thresholds->primary ? thresholds->primary->size + 1 : 1;
  4226. /* Allocate memory for new array of thresholds */
  4227. new = kmalloc(sizeof(*new) + size * sizeof(struct mem_cgroup_threshold),
  4228. GFP_KERNEL);
  4229. if (!new) {
  4230. ret = -ENOMEM;
  4231. goto unlock;
  4232. }
  4233. new->size = size;
  4234. /* Copy thresholds (if any) to new array */
  4235. if (thresholds->primary) {
  4236. memcpy(new->entries, thresholds->primary->entries, (size - 1) *
  4237. sizeof(struct mem_cgroup_threshold));
  4238. }
  4239. /* Add new threshold */
  4240. new->entries[size - 1].eventfd = eventfd;
  4241. new->entries[size - 1].threshold = threshold;
  4242. /* Sort thresholds. Registering of new threshold isn't time-critical */
  4243. sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
  4244. compare_thresholds, NULL);
  4245. /* Find current threshold */
  4246. new->current_threshold = -1;
  4247. for (i = 0; i < size; i++) {
  4248. if (new->entries[i].threshold <= usage) {
  4249. /*
  4250. * new->current_threshold will not be used until
  4251. * rcu_assign_pointer(), so it's safe to increment
  4252. * it here.
  4253. */
  4254. ++new->current_threshold;
  4255. } else
  4256. break;
  4257. }
  4258. /* Free old spare buffer and save old primary buffer as spare */
  4259. kfree(thresholds->spare);
  4260. thresholds->spare = thresholds->primary;
  4261. rcu_assign_pointer(thresholds->primary, new);
  4262. /* To be sure that nobody uses thresholds */
  4263. synchronize_rcu();
  4264. unlock:
  4265. mutex_unlock(&memcg->thresholds_lock);
  4266. return ret;
  4267. }
  4268. static void mem_cgroup_usage_unregister_event(struct cgroup *cgrp,
  4269. struct cftype *cft, struct eventfd_ctx *eventfd)
  4270. {
  4271. struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
  4272. struct mem_cgroup_thresholds *thresholds;
  4273. struct mem_cgroup_threshold_ary *new;
  4274. enum res_type type = MEMFILE_TYPE(cft->private);
  4275. u64 usage;
  4276. int i, j, size;
  4277. mutex_lock(&memcg->thresholds_lock);
  4278. if (type == _MEM)
  4279. thresholds = &memcg->thresholds;
  4280. else if (type == _MEMSWAP)
  4281. thresholds = &memcg->memsw_thresholds;
  4282. else
  4283. BUG();
  4284. if (!thresholds->primary)
  4285. goto unlock;
  4286. usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
  4287. /* Check if a threshold crossed before removing */
  4288. __mem_cgroup_threshold(memcg, type == _MEMSWAP);
  4289. /* Calculate new number of threshold */
  4290. size = 0;
  4291. for (i = 0; i < thresholds->primary->size; i++) {
  4292. if (thresholds->primary->entries[i].eventfd != eventfd)
  4293. size++;
  4294. }
  4295. new = thresholds->spare;
  4296. /* Set thresholds array to NULL if we don't have thresholds */
  4297. if (!size) {
  4298. kfree(new);
  4299. new = NULL;
  4300. goto swap_buffers;
  4301. }
  4302. new->size = size;
  4303. /* Copy thresholds and find current threshold */
  4304. new->current_threshold = -1;
  4305. for (i = 0, j = 0; i < thresholds->primary->size; i++) {
  4306. if (thresholds->primary->entries[i].eventfd == eventfd)
  4307. continue;
  4308. new->entries[j] = thresholds->primary->entries[i];
  4309. if (new->entries[j].threshold <= usage) {
  4310. /*
  4311. * new->current_threshold will not be used
  4312. * until rcu_assign_pointer(), so it's safe to increment
  4313. * it here.
  4314. */
  4315. ++new->current_threshold;
  4316. }
  4317. j++;
  4318. }
  4319. swap_buffers:
  4320. /* Swap primary and spare array */
  4321. thresholds->spare = thresholds->primary;
  4322. rcu_assign_pointer(thresholds->primary, new);
  4323. /* To be sure that nobody uses thresholds */
  4324. synchronize_rcu();
  4325. /* If all events are unregistered, free the spare array */
  4326. if (!new) {
  4327. kfree(thresholds->spare);
  4328. thresholds->spare = NULL;
  4329. }
  4330. unlock:
  4331. mutex_unlock(&memcg->thresholds_lock);
  4332. }
  4333. static int mem_cgroup_oom_register_event(struct cgroup *cgrp,
  4334. struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
  4335. {
  4336. struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
  4337. struct mem_cgroup_eventfd_list *event;
  4338. enum res_type type = MEMFILE_TYPE(cft->private);
  4339. BUG_ON(type != _OOM_TYPE);
  4340. event = kmalloc(sizeof(*event), GFP_KERNEL);
  4341. if (!event)
  4342. return -ENOMEM;
  4343. spin_lock(&memcg_oom_lock);
  4344. event->eventfd = eventfd;
  4345. list_add(&event->list, &memcg->oom_notify);
  4346. /* already in OOM ? */
  4347. if (atomic_read(&memcg->under_oom))
  4348. eventfd_signal(eventfd, 1);
  4349. spin_unlock(&memcg_oom_lock);
  4350. return 0;
  4351. }
  4352. static void mem_cgroup_oom_unregister_event(struct cgroup *cgrp,
  4353. struct cftype *cft, struct eventfd_ctx *eventfd)
  4354. {
  4355. struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
  4356. struct mem_cgroup_eventfd_list *ev, *tmp;
  4357. enum res_type type = MEMFILE_TYPE(cft->private);
  4358. BUG_ON(type != _OOM_TYPE);
  4359. spin_lock(&memcg_oom_lock);
  4360. list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
  4361. if (ev->eventfd == eventfd) {
  4362. list_del(&ev->list);
  4363. kfree(ev);
  4364. }
  4365. }
  4366. spin_unlock(&memcg_oom_lock);
  4367. }
  4368. static int mem_cgroup_oom_control_read(struct cgroup *cgrp,
  4369. struct cftype *cft, struct cgroup_map_cb *cb)
  4370. {
  4371. struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
  4372. cb->fill(cb, "oom_kill_disable", memcg->oom_kill_disable);
  4373. if (atomic_read(&memcg->under_oom))
  4374. cb->fill(cb, "under_oom", 1);
  4375. else
  4376. cb->fill(cb, "under_oom", 0);
  4377. return 0;
  4378. }
  4379. static int mem_cgroup_oom_control_write(struct cgroup *cgrp,
  4380. struct cftype *cft, u64 val)
  4381. {
  4382. struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
  4383. struct mem_cgroup *parent;
  4384. /* cannot set to root cgroup and only 0 and 1 are allowed */
  4385. if (!cgrp->parent || !((val == 0) || (val == 1)))
  4386. return -EINVAL;
  4387. parent = mem_cgroup_from_cont(cgrp->parent);
  4388. cgroup_lock();
  4389. /* oom-kill-disable is a flag for subhierarchy. */
  4390. if ((parent->use_hierarchy) ||
  4391. (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
  4392. cgroup_unlock();
  4393. return -EINVAL;
  4394. }
  4395. memcg->oom_kill_disable = val;
  4396. if (!val)
  4397. memcg_oom_recover(memcg);
  4398. cgroup_unlock();
  4399. return 0;
  4400. }
  4401. #ifdef CONFIG_MEMCG_KMEM
  4402. static int memcg_init_kmem(struct mem_cgroup *memcg, struct cgroup_subsys *ss)
  4403. {
  4404. memcg_propagate_kmem(memcg);
  4405. return mem_cgroup_sockets_init(memcg, ss);
  4406. };
  4407. static void kmem_cgroup_destroy(struct mem_cgroup *memcg)
  4408. {
  4409. mem_cgroup_sockets_destroy(memcg);
  4410. memcg_kmem_mark_dead(memcg);
  4411. if (res_counter_read_u64(&memcg->kmem, RES_USAGE) != 0)
  4412. return;
  4413. /*
  4414. * Charges already down to 0, undo mem_cgroup_get() done in the charge
  4415. * path here, being careful not to race with memcg_uncharge_kmem: it is
  4416. * possible that the charges went down to 0 between mark_dead and the
  4417. * res_counter read, so in that case, we don't need the put
  4418. */
  4419. if (memcg_kmem_test_and_clear_dead(memcg))
  4420. mem_cgroup_put(memcg);
  4421. }
  4422. #else
  4423. static int memcg_init_kmem(struct mem_cgroup *memcg, struct cgroup_subsys *ss)
  4424. {
  4425. return 0;
  4426. }
  4427. static void kmem_cgroup_destroy(struct mem_cgroup *memcg)
  4428. {
  4429. }
  4430. #endif
  4431. static struct cftype mem_cgroup_files[] = {
  4432. {
  4433. .name = "usage_in_bytes",
  4434. .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
  4435. .read = mem_cgroup_read,
  4436. .register_event = mem_cgroup_usage_register_event,
  4437. .unregister_event = mem_cgroup_usage_unregister_event,
  4438. },
  4439. {
  4440. .name = "max_usage_in_bytes",
  4441. .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
  4442. .trigger = mem_cgroup_reset,
  4443. .read = mem_cgroup_read,
  4444. },
  4445. {
  4446. .name = "limit_in_bytes",
  4447. .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
  4448. .write_string = mem_cgroup_write,
  4449. .read = mem_cgroup_read,
  4450. },
  4451. {
  4452. .name = "soft_limit_in_bytes",
  4453. .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
  4454. .write_string = mem_cgroup_write,
  4455. .read = mem_cgroup_read,
  4456. },
  4457. {
  4458. .name = "failcnt",
  4459. .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
  4460. .trigger = mem_cgroup_reset,
  4461. .read = mem_cgroup_read,
  4462. },
  4463. {
  4464. .name = "stat",
  4465. .read_seq_string = memcg_stat_show,
  4466. },
  4467. {
  4468. .name = "force_empty",
  4469. .trigger = mem_cgroup_force_empty_write,
  4470. },
  4471. {
  4472. .name = "use_hierarchy",
  4473. .write_u64 = mem_cgroup_hierarchy_write,
  4474. .read_u64 = mem_cgroup_hierarchy_read,
  4475. },
  4476. {
  4477. .name = "swappiness",
  4478. .read_u64 = mem_cgroup_swappiness_read,
  4479. .write_u64 = mem_cgroup_swappiness_write,
  4480. },
  4481. {
  4482. .name = "move_charge_at_immigrate",
  4483. .read_u64 = mem_cgroup_move_charge_read,
  4484. .write_u64 = mem_cgroup_move_charge_write,
  4485. },
  4486. {
  4487. .name = "oom_control",
  4488. .read_map = mem_cgroup_oom_control_read,
  4489. .write_u64 = mem_cgroup_oom_control_write,
  4490. .register_event = mem_cgroup_oom_register_event,
  4491. .unregister_event = mem_cgroup_oom_unregister_event,
  4492. .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
  4493. },
  4494. {
  4495. .name = "pressure_level",
  4496. .register_event = vmpressure_register_event,
  4497. .unregister_event = vmpressure_unregister_event,
  4498. },
  4499. #ifdef CONFIG_NUMA
  4500. {
  4501. .name = "numa_stat",
  4502. .read_seq_string = memcg_numa_stat_show,
  4503. },
  4504. #endif
  4505. #ifdef CONFIG_MEMCG_SWAP
  4506. {
  4507. .name = "memsw.usage_in_bytes",
  4508. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
  4509. .read = mem_cgroup_read,
  4510. .register_event = mem_cgroup_usage_register_event,
  4511. .unregister_event = mem_cgroup_usage_unregister_event,
  4512. },
  4513. {
  4514. .name = "memsw.max_usage_in_bytes",
  4515. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
  4516. .trigger = mem_cgroup_reset,
  4517. .read = mem_cgroup_read,
  4518. },
  4519. {
  4520. .name = "memsw.limit_in_bytes",
  4521. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
  4522. .write_string = mem_cgroup_write,
  4523. .read = mem_cgroup_read,
  4524. },
  4525. {
  4526. .name = "memsw.failcnt",
  4527. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
  4528. .trigger = mem_cgroup_reset,
  4529. .read = mem_cgroup_read,
  4530. },
  4531. #endif
  4532. #ifdef CONFIG_MEMCG_KMEM
  4533. {
  4534. .name = "kmem.limit_in_bytes",
  4535. .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
  4536. .write_string = mem_cgroup_write,
  4537. .read = mem_cgroup_read,
  4538. },
  4539. {
  4540. .name = "kmem.usage_in_bytes",
  4541. .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
  4542. .read = mem_cgroup_read,
  4543. },
  4544. {
  4545. .name = "kmem.failcnt",
  4546. .private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
  4547. .trigger = mem_cgroup_reset,
  4548. .read = mem_cgroup_read,
  4549. },
  4550. {
  4551. .name = "kmem.max_usage_in_bytes",
  4552. .private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
  4553. .trigger = mem_cgroup_reset,
  4554. .read = mem_cgroup_read,
  4555. },
  4556. #endif
  4557. { }, /* terminate */
  4558. };
  4559. static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
  4560. {
  4561. struct mem_cgroup_per_node *pn;
  4562. struct mem_cgroup_per_zone *mz;
  4563. int zone, tmp = node;
  4564. /*
  4565. * This routine is called against possible nodes.
  4566. * But it's BUG to call kmalloc() against offline node.
  4567. *
  4568. * TODO: this routine can waste much memory for nodes which will
  4569. * never be onlined. It's better to use memory hotplug callback
  4570. * function.
  4571. */
  4572. if (!node_state(node, N_NORMAL_MEMORY))
  4573. tmp = -1;
  4574. pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
  4575. if (!pn)
  4576. return 1;
  4577. for (zone = 0; zone < MAX_NR_ZONES; zone++) {
  4578. mz = &pn->zoneinfo[zone];
  4579. lruvec_init(&mz->lruvec, &NODE_DATA(node)->node_zones[zone]);
  4580. mz->usage_in_excess = 0;
  4581. mz->on_tree = false;
  4582. mz->memcg = memcg;
  4583. }
  4584. memcg->info.nodeinfo[node] = pn;
  4585. return 0;
  4586. }
  4587. static void free_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
  4588. {
  4589. kfree(memcg->info.nodeinfo[node]);
  4590. }
  4591. static struct mem_cgroup *mem_cgroup_alloc(void)
  4592. {
  4593. struct mem_cgroup *memcg;
  4594. int size = sizeof(struct mem_cgroup);
  4595. /* Can be very big if MAX_NUMNODES is very big */
  4596. if (size < PAGE_SIZE)
  4597. memcg = kzalloc(size, GFP_KERNEL);
  4598. else
  4599. memcg = vzalloc(size);
  4600. if (!memcg)
  4601. return NULL;
  4602. memcg->stat = alloc_percpu(struct mem_cgroup_stat_cpu);
  4603. if (!memcg->stat)
  4604. goto out_free;
  4605. spin_lock_init(&memcg->pcp_counter_lock);
  4606. return memcg;
  4607. out_free:
  4608. if (size < PAGE_SIZE)
  4609. kfree(memcg);
  4610. else
  4611. vfree(memcg);
  4612. return NULL;
  4613. }
  4614. /*
  4615. * Helpers for freeing a kmalloc()ed/vzalloc()ed mem_cgroup by RCU,
  4616. * but in process context. The work_freeing structure is overlaid
  4617. * on the rcu_freeing structure, which itself is overlaid on memsw.
  4618. */
  4619. static void free_work(struct work_struct *work)
  4620. {
  4621. struct mem_cgroup *memcg;
  4622. int size = sizeof(struct mem_cgroup);
  4623. memcg = container_of(work, struct mem_cgroup, work_freeing);
  4624. /*
  4625. * We need to make sure that (at least for now), the jump label
  4626. * destruction code runs outside of the cgroup lock. This is because
  4627. * get_online_cpus(), which is called from the static_branch update,
  4628. * can't be called inside the cgroup_lock. cpusets are the ones
  4629. * enforcing this dependency, so if they ever change, we might as well.
  4630. *
  4631. * schedule_work() will guarantee this happens. Be careful if you need
  4632. * to move this code around, and make sure it is outside
  4633. * the cgroup_lock.
  4634. */
  4635. disarm_static_keys(memcg);
  4636. if (size < PAGE_SIZE)
  4637. kfree(memcg);
  4638. else
  4639. vfree(memcg);
  4640. }
  4641. static void free_rcu(struct rcu_head *rcu_head)
  4642. {
  4643. struct mem_cgroup *memcg;
  4644. memcg = container_of(rcu_head, struct mem_cgroup, rcu_freeing);
  4645. INIT_WORK(&memcg->work_freeing, free_work);
  4646. schedule_work(&memcg->work_freeing);
  4647. }
  4648. /*
  4649. * At destroying mem_cgroup, references from swap_cgroup can remain.
  4650. * (scanning all at force_empty is too costly...)
  4651. *
  4652. * Instead of clearing all references at force_empty, we remember
  4653. * the number of reference from swap_cgroup and free mem_cgroup when
  4654. * it goes down to 0.
  4655. *
  4656. * Removal of cgroup itself succeeds regardless of refs from swap.
  4657. */
  4658. static void __mem_cgroup_free(struct mem_cgroup *memcg)
  4659. {
  4660. int node;
  4661. mem_cgroup_remove_from_trees(memcg);
  4662. free_css_id(&mem_cgroup_subsys, &memcg->css);
  4663. for_each_node(node)
  4664. free_mem_cgroup_per_zone_info(memcg, node);
  4665. free_percpu(memcg->stat);
  4666. call_rcu(&memcg->rcu_freeing, free_rcu);
  4667. }
  4668. static void mem_cgroup_get(struct mem_cgroup *memcg)
  4669. {
  4670. atomic_inc(&memcg->refcnt);
  4671. }
  4672. static void __mem_cgroup_put(struct mem_cgroup *memcg, int count)
  4673. {
  4674. if (atomic_sub_and_test(count, &memcg->refcnt)) {
  4675. struct mem_cgroup *parent = parent_mem_cgroup(memcg);
  4676. __mem_cgroup_free(memcg);
  4677. if (parent)
  4678. mem_cgroup_put(parent);
  4679. }
  4680. }
  4681. static void mem_cgroup_put(struct mem_cgroup *memcg)
  4682. {
  4683. __mem_cgroup_put(memcg, 1);
  4684. }
  4685. /*
  4686. * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
  4687. */
  4688. struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *memcg)
  4689. {
  4690. if (!memcg->res.parent)
  4691. return NULL;
  4692. return mem_cgroup_from_res_counter(memcg->res.parent, res);
  4693. }
  4694. EXPORT_SYMBOL(parent_mem_cgroup);
  4695. #ifdef CONFIG_MEMCG_SWAP
  4696. static void __init enable_swap_cgroup(void)
  4697. {
  4698. if (!mem_cgroup_disabled() && really_do_swap_account)
  4699. do_swap_account = 1;
  4700. }
  4701. #else
  4702. static void __init enable_swap_cgroup(void)
  4703. {
  4704. }
  4705. #endif
  4706. static int mem_cgroup_soft_limit_tree_init(void)
  4707. {
  4708. struct mem_cgroup_tree_per_node *rtpn;
  4709. struct mem_cgroup_tree_per_zone *rtpz;
  4710. int tmp, node, zone;
  4711. for_each_node(node) {
  4712. tmp = node;
  4713. if (!node_state(node, N_NORMAL_MEMORY))
  4714. tmp = -1;
  4715. rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, tmp);
  4716. if (!rtpn)
  4717. goto err_cleanup;
  4718. soft_limit_tree.rb_tree_per_node[node] = rtpn;
  4719. for (zone = 0; zone < MAX_NR_ZONES; zone++) {
  4720. rtpz = &rtpn->rb_tree_per_zone[zone];
  4721. rtpz->rb_root = RB_ROOT;
  4722. spin_lock_init(&rtpz->lock);
  4723. }
  4724. }
  4725. return 0;
  4726. err_cleanup:
  4727. for_each_node(node) {
  4728. if (!soft_limit_tree.rb_tree_per_node[node])
  4729. break;
  4730. kfree(soft_limit_tree.rb_tree_per_node[node]);
  4731. soft_limit_tree.rb_tree_per_node[node] = NULL;
  4732. }
  4733. return 1;
  4734. }
  4735. static struct cgroup_subsys_state * __ref
  4736. mem_cgroup_create(struct cgroup *cont)
  4737. {
  4738. struct mem_cgroup *memcg, *parent;
  4739. long error = -ENOMEM;
  4740. int node;
  4741. memcg = mem_cgroup_alloc();
  4742. if (!memcg)
  4743. return ERR_PTR(error);
  4744. for_each_node(node)
  4745. if (alloc_mem_cgroup_per_zone_info(memcg, node))
  4746. goto free_out;
  4747. /* root ? */
  4748. if (cont->parent == NULL) {
  4749. int cpu;
  4750. enable_swap_cgroup();
  4751. parent = NULL;
  4752. if (mem_cgroup_soft_limit_tree_init())
  4753. goto free_out;
  4754. root_mem_cgroup = memcg;
  4755. for_each_possible_cpu(cpu) {
  4756. struct memcg_stock_pcp *stock =
  4757. &per_cpu(memcg_stock, cpu);
  4758. INIT_WORK(&stock->work, drain_local_stock);
  4759. }
  4760. hotcpu_notifier(memcg_cpu_hotplug_callback, 0);
  4761. } else {
  4762. parent = mem_cgroup_from_cont(cont->parent);
  4763. memcg->use_hierarchy = parent->use_hierarchy;
  4764. memcg->oom_kill_disable = parent->oom_kill_disable;
  4765. }
  4766. if (parent && parent->use_hierarchy) {
  4767. res_counter_init(&memcg->res, &parent->res);
  4768. res_counter_init(&memcg->memsw, &parent->memsw);
  4769. res_counter_init(&memcg->kmem, &parent->kmem);
  4770. /*
  4771. * We increment refcnt of the parent to ensure that we can
  4772. * safely access it on res_counter_charge/uncharge.
  4773. * This refcnt will be decremented when freeing this
  4774. * mem_cgroup(see mem_cgroup_put).
  4775. */
  4776. mem_cgroup_get(parent);
  4777. } else {
  4778. res_counter_init(&memcg->res, NULL);
  4779. res_counter_init(&memcg->memsw, NULL);
  4780. res_counter_init(&memcg->kmem, NULL);
  4781. /*
  4782. * Deeper hierachy with use_hierarchy == false doesn't make
  4783. * much sense so let cgroup subsystem know about this
  4784. * unfortunate state in our controller.
  4785. */
  4786. if (parent && parent != root_mem_cgroup)
  4787. mem_cgroup_subsys.broken_hierarchy = true;
  4788. }
  4789. memcg->last_scanned_node = MAX_NUMNODES;
  4790. INIT_LIST_HEAD(&memcg->oom_notify);
  4791. if (parent)
  4792. memcg->swappiness = mem_cgroup_swappiness(parent);
  4793. atomic_set(&memcg->refcnt, 1);
  4794. memcg->move_charge_at_immigrate = 0;
  4795. mutex_init(&memcg->thresholds_lock);
  4796. spin_lock_init(&memcg->move_lock);
  4797. vmpressure_init(&memcg->vmpressure);
  4798. error = memcg_init_kmem(memcg, &mem_cgroup_subsys);
  4799. if (error) {
  4800. /*
  4801. * We call put now because our (and parent's) refcnts
  4802. * are already in place. mem_cgroup_put() will internally
  4803. * call __mem_cgroup_free, so return directly
  4804. */
  4805. mem_cgroup_put(memcg);
  4806. return ERR_PTR(error);
  4807. }
  4808. return &memcg->css;
  4809. free_out:
  4810. __mem_cgroup_free(memcg);
  4811. return ERR_PTR(error);
  4812. }
  4813. static int mem_cgroup_pre_destroy(struct cgroup *cont)
  4814. {
  4815. struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
  4816. int ret;
  4817. css_get(&memcg->css);
  4818. ret = mem_cgroup_reparent_charges(memcg);
  4819. css_put(&memcg->css);
  4820. return ret;
  4821. }
  4822. static void mem_cgroup_destroy(struct cgroup *cont)
  4823. {
  4824. struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
  4825. kmem_cgroup_destroy(memcg);
  4826. mem_cgroup_put(memcg);
  4827. }
  4828. #ifdef CONFIG_MMU
  4829. /* Handlers for move charge at task migration. */
  4830. #define PRECHARGE_COUNT_AT_ONCE 256
  4831. static int mem_cgroup_do_precharge(unsigned long count)
  4832. {
  4833. int ret = 0;
  4834. int batch_count = PRECHARGE_COUNT_AT_ONCE;
  4835. struct mem_cgroup *memcg = mc.to;
  4836. if (mem_cgroup_is_root(memcg)) {
  4837. mc.precharge += count;
  4838. /* we don't need css_get for root */
  4839. return ret;
  4840. }
  4841. /* try to charge at once */
  4842. if (count > 1) {
  4843. struct res_counter *dummy;
  4844. /*
  4845. * "memcg" cannot be under rmdir() because we've already checked
  4846. * by cgroup_lock_live_cgroup() that it is not removed and we
  4847. * are still under the same cgroup_mutex. So we can postpone
  4848. * css_get().
  4849. */
  4850. if (res_counter_charge(&memcg->res, PAGE_SIZE * count, &dummy))
  4851. goto one_by_one;
  4852. if (do_swap_account && res_counter_charge(&memcg->memsw,
  4853. PAGE_SIZE * count, &dummy)) {
  4854. res_counter_uncharge(&memcg->res, PAGE_SIZE * count);
  4855. goto one_by_one;
  4856. }
  4857. mc.precharge += count;
  4858. return ret;
  4859. }
  4860. one_by_one:
  4861. /* fall back to one by one charge */
  4862. while (count--) {
  4863. if (signal_pending(current)) {
  4864. ret = -EINTR;
  4865. break;
  4866. }
  4867. if (!batch_count--) {
  4868. batch_count = PRECHARGE_COUNT_AT_ONCE;
  4869. cond_resched();
  4870. }
  4871. ret = __mem_cgroup_try_charge(NULL,
  4872. GFP_KERNEL, 1, &memcg, false);
  4873. if (ret)
  4874. /* mem_cgroup_clear_mc() will do uncharge later */
  4875. return ret;
  4876. mc.precharge++;
  4877. }
  4878. return ret;
  4879. }
  4880. /**
  4881. * get_mctgt_type - get target type of moving charge
  4882. * @vma: the vma the pte to be checked belongs
  4883. * @addr: the address corresponding to the pte to be checked
  4884. * @ptent: the pte to be checked
  4885. * @target: the pointer the target page or swap ent will be stored(can be NULL)
  4886. *
  4887. * Returns
  4888. * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
  4889. * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
  4890. * move charge. if @target is not NULL, the page is stored in target->page
  4891. * with extra refcnt got(Callers should handle it).
  4892. * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
  4893. * target for charge migration. if @target is not NULL, the entry is stored
  4894. * in target->ent.
  4895. *
  4896. * Called with pte lock held.
  4897. */
  4898. union mc_target {
  4899. struct page *page;
  4900. swp_entry_t ent;
  4901. };
  4902. enum mc_target_type {
  4903. MC_TARGET_NONE = 0,
  4904. MC_TARGET_PAGE,
  4905. MC_TARGET_SWAP,
  4906. };
  4907. static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
  4908. unsigned long addr, pte_t ptent)
  4909. {
  4910. struct page *page = vm_normal_page(vma, addr, ptent);
  4911. if (!page || !page_mapped(page))
  4912. return NULL;
  4913. if (PageAnon(page)) {
  4914. /* we don't move shared anon */
  4915. if (!move_anon())
  4916. return NULL;
  4917. } else if (!move_file())
  4918. /* we ignore mapcount for file pages */
  4919. return NULL;
  4920. if (!get_page_unless_zero(page))
  4921. return NULL;
  4922. return page;
  4923. }
  4924. #ifdef CONFIG_SWAP
  4925. static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
  4926. unsigned long addr, pte_t ptent, swp_entry_t *entry)
  4927. {
  4928. struct page *page = NULL;
  4929. swp_entry_t ent = pte_to_swp_entry(ptent);
  4930. if (!move_anon() || non_swap_entry(ent))
  4931. return NULL;
  4932. /*
  4933. * Because lookup_swap_cache() updates some statistics counter,
  4934. * we call find_get_page() with swapper_space directly.
  4935. */
  4936. page = find_get_page(swap_address_space(ent), ent.val);
  4937. if (do_swap_account)
  4938. entry->val = ent.val;
  4939. return page;
  4940. }
  4941. #else
  4942. static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
  4943. unsigned long addr, pte_t ptent, swp_entry_t *entry)
  4944. {
  4945. return NULL;
  4946. }
  4947. #endif
  4948. static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
  4949. unsigned long addr, pte_t ptent, swp_entry_t *entry)
  4950. {
  4951. struct page *page = NULL;
  4952. struct address_space *mapping;
  4953. pgoff_t pgoff;
  4954. if (!vma->vm_file) /* anonymous vma */
  4955. return NULL;
  4956. if (!move_file())
  4957. return NULL;
  4958. mapping = vma->vm_file->f_mapping;
  4959. if (pte_none(ptent))
  4960. pgoff = linear_page_index(vma, addr);
  4961. else /* pte_file(ptent) is true */
  4962. pgoff = pte_to_pgoff(ptent);
  4963. /* page is moved even if it's not RSS of this task(page-faulted). */
  4964. page = find_get_page(mapping, pgoff);
  4965. #ifdef CONFIG_SWAP
  4966. /* shmem/tmpfs may report page out on swap: account for that too. */
  4967. if (radix_tree_exceptional_entry(page)) {
  4968. swp_entry_t swap = radix_to_swp_entry(page);
  4969. if (do_swap_account)
  4970. *entry = swap;
  4971. page = find_get_page(swap_address_space(swap), swap.val);
  4972. }
  4973. #endif
  4974. return page;
  4975. }
  4976. static enum mc_target_type get_mctgt_type(struct vm_area_struct *vma,
  4977. unsigned long addr, pte_t ptent, union mc_target *target)
  4978. {
  4979. struct page *page = NULL;
  4980. struct page_cgroup *pc;
  4981. enum mc_target_type ret = MC_TARGET_NONE;
  4982. swp_entry_t ent = { .val = 0 };
  4983. if (pte_present(ptent))
  4984. page = mc_handle_present_pte(vma, addr, ptent);
  4985. else if (is_swap_pte(ptent))
  4986. page = mc_handle_swap_pte(vma, addr, ptent, &ent);
  4987. else if (pte_none(ptent) || pte_file(ptent))
  4988. page = mc_handle_file_pte(vma, addr, ptent, &ent);
  4989. if (!page && !ent.val)
  4990. return ret;
  4991. if (page) {
  4992. pc = lookup_page_cgroup(page);
  4993. /*
  4994. * Do only loose check w/o page_cgroup lock.
  4995. * mem_cgroup_move_account() checks the pc is valid or not under
  4996. * the lock.
  4997. */
  4998. if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
  4999. ret = MC_TARGET_PAGE;
  5000. if (target)
  5001. target->page = page;
  5002. }
  5003. if (!ret || !target)
  5004. put_page(page);
  5005. }
  5006. /* There is a swap entry and a page doesn't exist or isn't charged */
  5007. if (ent.val && !ret &&
  5008. css_id(&mc.from->css) == lookup_swap_cgroup_id(ent)) {
  5009. ret = MC_TARGET_SWAP;
  5010. if (target)
  5011. target->ent = ent;
  5012. }
  5013. return ret;
  5014. }
  5015. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  5016. /*
  5017. * We don't consider swapping or file mapped pages because THP does not
  5018. * support them for now.
  5019. * Caller should make sure that pmd_trans_huge(pmd) is true.
  5020. */
  5021. static enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
  5022. unsigned long addr, pmd_t pmd, union mc_target *target)
  5023. {
  5024. struct page *page = NULL;
  5025. struct page_cgroup *pc;
  5026. enum mc_target_type ret = MC_TARGET_NONE;
  5027. page = pmd_page(pmd);
  5028. VM_BUG_ON(!page || !PageHead(page));
  5029. if (!move_anon())
  5030. return ret;
  5031. pc = lookup_page_cgroup(page);
  5032. if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
  5033. ret = MC_TARGET_PAGE;
  5034. if (target) {
  5035. get_page(page);
  5036. target->page = page;
  5037. }
  5038. }
  5039. return ret;
  5040. }
  5041. #else
  5042. static inline enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
  5043. unsigned long addr, pmd_t pmd, union mc_target *target)
  5044. {
  5045. return MC_TARGET_NONE;
  5046. }
  5047. #endif
  5048. static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
  5049. unsigned long addr, unsigned long end,
  5050. struct mm_walk *walk)
  5051. {
  5052. struct vm_area_struct *vma = walk->private;
  5053. pte_t *pte;
  5054. spinlock_t *ptl;
  5055. if (pmd_trans_huge_lock(pmd, vma) == 1) {
  5056. if (get_mctgt_type_thp(vma, addr, *pmd, NULL) == MC_TARGET_PAGE)
  5057. mc.precharge += HPAGE_PMD_NR;
  5058. spin_unlock(&vma->vm_mm->page_table_lock);
  5059. return 0;
  5060. }
  5061. if (pmd_trans_unstable(pmd))
  5062. return 0;
  5063. pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
  5064. for (; addr != end; pte++, addr += PAGE_SIZE)
  5065. if (get_mctgt_type(vma, addr, *pte, NULL))
  5066. mc.precharge++; /* increment precharge temporarily */
  5067. pte_unmap_unlock(pte - 1, ptl);
  5068. cond_resched();
  5069. return 0;
  5070. }
  5071. static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
  5072. {
  5073. unsigned long precharge;
  5074. struct vm_area_struct *vma;
  5075. down_read(&mm->mmap_sem);
  5076. for (vma = mm->mmap; vma; vma = vma->vm_next) {
  5077. struct mm_walk mem_cgroup_count_precharge_walk = {
  5078. .pmd_entry = mem_cgroup_count_precharge_pte_range,
  5079. .mm = mm,
  5080. .private = vma,
  5081. };
  5082. if (is_vm_hugetlb_page(vma))
  5083. continue;
  5084. walk_page_range(vma->vm_start, vma->vm_end,
  5085. &mem_cgroup_count_precharge_walk);
  5086. }
  5087. up_read(&mm->mmap_sem);
  5088. precharge = mc.precharge;
  5089. mc.precharge = 0;
  5090. return precharge;
  5091. }
  5092. static int mem_cgroup_precharge_mc(struct mm_struct *mm)
  5093. {
  5094. unsigned long precharge = mem_cgroup_count_precharge(mm);
  5095. VM_BUG_ON(mc.moving_task);
  5096. mc.moving_task = current;
  5097. return mem_cgroup_do_precharge(precharge);
  5098. }
  5099. /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
  5100. static void __mem_cgroup_clear_mc(void)
  5101. {
  5102. struct mem_cgroup *from = mc.from;
  5103. struct mem_cgroup *to = mc.to;
  5104. /* we must uncharge all the leftover precharges from mc.to */
  5105. if (mc.precharge) {
  5106. __mem_cgroup_cancel_charge(mc.to, mc.precharge);
  5107. mc.precharge = 0;
  5108. }
  5109. /*
  5110. * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
  5111. * we must uncharge here.
  5112. */
  5113. if (mc.moved_charge) {
  5114. __mem_cgroup_cancel_charge(mc.from, mc.moved_charge);
  5115. mc.moved_charge = 0;
  5116. }
  5117. /* we must fixup refcnts and charges */
  5118. if (mc.moved_swap) {
  5119. /* uncharge swap account from the old cgroup */
  5120. if (!mem_cgroup_is_root(mc.from))
  5121. res_counter_uncharge(&mc.from->memsw,
  5122. PAGE_SIZE * mc.moved_swap);
  5123. __mem_cgroup_put(mc.from, mc.moved_swap);
  5124. if (!mem_cgroup_is_root(mc.to)) {
  5125. /*
  5126. * we charged both to->res and to->memsw, so we should
  5127. * uncharge to->res.
  5128. */
  5129. res_counter_uncharge(&mc.to->res,
  5130. PAGE_SIZE * mc.moved_swap);
  5131. }
  5132. /* we've already done mem_cgroup_get(mc.to) */
  5133. mc.moved_swap = 0;
  5134. }
  5135. memcg_oom_recover(from);
  5136. memcg_oom_recover(to);
  5137. wake_up_all(&mc.waitq);
  5138. }
  5139. static void mem_cgroup_clear_mc(void)
  5140. {
  5141. struct mem_cgroup *from = mc.from;
  5142. /*
  5143. * we must clear moving_task before waking up waiters at the end of
  5144. * task migration.
  5145. */
  5146. mc.moving_task = NULL;
  5147. __mem_cgroup_clear_mc();
  5148. spin_lock(&mc.lock);
  5149. mc.from = NULL;
  5150. mc.to = NULL;
  5151. spin_unlock(&mc.lock);
  5152. mem_cgroup_end_move(from);
  5153. }
  5154. static int mem_cgroup_can_attach(struct cgroup *cgroup,
  5155. struct cgroup_taskset *tset)
  5156. {
  5157. struct task_struct *p = cgroup_taskset_first(tset);
  5158. int ret = 0;
  5159. struct mem_cgroup *memcg = mem_cgroup_from_cont(cgroup);
  5160. if (memcg->move_charge_at_immigrate) {
  5161. struct mm_struct *mm;
  5162. struct mem_cgroup *from = mem_cgroup_from_task(p);
  5163. VM_BUG_ON(from == memcg);
  5164. mm = get_task_mm(p);
  5165. if (!mm)
  5166. return 0;
  5167. /* We move charges only when we move a owner of the mm */
  5168. if (mm->owner == p) {
  5169. VM_BUG_ON(mc.from);
  5170. VM_BUG_ON(mc.to);
  5171. VM_BUG_ON(mc.precharge);
  5172. VM_BUG_ON(mc.moved_charge);
  5173. VM_BUG_ON(mc.moved_swap);
  5174. mem_cgroup_start_move(from);
  5175. spin_lock(&mc.lock);
  5176. mc.from = from;
  5177. mc.to = memcg;
  5178. spin_unlock(&mc.lock);
  5179. /* We set mc.moving_task later */
  5180. ret = mem_cgroup_precharge_mc(mm);
  5181. if (ret)
  5182. mem_cgroup_clear_mc();
  5183. }
  5184. mmput(mm);
  5185. }
  5186. return ret;
  5187. }
  5188. static void mem_cgroup_cancel_attach(struct cgroup *cgroup,
  5189. struct cgroup_taskset *tset)
  5190. {
  5191. mem_cgroup_clear_mc();
  5192. }
  5193. static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
  5194. unsigned long addr, unsigned long end,
  5195. struct mm_walk *walk)
  5196. {
  5197. int ret = 0;
  5198. struct vm_area_struct *vma = walk->private;
  5199. pte_t *pte;
  5200. spinlock_t *ptl;
  5201. enum mc_target_type target_type;
  5202. union mc_target target;
  5203. struct page *page;
  5204. struct page_cgroup *pc;
  5205. /*
  5206. * We don't take compound_lock() here but no race with splitting thp
  5207. * happens because:
  5208. * - if pmd_trans_huge_lock() returns 1, the relevant thp is not
  5209. * under splitting, which means there's no concurrent thp split,
  5210. * - if another thread runs into split_huge_page() just after we
  5211. * entered this if-block, the thread must wait for page table lock
  5212. * to be unlocked in __split_huge_page_splitting(), where the main
  5213. * part of thp split is not executed yet.
  5214. */
  5215. if (pmd_trans_huge_lock(pmd, vma) == 1) {
  5216. if (mc.precharge < HPAGE_PMD_NR) {
  5217. spin_unlock(&vma->vm_mm->page_table_lock);
  5218. return 0;
  5219. }
  5220. target_type = get_mctgt_type_thp(vma, addr, *pmd, &target);
  5221. if (target_type == MC_TARGET_PAGE) {
  5222. page = target.page;
  5223. if (!isolate_lru_page(page)) {
  5224. pc = lookup_page_cgroup(page);
  5225. if (!mem_cgroup_move_account(page, HPAGE_PMD_NR,
  5226. pc, mc.from, mc.to)) {
  5227. mc.precharge -= HPAGE_PMD_NR;
  5228. mc.moved_charge += HPAGE_PMD_NR;
  5229. }
  5230. putback_lru_page(page);
  5231. }
  5232. put_page(page);
  5233. }
  5234. spin_unlock(&vma->vm_mm->page_table_lock);
  5235. return 0;
  5236. }
  5237. if (pmd_trans_unstable(pmd))
  5238. return 0;
  5239. retry:
  5240. pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
  5241. for (; addr != end; addr += PAGE_SIZE) {
  5242. pte_t ptent = *(pte++);
  5243. swp_entry_t ent;
  5244. if (!mc.precharge)
  5245. break;
  5246. switch (get_mctgt_type(vma, addr, ptent, &target)) {
  5247. case MC_TARGET_PAGE:
  5248. page = target.page;
  5249. if (isolate_lru_page(page))
  5250. goto put;
  5251. pc = lookup_page_cgroup(page);
  5252. if (!mem_cgroup_move_account(page, 1, pc,
  5253. mc.from, mc.to)) {
  5254. mc.precharge--;
  5255. /* we uncharge from mc.from later. */
  5256. mc.moved_charge++;
  5257. }
  5258. putback_lru_page(page);
  5259. put: /* get_mctgt_type() gets the page */
  5260. put_page(page);
  5261. break;
  5262. case MC_TARGET_SWAP:
  5263. ent = target.ent;
  5264. if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to)) {
  5265. mc.precharge--;
  5266. /* we fixup refcnts and charges later. */
  5267. mc.moved_swap++;
  5268. }
  5269. break;
  5270. default:
  5271. break;
  5272. }
  5273. }
  5274. pte_unmap_unlock(pte - 1, ptl);
  5275. cond_resched();
  5276. if (addr != end) {
  5277. /*
  5278. * We have consumed all precharges we got in can_attach().
  5279. * We try charge one by one, but don't do any additional
  5280. * charges to mc.to if we have failed in charge once in attach()
  5281. * phase.
  5282. */
  5283. ret = mem_cgroup_do_precharge(1);
  5284. if (!ret)
  5285. goto retry;
  5286. }
  5287. return ret;
  5288. }
  5289. static void mem_cgroup_move_charge(struct mm_struct *mm)
  5290. {
  5291. struct vm_area_struct *vma;
  5292. lru_add_drain_all();
  5293. retry:
  5294. if (unlikely(!down_read_trylock(&mm->mmap_sem))) {
  5295. /*
  5296. * Someone who are holding the mmap_sem might be waiting in
  5297. * waitq. So we cancel all extra charges, wake up all waiters,
  5298. * and retry. Because we cancel precharges, we might not be able
  5299. * to move enough charges, but moving charge is a best-effort
  5300. * feature anyway, so it wouldn't be a big problem.
  5301. */
  5302. __mem_cgroup_clear_mc();
  5303. cond_resched();
  5304. goto retry;
  5305. }
  5306. for (vma = mm->mmap; vma; vma = vma->vm_next) {
  5307. int ret;
  5308. struct mm_walk mem_cgroup_move_charge_walk = {
  5309. .pmd_entry = mem_cgroup_move_charge_pte_range,
  5310. .mm = mm,
  5311. .private = vma,
  5312. };
  5313. if (is_vm_hugetlb_page(vma))
  5314. continue;
  5315. ret = walk_page_range(vma->vm_start, vma->vm_end,
  5316. &mem_cgroup_move_charge_walk);
  5317. if (ret)
  5318. /*
  5319. * means we have consumed all precharges and failed in
  5320. * doing additional charge. Just abandon here.
  5321. */
  5322. break;
  5323. }
  5324. up_read(&mm->mmap_sem);
  5325. }
  5326. static void mem_cgroup_move_task(struct cgroup *cont,
  5327. struct cgroup_taskset *tset)
  5328. {
  5329. struct task_struct *p = cgroup_taskset_first(tset);
  5330. struct mm_struct *mm = get_task_mm(p);
  5331. if (mm) {
  5332. if (mc.to)
  5333. mem_cgroup_move_charge(mm);
  5334. mmput(mm);
  5335. }
  5336. if (mc.to)
  5337. mem_cgroup_clear_mc();
  5338. }
  5339. #else /* !CONFIG_MMU */
  5340. static int mem_cgroup_can_attach(struct cgroup *cgroup,
  5341. struct cgroup_taskset *tset)
  5342. {
  5343. return 0;
  5344. }
  5345. static void mem_cgroup_cancel_attach(struct cgroup *cgroup,
  5346. struct cgroup_taskset *tset)
  5347. {
  5348. }
  5349. static void mem_cgroup_move_task(struct cgroup *cont,
  5350. struct cgroup_taskset *tset)
  5351. {
  5352. }
  5353. #endif
  5354. struct cgroup_subsys mem_cgroup_subsys = {
  5355. .name = "memory",
  5356. .subsys_id = mem_cgroup_subsys_id,
  5357. .create = mem_cgroup_create,
  5358. .pre_destroy = mem_cgroup_pre_destroy,
  5359. .destroy = mem_cgroup_destroy,
  5360. .can_attach = mem_cgroup_can_attach,
  5361. .cancel_attach = mem_cgroup_cancel_attach,
  5362. .attach = mem_cgroup_move_task,
  5363. .base_cftypes = mem_cgroup_files,
  5364. .early_init = 0,
  5365. .use_id = 1,
  5366. };
  5367. #ifdef CONFIG_MEMCG_SWAP
  5368. static int __init enable_swap_account(char *s)
  5369. {
  5370. /* consider enabled if no parameter or 1 is given */
  5371. if (!strcmp(s, "1"))
  5372. really_do_swap_account = 1;
  5373. else if (!strcmp(s, "0"))
  5374. really_do_swap_account = 0;
  5375. return 1;
  5376. }
  5377. __setup("swapaccount=", enable_swap_account);
  5378. #endif