memcontrol.c 187 KB

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