memcontrol.c 184 KB

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