memcontrol.c 190 KB

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