memcontrol.c 181 KB

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