memcontrol.c 160 KB

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