memcontrol.c 180 KB

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