memcontrol.c 185 KB

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