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