memcontrol.c 165 KB

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