memcontrol.c 182 KB

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