memcontrol.c 185 KB

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