memcontrol.c 153 KB

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