memcontrol.c 188 KB

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