memcontrol.c 194 KB

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