memcontrol.c 168 KB

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