memcontrol.c 158 KB

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