memcontrol.c 186 KB

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