memcontrol.c 186 KB

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