memcontrol.c 181 KB

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