memcontrol.c 191 KB

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