memcontrol.c 177 KB

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