memcontrol.c 193 KB

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