memcontrol.c 155 KB

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