memcontrol.c 172 KB

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