memcontrol.c 181 KB

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