memcontrol.c 179 KB

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