memcontrol.c 184 KB

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