memcontrol.c 186 KB

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