memcontrol.c 186 KB

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