memcontrol.c 150 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928
  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. * Native page reclaim
  18. * Charge lifetime sanitation
  19. * Lockless page tracking & accounting
  20. * Unified hierarchy configuration model
  21. * Copyright (C) 2015 Red Hat, Inc., Johannes Weiner
  22. *
  23. * This program is free software; you can redistribute it and/or modify
  24. * it under the terms of the GNU General Public License as published by
  25. * the Free Software Foundation; either version 2 of the License, or
  26. * (at your option) any later version.
  27. *
  28. * This program is distributed in the hope that it will be useful,
  29. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  30. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  31. * GNU General Public License for more details.
  32. */
  33. #include <linux/page_counter.h>
  34. #include <linux/memcontrol.h>
  35. #include <linux/cgroup.h>
  36. #include <linux/mm.h>
  37. #include <linux/hugetlb.h>
  38. #include <linux/pagemap.h>
  39. #include <linux/smp.h>
  40. #include <linux/page-flags.h>
  41. #include <linux/backing-dev.h>
  42. #include <linux/bit_spinlock.h>
  43. #include <linux/rcupdate.h>
  44. #include <linux/limits.h>
  45. #include <linux/export.h>
  46. #include <linux/mutex.h>
  47. #include <linux/rbtree.h>
  48. #include <linux/slab.h>
  49. #include <linux/swap.h>
  50. #include <linux/swapops.h>
  51. #include <linux/spinlock.h>
  52. #include <linux/eventfd.h>
  53. #include <linux/poll.h>
  54. #include <linux/sort.h>
  55. #include <linux/fs.h>
  56. #include <linux/seq_file.h>
  57. #include <linux/vmpressure.h>
  58. #include <linux/mm_inline.h>
  59. #include <linux/swap_cgroup.h>
  60. #include <linux/cpu.h>
  61. #include <linux/oom.h>
  62. #include <linux/lockdep.h>
  63. #include <linux/file.h>
  64. #include "internal.h"
  65. #include <net/sock.h>
  66. #include <net/ip.h>
  67. #include <net/tcp_memcontrol.h>
  68. #include "slab.h"
  69. #include <asm/uaccess.h>
  70. #include <trace/events/vmscan.h>
  71. struct cgroup_subsys memory_cgrp_subsys __read_mostly;
  72. EXPORT_SYMBOL(memory_cgrp_subsys);
  73. #define MEM_CGROUP_RECLAIM_RETRIES 5
  74. static struct mem_cgroup *root_mem_cgroup __read_mostly;
  75. /* Whether the swap controller is active */
  76. #ifdef CONFIG_MEMCG_SWAP
  77. int do_swap_account __read_mostly;
  78. #else
  79. #define do_swap_account 0
  80. #endif
  81. static const char * const mem_cgroup_stat_names[] = {
  82. "cache",
  83. "rss",
  84. "rss_huge",
  85. "mapped_file",
  86. "writeback",
  87. "swap",
  88. };
  89. static const char * const mem_cgroup_events_names[] = {
  90. "pgpgin",
  91. "pgpgout",
  92. "pgfault",
  93. "pgmajfault",
  94. };
  95. static const char * const mem_cgroup_lru_names[] = {
  96. "inactive_anon",
  97. "active_anon",
  98. "inactive_file",
  99. "active_file",
  100. "unevictable",
  101. };
  102. /*
  103. * Per memcg event counter is incremented at every pagein/pageout. With THP,
  104. * it will be incremated by the number of pages. This counter is used for
  105. * for trigger some periodic events. This is straightforward and better
  106. * than using jiffies etc. to handle periodic memcg event.
  107. */
  108. enum mem_cgroup_events_target {
  109. MEM_CGROUP_TARGET_THRESH,
  110. MEM_CGROUP_TARGET_SOFTLIMIT,
  111. MEM_CGROUP_TARGET_NUMAINFO,
  112. MEM_CGROUP_NTARGETS,
  113. };
  114. #define THRESHOLDS_EVENTS_TARGET 128
  115. #define SOFTLIMIT_EVENTS_TARGET 1024
  116. #define NUMAINFO_EVENTS_TARGET 1024
  117. struct mem_cgroup_stat_cpu {
  118. long count[MEM_CGROUP_STAT_NSTATS];
  119. unsigned long events[MEMCG_NR_EVENTS];
  120. unsigned long nr_page_events;
  121. unsigned long targets[MEM_CGROUP_NTARGETS];
  122. };
  123. struct reclaim_iter {
  124. struct mem_cgroup *position;
  125. /* scan generation, increased every round-trip */
  126. unsigned int generation;
  127. };
  128. /*
  129. * per-zone information in memory controller.
  130. */
  131. struct mem_cgroup_per_zone {
  132. struct lruvec lruvec;
  133. unsigned long lru_size[NR_LRU_LISTS];
  134. struct reclaim_iter iter[DEF_PRIORITY + 1];
  135. struct rb_node tree_node; /* RB tree node */
  136. unsigned long usage_in_excess;/* Set to the value by which */
  137. /* the soft limit is exceeded*/
  138. bool on_tree;
  139. struct mem_cgroup *memcg; /* Back pointer, we cannot */
  140. /* use container_of */
  141. };
  142. struct mem_cgroup_per_node {
  143. struct mem_cgroup_per_zone zoneinfo[MAX_NR_ZONES];
  144. };
  145. /*
  146. * Cgroups above their limits are maintained in a RB-Tree, independent of
  147. * their hierarchy representation
  148. */
  149. struct mem_cgroup_tree_per_zone {
  150. struct rb_root rb_root;
  151. spinlock_t lock;
  152. };
  153. struct mem_cgroup_tree_per_node {
  154. struct mem_cgroup_tree_per_zone rb_tree_per_zone[MAX_NR_ZONES];
  155. };
  156. struct mem_cgroup_tree {
  157. struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
  158. };
  159. static struct mem_cgroup_tree soft_limit_tree __read_mostly;
  160. struct mem_cgroup_threshold {
  161. struct eventfd_ctx *eventfd;
  162. unsigned long threshold;
  163. };
  164. /* For threshold */
  165. struct mem_cgroup_threshold_ary {
  166. /* An array index points to threshold just below or equal to usage. */
  167. int current_threshold;
  168. /* Size of entries[] */
  169. unsigned int size;
  170. /* Array of thresholds */
  171. struct mem_cgroup_threshold entries[0];
  172. };
  173. struct mem_cgroup_thresholds {
  174. /* Primary thresholds array */
  175. struct mem_cgroup_threshold_ary *primary;
  176. /*
  177. * Spare threshold array.
  178. * This is needed to make mem_cgroup_unregister_event() "never fail".
  179. * It must be able to store at least primary->size - 1 entries.
  180. */
  181. struct mem_cgroup_threshold_ary *spare;
  182. };
  183. /* for OOM */
  184. struct mem_cgroup_eventfd_list {
  185. struct list_head list;
  186. struct eventfd_ctx *eventfd;
  187. };
  188. /*
  189. * cgroup_event represents events which userspace want to receive.
  190. */
  191. struct mem_cgroup_event {
  192. /*
  193. * memcg which the event belongs to.
  194. */
  195. struct mem_cgroup *memcg;
  196. /*
  197. * eventfd to signal userspace about the event.
  198. */
  199. struct eventfd_ctx *eventfd;
  200. /*
  201. * Each of these stored in a list by the cgroup.
  202. */
  203. struct list_head list;
  204. /*
  205. * register_event() callback will be used to add new userspace
  206. * waiter for changes related to this event. Use eventfd_signal()
  207. * on eventfd to send notification to userspace.
  208. */
  209. int (*register_event)(struct mem_cgroup *memcg,
  210. struct eventfd_ctx *eventfd, const char *args);
  211. /*
  212. * unregister_event() callback will be called when userspace closes
  213. * the eventfd or on cgroup removing. This callback must be set,
  214. * if you want provide notification functionality.
  215. */
  216. void (*unregister_event)(struct mem_cgroup *memcg,
  217. struct eventfd_ctx *eventfd);
  218. /*
  219. * All fields below needed to unregister event when
  220. * userspace closes eventfd.
  221. */
  222. poll_table pt;
  223. wait_queue_head_t *wqh;
  224. wait_queue_t wait;
  225. struct work_struct remove;
  226. };
  227. static void mem_cgroup_threshold(struct mem_cgroup *memcg);
  228. static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
  229. /*
  230. * The memory controller data structure. The memory controller controls both
  231. * page cache and RSS per cgroup. We would eventually like to provide
  232. * statistics based on the statistics developed by Rik Van Riel for clock-pro,
  233. * to help the administrator determine what knobs to tune.
  234. */
  235. struct mem_cgroup {
  236. struct cgroup_subsys_state css;
  237. /* Accounted resources */
  238. struct page_counter memory;
  239. struct page_counter memsw;
  240. struct page_counter kmem;
  241. /* Normal memory consumption range */
  242. unsigned long low;
  243. unsigned long high;
  244. unsigned long soft_limit;
  245. /* vmpressure notifications */
  246. struct vmpressure vmpressure;
  247. /* css_online() has been completed */
  248. int initialized;
  249. /*
  250. * Should the accounting and control be hierarchical, per subtree?
  251. */
  252. bool use_hierarchy;
  253. bool oom_lock;
  254. atomic_t under_oom;
  255. atomic_t oom_wakeups;
  256. int swappiness;
  257. /* OOM-Killer disable */
  258. int oom_kill_disable;
  259. /* protect arrays of thresholds */
  260. struct mutex thresholds_lock;
  261. /* thresholds for memory usage. RCU-protected */
  262. struct mem_cgroup_thresholds thresholds;
  263. /* thresholds for mem+swap usage. RCU-protected */
  264. struct mem_cgroup_thresholds memsw_thresholds;
  265. /* For oom notifier event fd */
  266. struct list_head oom_notify;
  267. /*
  268. * Should we move charges of a task when a task is moved into this
  269. * mem_cgroup ? And what type of charges should we move ?
  270. */
  271. unsigned long move_charge_at_immigrate;
  272. /*
  273. * set > 0 if pages under this cgroup are moving to other cgroup.
  274. */
  275. atomic_t moving_account;
  276. /* taken only while moving_account > 0 */
  277. spinlock_t move_lock;
  278. struct task_struct *move_lock_task;
  279. unsigned long move_lock_flags;
  280. /*
  281. * percpu counter.
  282. */
  283. struct mem_cgroup_stat_cpu __percpu *stat;
  284. /*
  285. * used when a cpu is offlined or other synchronizations
  286. * See mem_cgroup_read_stat().
  287. */
  288. struct mem_cgroup_stat_cpu nocpu_base;
  289. spinlock_t pcp_counter_lock;
  290. #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_INET)
  291. struct cg_proto tcp_mem;
  292. #endif
  293. #if defined(CONFIG_MEMCG_KMEM)
  294. /* Index in the kmem_cache->memcg_params.memcg_caches array */
  295. int kmemcg_id;
  296. bool kmem_acct_activated;
  297. bool kmem_acct_active;
  298. #endif
  299. int last_scanned_node;
  300. #if MAX_NUMNODES > 1
  301. nodemask_t scan_nodes;
  302. atomic_t numainfo_events;
  303. atomic_t numainfo_updating;
  304. #endif
  305. /* List of events which userspace want to receive */
  306. struct list_head event_list;
  307. spinlock_t event_list_lock;
  308. struct mem_cgroup_per_node *nodeinfo[0];
  309. /* WARNING: nodeinfo must be the last member here */
  310. };
  311. #ifdef CONFIG_MEMCG_KMEM
  312. bool memcg_kmem_is_active(struct mem_cgroup *memcg)
  313. {
  314. return memcg->kmem_acct_active;
  315. }
  316. #endif
  317. /* Stuffs for move charges at task migration. */
  318. /*
  319. * Types of charges to be moved.
  320. */
  321. #define MOVE_ANON 0x1U
  322. #define MOVE_FILE 0x2U
  323. #define MOVE_MASK (MOVE_ANON | MOVE_FILE)
  324. /* "mc" and its members are protected by cgroup_mutex */
  325. static struct move_charge_struct {
  326. spinlock_t lock; /* for from, to */
  327. struct mem_cgroup *from;
  328. struct mem_cgroup *to;
  329. unsigned long flags;
  330. unsigned long precharge;
  331. unsigned long moved_charge;
  332. unsigned long moved_swap;
  333. struct task_struct *moving_task; /* a task moving charges */
  334. wait_queue_head_t waitq; /* a waitq for other context */
  335. } mc = {
  336. .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
  337. .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
  338. };
  339. /*
  340. * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
  341. * limit reclaim to prevent infinite loops, if they ever occur.
  342. */
  343. #define MEM_CGROUP_MAX_RECLAIM_LOOPS 100
  344. #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS 2
  345. enum charge_type {
  346. MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
  347. MEM_CGROUP_CHARGE_TYPE_ANON,
  348. MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
  349. MEM_CGROUP_CHARGE_TYPE_DROP, /* a page was unused swap cache */
  350. NR_CHARGE_TYPE,
  351. };
  352. /* for encoding cft->private value on file */
  353. enum res_type {
  354. _MEM,
  355. _MEMSWAP,
  356. _OOM_TYPE,
  357. _KMEM,
  358. };
  359. #define MEMFILE_PRIVATE(x, val) ((x) << 16 | (val))
  360. #define MEMFILE_TYPE(val) ((val) >> 16 & 0xffff)
  361. #define MEMFILE_ATTR(val) ((val) & 0xffff)
  362. /* Used for OOM nofiier */
  363. #define OOM_CONTROL (0)
  364. /*
  365. * The memcg_create_mutex will be held whenever a new cgroup is created.
  366. * As a consequence, any change that needs to protect against new child cgroups
  367. * appearing has to hold it as well.
  368. */
  369. static DEFINE_MUTEX(memcg_create_mutex);
  370. struct mem_cgroup *mem_cgroup_from_css(struct cgroup_subsys_state *s)
  371. {
  372. return s ? container_of(s, struct mem_cgroup, css) : NULL;
  373. }
  374. /* Some nice accessors for the vmpressure. */
  375. struct vmpressure *memcg_to_vmpressure(struct mem_cgroup *memcg)
  376. {
  377. if (!memcg)
  378. memcg = root_mem_cgroup;
  379. return &memcg->vmpressure;
  380. }
  381. struct cgroup_subsys_state *vmpressure_to_css(struct vmpressure *vmpr)
  382. {
  383. return &container_of(vmpr, struct mem_cgroup, vmpressure)->css;
  384. }
  385. static inline bool mem_cgroup_is_root(struct mem_cgroup *memcg)
  386. {
  387. return (memcg == root_mem_cgroup);
  388. }
  389. /*
  390. * We restrict the id in the range of [1, 65535], so it can fit into
  391. * an unsigned short.
  392. */
  393. #define MEM_CGROUP_ID_MAX USHRT_MAX
  394. static inline unsigned short mem_cgroup_id(struct mem_cgroup *memcg)
  395. {
  396. return memcg->css.id;
  397. }
  398. /*
  399. * A helper function to get mem_cgroup from ID. must be called under
  400. * rcu_read_lock(). The caller is responsible for calling
  401. * css_tryget_online() if the mem_cgroup is used for charging. (dropping
  402. * refcnt from swap can be called against removed memcg.)
  403. */
  404. static inline struct mem_cgroup *mem_cgroup_from_id(unsigned short id)
  405. {
  406. struct cgroup_subsys_state *css;
  407. css = css_from_id(id, &memory_cgrp_subsys);
  408. return mem_cgroup_from_css(css);
  409. }
  410. /* Writing them here to avoid exposing memcg's inner layout */
  411. #if defined(CONFIG_INET) && defined(CONFIG_MEMCG_KMEM)
  412. void sock_update_memcg(struct sock *sk)
  413. {
  414. if (mem_cgroup_sockets_enabled) {
  415. struct mem_cgroup *memcg;
  416. struct cg_proto *cg_proto;
  417. BUG_ON(!sk->sk_prot->proto_cgroup);
  418. /* Socket cloning can throw us here with sk_cgrp already
  419. * filled. It won't however, necessarily happen from
  420. * process context. So the test for root memcg given
  421. * the current task's memcg won't help us in this case.
  422. *
  423. * Respecting the original socket's memcg is a better
  424. * decision in this case.
  425. */
  426. if (sk->sk_cgrp) {
  427. BUG_ON(mem_cgroup_is_root(sk->sk_cgrp->memcg));
  428. css_get(&sk->sk_cgrp->memcg->css);
  429. return;
  430. }
  431. rcu_read_lock();
  432. memcg = mem_cgroup_from_task(current);
  433. cg_proto = sk->sk_prot->proto_cgroup(memcg);
  434. if (!mem_cgroup_is_root(memcg) &&
  435. memcg_proto_active(cg_proto) &&
  436. css_tryget_online(&memcg->css)) {
  437. sk->sk_cgrp = cg_proto;
  438. }
  439. rcu_read_unlock();
  440. }
  441. }
  442. EXPORT_SYMBOL(sock_update_memcg);
  443. void sock_release_memcg(struct sock *sk)
  444. {
  445. if (mem_cgroup_sockets_enabled && sk->sk_cgrp) {
  446. struct mem_cgroup *memcg;
  447. WARN_ON(!sk->sk_cgrp->memcg);
  448. memcg = sk->sk_cgrp->memcg;
  449. css_put(&sk->sk_cgrp->memcg->css);
  450. }
  451. }
  452. struct cg_proto *tcp_proto_cgroup(struct mem_cgroup *memcg)
  453. {
  454. if (!memcg || mem_cgroup_is_root(memcg))
  455. return NULL;
  456. return &memcg->tcp_mem;
  457. }
  458. EXPORT_SYMBOL(tcp_proto_cgroup);
  459. #endif
  460. #ifdef CONFIG_MEMCG_KMEM
  461. /*
  462. * This will be the memcg's index in each cache's ->memcg_params.memcg_caches.
  463. * The main reason for not using cgroup id for this:
  464. * this works better in sparse environments, where we have a lot of memcgs,
  465. * but only a few kmem-limited. Or also, if we have, for instance, 200
  466. * memcgs, and none but the 200th is kmem-limited, we'd have to have a
  467. * 200 entry array for that.
  468. *
  469. * The current size of the caches array is stored in memcg_nr_cache_ids. It
  470. * will double each time we have to increase it.
  471. */
  472. static DEFINE_IDA(memcg_cache_ida);
  473. int memcg_nr_cache_ids;
  474. /* Protects memcg_nr_cache_ids */
  475. static DECLARE_RWSEM(memcg_cache_ids_sem);
  476. void memcg_get_cache_ids(void)
  477. {
  478. down_read(&memcg_cache_ids_sem);
  479. }
  480. void memcg_put_cache_ids(void)
  481. {
  482. up_read(&memcg_cache_ids_sem);
  483. }
  484. /*
  485. * MIN_SIZE is different than 1, because we would like to avoid going through
  486. * the alloc/free process all the time. In a small machine, 4 kmem-limited
  487. * cgroups is a reasonable guess. In the future, it could be a parameter or
  488. * tunable, but that is strictly not necessary.
  489. *
  490. * MAX_SIZE should be as large as the number of cgrp_ids. Ideally, we could get
  491. * this constant directly from cgroup, but it is understandable that this is
  492. * better kept as an internal representation in cgroup.c. In any case, the
  493. * cgrp_id space is not getting any smaller, and we don't have to necessarily
  494. * increase ours as well if it increases.
  495. */
  496. #define MEMCG_CACHES_MIN_SIZE 4
  497. #define MEMCG_CACHES_MAX_SIZE MEM_CGROUP_ID_MAX
  498. /*
  499. * A lot of the calls to the cache allocation functions are expected to be
  500. * inlined by the compiler. Since the calls to memcg_kmem_get_cache are
  501. * conditional to this static branch, we'll have to allow modules that does
  502. * kmem_cache_alloc and the such to see this symbol as well
  503. */
  504. struct static_key memcg_kmem_enabled_key;
  505. EXPORT_SYMBOL(memcg_kmem_enabled_key);
  506. #endif /* CONFIG_MEMCG_KMEM */
  507. static struct mem_cgroup_per_zone *
  508. mem_cgroup_zone_zoneinfo(struct mem_cgroup *memcg, struct zone *zone)
  509. {
  510. int nid = zone_to_nid(zone);
  511. int zid = zone_idx(zone);
  512. return &memcg->nodeinfo[nid]->zoneinfo[zid];
  513. }
  514. struct cgroup_subsys_state *mem_cgroup_css(struct mem_cgroup *memcg)
  515. {
  516. return &memcg->css;
  517. }
  518. static struct mem_cgroup_per_zone *
  519. mem_cgroup_page_zoneinfo(struct mem_cgroup *memcg, struct page *page)
  520. {
  521. int nid = page_to_nid(page);
  522. int zid = page_zonenum(page);
  523. return &memcg->nodeinfo[nid]->zoneinfo[zid];
  524. }
  525. static struct mem_cgroup_tree_per_zone *
  526. soft_limit_tree_node_zone(int nid, int zid)
  527. {
  528. return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
  529. }
  530. static struct mem_cgroup_tree_per_zone *
  531. soft_limit_tree_from_page(struct page *page)
  532. {
  533. int nid = page_to_nid(page);
  534. int zid = page_zonenum(page);
  535. return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
  536. }
  537. static void __mem_cgroup_insert_exceeded(struct mem_cgroup_per_zone *mz,
  538. struct mem_cgroup_tree_per_zone *mctz,
  539. unsigned long new_usage_in_excess)
  540. {
  541. struct rb_node **p = &mctz->rb_root.rb_node;
  542. struct rb_node *parent = NULL;
  543. struct mem_cgroup_per_zone *mz_node;
  544. if (mz->on_tree)
  545. return;
  546. mz->usage_in_excess = new_usage_in_excess;
  547. if (!mz->usage_in_excess)
  548. return;
  549. while (*p) {
  550. parent = *p;
  551. mz_node = rb_entry(parent, struct mem_cgroup_per_zone,
  552. tree_node);
  553. if (mz->usage_in_excess < mz_node->usage_in_excess)
  554. p = &(*p)->rb_left;
  555. /*
  556. * We can't avoid mem cgroups that are over their soft
  557. * limit by the same amount
  558. */
  559. else if (mz->usage_in_excess >= mz_node->usage_in_excess)
  560. p = &(*p)->rb_right;
  561. }
  562. rb_link_node(&mz->tree_node, parent, p);
  563. rb_insert_color(&mz->tree_node, &mctz->rb_root);
  564. mz->on_tree = true;
  565. }
  566. static void __mem_cgroup_remove_exceeded(struct mem_cgroup_per_zone *mz,
  567. struct mem_cgroup_tree_per_zone *mctz)
  568. {
  569. if (!mz->on_tree)
  570. return;
  571. rb_erase(&mz->tree_node, &mctz->rb_root);
  572. mz->on_tree = false;
  573. }
  574. static void mem_cgroup_remove_exceeded(struct mem_cgroup_per_zone *mz,
  575. struct mem_cgroup_tree_per_zone *mctz)
  576. {
  577. unsigned long flags;
  578. spin_lock_irqsave(&mctz->lock, flags);
  579. __mem_cgroup_remove_exceeded(mz, mctz);
  580. spin_unlock_irqrestore(&mctz->lock, flags);
  581. }
  582. static unsigned long soft_limit_excess(struct mem_cgroup *memcg)
  583. {
  584. unsigned long nr_pages = page_counter_read(&memcg->memory);
  585. unsigned long soft_limit = READ_ONCE(memcg->soft_limit);
  586. unsigned long excess = 0;
  587. if (nr_pages > soft_limit)
  588. excess = nr_pages - soft_limit;
  589. return excess;
  590. }
  591. static void mem_cgroup_update_tree(struct mem_cgroup *memcg, struct page *page)
  592. {
  593. unsigned long excess;
  594. struct mem_cgroup_per_zone *mz;
  595. struct mem_cgroup_tree_per_zone *mctz;
  596. mctz = soft_limit_tree_from_page(page);
  597. /*
  598. * Necessary to update all ancestors when hierarchy is used.
  599. * because their event counter is not touched.
  600. */
  601. for (; memcg; memcg = parent_mem_cgroup(memcg)) {
  602. mz = mem_cgroup_page_zoneinfo(memcg, page);
  603. excess = soft_limit_excess(memcg);
  604. /*
  605. * We have to update the tree if mz is on RB-tree or
  606. * mem is over its softlimit.
  607. */
  608. if (excess || mz->on_tree) {
  609. unsigned long flags;
  610. spin_lock_irqsave(&mctz->lock, flags);
  611. /* if on-tree, remove it */
  612. if (mz->on_tree)
  613. __mem_cgroup_remove_exceeded(mz, mctz);
  614. /*
  615. * Insert again. mz->usage_in_excess will be updated.
  616. * If excess is 0, no tree ops.
  617. */
  618. __mem_cgroup_insert_exceeded(mz, mctz, excess);
  619. spin_unlock_irqrestore(&mctz->lock, flags);
  620. }
  621. }
  622. }
  623. static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
  624. {
  625. struct mem_cgroup_tree_per_zone *mctz;
  626. struct mem_cgroup_per_zone *mz;
  627. int nid, zid;
  628. for_each_node(nid) {
  629. for (zid = 0; zid < MAX_NR_ZONES; zid++) {
  630. mz = &memcg->nodeinfo[nid]->zoneinfo[zid];
  631. mctz = soft_limit_tree_node_zone(nid, zid);
  632. mem_cgroup_remove_exceeded(mz, mctz);
  633. }
  634. }
  635. }
  636. static struct mem_cgroup_per_zone *
  637. __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
  638. {
  639. struct rb_node *rightmost = NULL;
  640. struct mem_cgroup_per_zone *mz;
  641. retry:
  642. mz = NULL;
  643. rightmost = rb_last(&mctz->rb_root);
  644. if (!rightmost)
  645. goto done; /* Nothing to reclaim from */
  646. mz = rb_entry(rightmost, struct mem_cgroup_per_zone, tree_node);
  647. /*
  648. * Remove the node now but someone else can add it back,
  649. * we will to add it back at the end of reclaim to its correct
  650. * position in the tree.
  651. */
  652. __mem_cgroup_remove_exceeded(mz, mctz);
  653. if (!soft_limit_excess(mz->memcg) ||
  654. !css_tryget_online(&mz->memcg->css))
  655. goto retry;
  656. done:
  657. return mz;
  658. }
  659. static struct mem_cgroup_per_zone *
  660. mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
  661. {
  662. struct mem_cgroup_per_zone *mz;
  663. spin_lock_irq(&mctz->lock);
  664. mz = __mem_cgroup_largest_soft_limit_node(mctz);
  665. spin_unlock_irq(&mctz->lock);
  666. return mz;
  667. }
  668. /*
  669. * Implementation Note: reading percpu statistics for memcg.
  670. *
  671. * Both of vmstat[] and percpu_counter has threshold and do periodic
  672. * synchronization to implement "quick" read. There are trade-off between
  673. * reading cost and precision of value. Then, we may have a chance to implement
  674. * a periodic synchronizion of counter in memcg's counter.
  675. *
  676. * But this _read() function is used for user interface now. The user accounts
  677. * memory usage by memory cgroup and he _always_ requires exact value because
  678. * he accounts memory. Even if we provide quick-and-fuzzy read, we always
  679. * have to visit all online cpus and make sum. So, for now, unnecessary
  680. * synchronization is not implemented. (just implemented for cpu hotplug)
  681. *
  682. * If there are kernel internal actions which can make use of some not-exact
  683. * value, and reading all cpu value can be performance bottleneck in some
  684. * common workload, threashold and synchonization as vmstat[] should be
  685. * implemented.
  686. */
  687. static long mem_cgroup_read_stat(struct mem_cgroup *memcg,
  688. enum mem_cgroup_stat_index idx)
  689. {
  690. long val = 0;
  691. int cpu;
  692. get_online_cpus();
  693. for_each_online_cpu(cpu)
  694. val += per_cpu(memcg->stat->count[idx], cpu);
  695. #ifdef CONFIG_HOTPLUG_CPU
  696. spin_lock(&memcg->pcp_counter_lock);
  697. val += memcg->nocpu_base.count[idx];
  698. spin_unlock(&memcg->pcp_counter_lock);
  699. #endif
  700. put_online_cpus();
  701. return val;
  702. }
  703. static unsigned long mem_cgroup_read_events(struct mem_cgroup *memcg,
  704. enum mem_cgroup_events_index idx)
  705. {
  706. unsigned long val = 0;
  707. int cpu;
  708. get_online_cpus();
  709. for_each_online_cpu(cpu)
  710. val += per_cpu(memcg->stat->events[idx], cpu);
  711. #ifdef CONFIG_HOTPLUG_CPU
  712. spin_lock(&memcg->pcp_counter_lock);
  713. val += memcg->nocpu_base.events[idx];
  714. spin_unlock(&memcg->pcp_counter_lock);
  715. #endif
  716. put_online_cpus();
  717. return val;
  718. }
  719. static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
  720. struct page *page,
  721. int nr_pages)
  722. {
  723. /*
  724. * Here, RSS means 'mapped anon' and anon's SwapCache. Shmem/tmpfs is
  725. * counted as CACHE even if it's on ANON LRU.
  726. */
  727. if (PageAnon(page))
  728. __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_RSS],
  729. nr_pages);
  730. else
  731. __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_CACHE],
  732. nr_pages);
  733. if (PageTransHuge(page))
  734. __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_RSS_HUGE],
  735. nr_pages);
  736. /* pagein of a big page is an event. So, ignore page size */
  737. if (nr_pages > 0)
  738. __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGIN]);
  739. else {
  740. __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGOUT]);
  741. nr_pages = -nr_pages; /* for event */
  742. }
  743. __this_cpu_add(memcg->stat->nr_page_events, nr_pages);
  744. }
  745. unsigned long mem_cgroup_get_lru_size(struct lruvec *lruvec, enum lru_list lru)
  746. {
  747. struct mem_cgroup_per_zone *mz;
  748. mz = container_of(lruvec, struct mem_cgroup_per_zone, lruvec);
  749. return mz->lru_size[lru];
  750. }
  751. static unsigned long mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
  752. int nid,
  753. unsigned int lru_mask)
  754. {
  755. unsigned long nr = 0;
  756. int zid;
  757. VM_BUG_ON((unsigned)nid >= nr_node_ids);
  758. for (zid = 0; zid < MAX_NR_ZONES; zid++) {
  759. struct mem_cgroup_per_zone *mz;
  760. enum lru_list lru;
  761. for_each_lru(lru) {
  762. if (!(BIT(lru) & lru_mask))
  763. continue;
  764. mz = &memcg->nodeinfo[nid]->zoneinfo[zid];
  765. nr += mz->lru_size[lru];
  766. }
  767. }
  768. return nr;
  769. }
  770. static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
  771. unsigned int lru_mask)
  772. {
  773. unsigned long nr = 0;
  774. int nid;
  775. for_each_node_state(nid, N_MEMORY)
  776. nr += mem_cgroup_node_nr_lru_pages(memcg, nid, lru_mask);
  777. return nr;
  778. }
  779. static bool mem_cgroup_event_ratelimit(struct mem_cgroup *memcg,
  780. enum mem_cgroup_events_target target)
  781. {
  782. unsigned long val, next;
  783. val = __this_cpu_read(memcg->stat->nr_page_events);
  784. next = __this_cpu_read(memcg->stat->targets[target]);
  785. /* from time_after() in jiffies.h */
  786. if ((long)next - (long)val < 0) {
  787. switch (target) {
  788. case MEM_CGROUP_TARGET_THRESH:
  789. next = val + THRESHOLDS_EVENTS_TARGET;
  790. break;
  791. case MEM_CGROUP_TARGET_SOFTLIMIT:
  792. next = val + SOFTLIMIT_EVENTS_TARGET;
  793. break;
  794. case MEM_CGROUP_TARGET_NUMAINFO:
  795. next = val + NUMAINFO_EVENTS_TARGET;
  796. break;
  797. default:
  798. break;
  799. }
  800. __this_cpu_write(memcg->stat->targets[target], next);
  801. return true;
  802. }
  803. return false;
  804. }
  805. /*
  806. * Check events in order.
  807. *
  808. */
  809. static void memcg_check_events(struct mem_cgroup *memcg, struct page *page)
  810. {
  811. /* threshold event is triggered in finer grain than soft limit */
  812. if (unlikely(mem_cgroup_event_ratelimit(memcg,
  813. MEM_CGROUP_TARGET_THRESH))) {
  814. bool do_softlimit;
  815. bool do_numainfo __maybe_unused;
  816. do_softlimit = mem_cgroup_event_ratelimit(memcg,
  817. MEM_CGROUP_TARGET_SOFTLIMIT);
  818. #if MAX_NUMNODES > 1
  819. do_numainfo = mem_cgroup_event_ratelimit(memcg,
  820. MEM_CGROUP_TARGET_NUMAINFO);
  821. #endif
  822. mem_cgroup_threshold(memcg);
  823. if (unlikely(do_softlimit))
  824. mem_cgroup_update_tree(memcg, page);
  825. #if MAX_NUMNODES > 1
  826. if (unlikely(do_numainfo))
  827. atomic_inc(&memcg->numainfo_events);
  828. #endif
  829. }
  830. }
  831. struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
  832. {
  833. /*
  834. * mm_update_next_owner() may clear mm->owner to NULL
  835. * if it races with swapoff, page migration, etc.
  836. * So this can be called with p == NULL.
  837. */
  838. if (unlikely(!p))
  839. return NULL;
  840. return mem_cgroup_from_css(task_css(p, memory_cgrp_id));
  841. }
  842. static struct mem_cgroup *get_mem_cgroup_from_mm(struct mm_struct *mm)
  843. {
  844. struct mem_cgroup *memcg = NULL;
  845. rcu_read_lock();
  846. do {
  847. /*
  848. * Page cache insertions can happen withou an
  849. * actual mm context, e.g. during disk probing
  850. * on boot, loopback IO, acct() writes etc.
  851. */
  852. if (unlikely(!mm))
  853. memcg = root_mem_cgroup;
  854. else {
  855. memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
  856. if (unlikely(!memcg))
  857. memcg = root_mem_cgroup;
  858. }
  859. } while (!css_tryget_online(&memcg->css));
  860. rcu_read_unlock();
  861. return memcg;
  862. }
  863. /**
  864. * mem_cgroup_iter - iterate over memory cgroup hierarchy
  865. * @root: hierarchy root
  866. * @prev: previously returned memcg, NULL on first invocation
  867. * @reclaim: cookie for shared reclaim walks, NULL for full walks
  868. *
  869. * Returns references to children of the hierarchy below @root, or
  870. * @root itself, or %NULL after a full round-trip.
  871. *
  872. * Caller must pass the return value in @prev on subsequent
  873. * invocations for reference counting, or use mem_cgroup_iter_break()
  874. * to cancel a hierarchy walk before the round-trip is complete.
  875. *
  876. * Reclaimers can specify a zone and a priority level in @reclaim to
  877. * divide up the memcgs in the hierarchy among all concurrent
  878. * reclaimers operating on the same zone and priority.
  879. */
  880. struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
  881. struct mem_cgroup *prev,
  882. struct mem_cgroup_reclaim_cookie *reclaim)
  883. {
  884. struct reclaim_iter *uninitialized_var(iter);
  885. struct cgroup_subsys_state *css = NULL;
  886. struct mem_cgroup *memcg = NULL;
  887. struct mem_cgroup *pos = NULL;
  888. if (mem_cgroup_disabled())
  889. return NULL;
  890. if (!root)
  891. root = root_mem_cgroup;
  892. if (prev && !reclaim)
  893. pos = prev;
  894. if (!root->use_hierarchy && root != root_mem_cgroup) {
  895. if (prev)
  896. goto out;
  897. return root;
  898. }
  899. rcu_read_lock();
  900. if (reclaim) {
  901. struct mem_cgroup_per_zone *mz;
  902. mz = mem_cgroup_zone_zoneinfo(root, reclaim->zone);
  903. iter = &mz->iter[reclaim->priority];
  904. if (prev && reclaim->generation != iter->generation)
  905. goto out_unlock;
  906. do {
  907. pos = READ_ONCE(iter->position);
  908. /*
  909. * A racing update may change the position and
  910. * put the last reference, hence css_tryget(),
  911. * or retry to see the updated position.
  912. */
  913. } while (pos && !css_tryget(&pos->css));
  914. }
  915. if (pos)
  916. css = &pos->css;
  917. for (;;) {
  918. css = css_next_descendant_pre(css, &root->css);
  919. if (!css) {
  920. /*
  921. * Reclaimers share the hierarchy walk, and a
  922. * new one might jump in right at the end of
  923. * the hierarchy - make sure they see at least
  924. * one group and restart from the beginning.
  925. */
  926. if (!prev)
  927. continue;
  928. break;
  929. }
  930. /*
  931. * Verify the css and acquire a reference. The root
  932. * is provided by the caller, so we know it's alive
  933. * and kicking, and don't take an extra reference.
  934. */
  935. memcg = mem_cgroup_from_css(css);
  936. if (css == &root->css)
  937. break;
  938. if (css_tryget(css)) {
  939. /*
  940. * Make sure the memcg is initialized:
  941. * mem_cgroup_css_online() orders the the
  942. * initialization against setting the flag.
  943. */
  944. if (smp_load_acquire(&memcg->initialized))
  945. break;
  946. css_put(css);
  947. }
  948. memcg = NULL;
  949. }
  950. if (reclaim) {
  951. if (cmpxchg(&iter->position, pos, memcg) == pos) {
  952. if (memcg)
  953. css_get(&memcg->css);
  954. if (pos)
  955. css_put(&pos->css);
  956. }
  957. /*
  958. * pairs with css_tryget when dereferencing iter->position
  959. * above.
  960. */
  961. if (pos)
  962. css_put(&pos->css);
  963. if (!memcg)
  964. iter->generation++;
  965. else if (!prev)
  966. reclaim->generation = iter->generation;
  967. }
  968. out_unlock:
  969. rcu_read_unlock();
  970. out:
  971. if (prev && prev != root)
  972. css_put(&prev->css);
  973. return memcg;
  974. }
  975. /**
  976. * mem_cgroup_iter_break - abort a hierarchy walk prematurely
  977. * @root: hierarchy root
  978. * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
  979. */
  980. void mem_cgroup_iter_break(struct mem_cgroup *root,
  981. struct mem_cgroup *prev)
  982. {
  983. if (!root)
  984. root = root_mem_cgroup;
  985. if (prev && prev != root)
  986. css_put(&prev->css);
  987. }
  988. /*
  989. * Iteration constructs for visiting all cgroups (under a tree). If
  990. * loops are exited prematurely (break), mem_cgroup_iter_break() must
  991. * be used for reference counting.
  992. */
  993. #define for_each_mem_cgroup_tree(iter, root) \
  994. for (iter = mem_cgroup_iter(root, NULL, NULL); \
  995. iter != NULL; \
  996. iter = mem_cgroup_iter(root, iter, NULL))
  997. #define for_each_mem_cgroup(iter) \
  998. for (iter = mem_cgroup_iter(NULL, NULL, NULL); \
  999. iter != NULL; \
  1000. iter = mem_cgroup_iter(NULL, iter, NULL))
  1001. void __mem_cgroup_count_vm_event(struct mm_struct *mm, enum vm_event_item idx)
  1002. {
  1003. struct mem_cgroup *memcg;
  1004. rcu_read_lock();
  1005. memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
  1006. if (unlikely(!memcg))
  1007. goto out;
  1008. switch (idx) {
  1009. case PGFAULT:
  1010. this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGFAULT]);
  1011. break;
  1012. case PGMAJFAULT:
  1013. this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGMAJFAULT]);
  1014. break;
  1015. default:
  1016. BUG();
  1017. }
  1018. out:
  1019. rcu_read_unlock();
  1020. }
  1021. EXPORT_SYMBOL(__mem_cgroup_count_vm_event);
  1022. /**
  1023. * mem_cgroup_zone_lruvec - get the lru list vector for a zone and memcg
  1024. * @zone: zone of the wanted lruvec
  1025. * @memcg: memcg of the wanted lruvec
  1026. *
  1027. * Returns the lru list vector holding pages for the given @zone and
  1028. * @mem. This can be the global zone lruvec, if the memory controller
  1029. * is disabled.
  1030. */
  1031. struct lruvec *mem_cgroup_zone_lruvec(struct zone *zone,
  1032. struct mem_cgroup *memcg)
  1033. {
  1034. struct mem_cgroup_per_zone *mz;
  1035. struct lruvec *lruvec;
  1036. if (mem_cgroup_disabled()) {
  1037. lruvec = &zone->lruvec;
  1038. goto out;
  1039. }
  1040. mz = mem_cgroup_zone_zoneinfo(memcg, zone);
  1041. lruvec = &mz->lruvec;
  1042. out:
  1043. /*
  1044. * Since a node can be onlined after the mem_cgroup was created,
  1045. * we have to be prepared to initialize lruvec->zone here;
  1046. * and if offlined then reonlined, we need to reinitialize it.
  1047. */
  1048. if (unlikely(lruvec->zone != zone))
  1049. lruvec->zone = zone;
  1050. return lruvec;
  1051. }
  1052. /**
  1053. * mem_cgroup_page_lruvec - return lruvec for isolating/putting an LRU page
  1054. * @page: the page
  1055. * @zone: zone of the page
  1056. *
  1057. * This function is only safe when following the LRU page isolation
  1058. * and putback protocol: the LRU lock must be held, and the page must
  1059. * either be PageLRU() or the caller must have isolated/allocated it.
  1060. */
  1061. struct lruvec *mem_cgroup_page_lruvec(struct page *page, struct zone *zone)
  1062. {
  1063. struct mem_cgroup_per_zone *mz;
  1064. struct mem_cgroup *memcg;
  1065. struct lruvec *lruvec;
  1066. if (mem_cgroup_disabled()) {
  1067. lruvec = &zone->lruvec;
  1068. goto out;
  1069. }
  1070. memcg = page->mem_cgroup;
  1071. /*
  1072. * Swapcache readahead pages are added to the LRU - and
  1073. * possibly migrated - before they are charged.
  1074. */
  1075. if (!memcg)
  1076. memcg = root_mem_cgroup;
  1077. mz = mem_cgroup_page_zoneinfo(memcg, page);
  1078. lruvec = &mz->lruvec;
  1079. out:
  1080. /*
  1081. * Since a node can be onlined after the mem_cgroup was created,
  1082. * we have to be prepared to initialize lruvec->zone here;
  1083. * and if offlined then reonlined, we need to reinitialize it.
  1084. */
  1085. if (unlikely(lruvec->zone != zone))
  1086. lruvec->zone = zone;
  1087. return lruvec;
  1088. }
  1089. /**
  1090. * mem_cgroup_update_lru_size - account for adding or removing an lru page
  1091. * @lruvec: mem_cgroup per zone lru vector
  1092. * @lru: index of lru list the page is sitting on
  1093. * @nr_pages: positive when adding or negative when removing
  1094. *
  1095. * This function must be called when a page is added to or removed from an
  1096. * lru list.
  1097. */
  1098. void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
  1099. int nr_pages)
  1100. {
  1101. struct mem_cgroup_per_zone *mz;
  1102. unsigned long *lru_size;
  1103. if (mem_cgroup_disabled())
  1104. return;
  1105. mz = container_of(lruvec, struct mem_cgroup_per_zone, lruvec);
  1106. lru_size = mz->lru_size + lru;
  1107. *lru_size += nr_pages;
  1108. VM_BUG_ON((long)(*lru_size) < 0);
  1109. }
  1110. bool mem_cgroup_is_descendant(struct mem_cgroup *memcg, struct mem_cgroup *root)
  1111. {
  1112. if (root == memcg)
  1113. return true;
  1114. if (!root->use_hierarchy)
  1115. return false;
  1116. return cgroup_is_descendant(memcg->css.cgroup, root->css.cgroup);
  1117. }
  1118. bool task_in_mem_cgroup(struct task_struct *task, struct mem_cgroup *memcg)
  1119. {
  1120. struct mem_cgroup *task_memcg;
  1121. struct task_struct *p;
  1122. bool ret;
  1123. p = find_lock_task_mm(task);
  1124. if (p) {
  1125. task_memcg = get_mem_cgroup_from_mm(p->mm);
  1126. task_unlock(p);
  1127. } else {
  1128. /*
  1129. * All threads may have already detached their mm's, but the oom
  1130. * killer still needs to detect if they have already been oom
  1131. * killed to prevent needlessly killing additional tasks.
  1132. */
  1133. rcu_read_lock();
  1134. task_memcg = mem_cgroup_from_task(task);
  1135. css_get(&task_memcg->css);
  1136. rcu_read_unlock();
  1137. }
  1138. ret = mem_cgroup_is_descendant(task_memcg, memcg);
  1139. css_put(&task_memcg->css);
  1140. return ret;
  1141. }
  1142. int mem_cgroup_inactive_anon_is_low(struct lruvec *lruvec)
  1143. {
  1144. unsigned long inactive_ratio;
  1145. unsigned long inactive;
  1146. unsigned long active;
  1147. unsigned long gb;
  1148. inactive = mem_cgroup_get_lru_size(lruvec, LRU_INACTIVE_ANON);
  1149. active = mem_cgroup_get_lru_size(lruvec, LRU_ACTIVE_ANON);
  1150. gb = (inactive + active) >> (30 - PAGE_SHIFT);
  1151. if (gb)
  1152. inactive_ratio = int_sqrt(10 * gb);
  1153. else
  1154. inactive_ratio = 1;
  1155. return inactive * inactive_ratio < active;
  1156. }
  1157. bool mem_cgroup_lruvec_online(struct lruvec *lruvec)
  1158. {
  1159. struct mem_cgroup_per_zone *mz;
  1160. struct mem_cgroup *memcg;
  1161. if (mem_cgroup_disabled())
  1162. return true;
  1163. mz = container_of(lruvec, struct mem_cgroup_per_zone, lruvec);
  1164. memcg = mz->memcg;
  1165. return !!(memcg->css.flags & CSS_ONLINE);
  1166. }
  1167. #define mem_cgroup_from_counter(counter, member) \
  1168. container_of(counter, struct mem_cgroup, member)
  1169. /**
  1170. * mem_cgroup_margin - calculate chargeable space of a memory cgroup
  1171. * @memcg: the memory cgroup
  1172. *
  1173. * Returns the maximum amount of memory @mem can be charged with, in
  1174. * pages.
  1175. */
  1176. static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
  1177. {
  1178. unsigned long margin = 0;
  1179. unsigned long count;
  1180. unsigned long limit;
  1181. count = page_counter_read(&memcg->memory);
  1182. limit = READ_ONCE(memcg->memory.limit);
  1183. if (count < limit)
  1184. margin = limit - count;
  1185. if (do_swap_account) {
  1186. count = page_counter_read(&memcg->memsw);
  1187. limit = READ_ONCE(memcg->memsw.limit);
  1188. if (count <= limit)
  1189. margin = min(margin, limit - count);
  1190. }
  1191. return margin;
  1192. }
  1193. int mem_cgroup_swappiness(struct mem_cgroup *memcg)
  1194. {
  1195. /* root ? */
  1196. if (mem_cgroup_disabled() || !memcg->css.parent)
  1197. return vm_swappiness;
  1198. return memcg->swappiness;
  1199. }
  1200. /*
  1201. * A routine for checking "mem" is under move_account() or not.
  1202. *
  1203. * Checking a cgroup is mc.from or mc.to or under hierarchy of
  1204. * moving cgroups. This is for waiting at high-memory pressure
  1205. * caused by "move".
  1206. */
  1207. static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
  1208. {
  1209. struct mem_cgroup *from;
  1210. struct mem_cgroup *to;
  1211. bool ret = false;
  1212. /*
  1213. * Unlike task_move routines, we access mc.to, mc.from not under
  1214. * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
  1215. */
  1216. spin_lock(&mc.lock);
  1217. from = mc.from;
  1218. to = mc.to;
  1219. if (!from)
  1220. goto unlock;
  1221. ret = mem_cgroup_is_descendant(from, memcg) ||
  1222. mem_cgroup_is_descendant(to, memcg);
  1223. unlock:
  1224. spin_unlock(&mc.lock);
  1225. return ret;
  1226. }
  1227. static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
  1228. {
  1229. if (mc.moving_task && current != mc.moving_task) {
  1230. if (mem_cgroup_under_move(memcg)) {
  1231. DEFINE_WAIT(wait);
  1232. prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
  1233. /* moving charge context might have finished. */
  1234. if (mc.moving_task)
  1235. schedule();
  1236. finish_wait(&mc.waitq, &wait);
  1237. return true;
  1238. }
  1239. }
  1240. return false;
  1241. }
  1242. #define K(x) ((x) << (PAGE_SHIFT-10))
  1243. /**
  1244. * mem_cgroup_print_oom_info: Print OOM information relevant to memory controller.
  1245. * @memcg: The memory cgroup that went over limit
  1246. * @p: Task that is going to be killed
  1247. *
  1248. * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
  1249. * enabled
  1250. */
  1251. void mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p)
  1252. {
  1253. /* oom_info_lock ensures that parallel ooms do not interleave */
  1254. static DEFINE_MUTEX(oom_info_lock);
  1255. struct mem_cgroup *iter;
  1256. unsigned int i;
  1257. mutex_lock(&oom_info_lock);
  1258. rcu_read_lock();
  1259. if (p) {
  1260. pr_info("Task in ");
  1261. pr_cont_cgroup_path(task_cgroup(p, memory_cgrp_id));
  1262. pr_cont(" killed as a result of limit of ");
  1263. } else {
  1264. pr_info("Memory limit reached of cgroup ");
  1265. }
  1266. pr_cont_cgroup_path(memcg->css.cgroup);
  1267. pr_cont("\n");
  1268. rcu_read_unlock();
  1269. pr_info("memory: usage %llukB, limit %llukB, failcnt %lu\n",
  1270. K((u64)page_counter_read(&memcg->memory)),
  1271. K((u64)memcg->memory.limit), memcg->memory.failcnt);
  1272. pr_info("memory+swap: usage %llukB, limit %llukB, failcnt %lu\n",
  1273. K((u64)page_counter_read(&memcg->memsw)),
  1274. K((u64)memcg->memsw.limit), memcg->memsw.failcnt);
  1275. pr_info("kmem: usage %llukB, limit %llukB, failcnt %lu\n",
  1276. K((u64)page_counter_read(&memcg->kmem)),
  1277. K((u64)memcg->kmem.limit), memcg->kmem.failcnt);
  1278. for_each_mem_cgroup_tree(iter, memcg) {
  1279. pr_info("Memory cgroup stats for ");
  1280. pr_cont_cgroup_path(iter->css.cgroup);
  1281. pr_cont(":");
  1282. for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
  1283. if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
  1284. continue;
  1285. pr_cont(" %s:%ldKB", mem_cgroup_stat_names[i],
  1286. K(mem_cgroup_read_stat(iter, i)));
  1287. }
  1288. for (i = 0; i < NR_LRU_LISTS; i++)
  1289. pr_cont(" %s:%luKB", mem_cgroup_lru_names[i],
  1290. K(mem_cgroup_nr_lru_pages(iter, BIT(i))));
  1291. pr_cont("\n");
  1292. }
  1293. mutex_unlock(&oom_info_lock);
  1294. }
  1295. /*
  1296. * This function returns the number of memcg under hierarchy tree. Returns
  1297. * 1(self count) if no children.
  1298. */
  1299. static int mem_cgroup_count_children(struct mem_cgroup *memcg)
  1300. {
  1301. int num = 0;
  1302. struct mem_cgroup *iter;
  1303. for_each_mem_cgroup_tree(iter, memcg)
  1304. num++;
  1305. return num;
  1306. }
  1307. /*
  1308. * Return the memory (and swap, if configured) limit for a memcg.
  1309. */
  1310. static unsigned long mem_cgroup_get_limit(struct mem_cgroup *memcg)
  1311. {
  1312. unsigned long limit;
  1313. limit = memcg->memory.limit;
  1314. if (mem_cgroup_swappiness(memcg)) {
  1315. unsigned long memsw_limit;
  1316. memsw_limit = memcg->memsw.limit;
  1317. limit = min(limit + total_swap_pages, memsw_limit);
  1318. }
  1319. return limit;
  1320. }
  1321. static void mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
  1322. int order)
  1323. {
  1324. struct mem_cgroup *iter;
  1325. unsigned long chosen_points = 0;
  1326. unsigned long totalpages;
  1327. unsigned int points = 0;
  1328. struct task_struct *chosen = NULL;
  1329. mutex_lock(&oom_lock);
  1330. /*
  1331. * If current has a pending SIGKILL or is exiting, then automatically
  1332. * select it. The goal is to allow it to allocate so that it may
  1333. * quickly exit and free its memory.
  1334. */
  1335. if (fatal_signal_pending(current) || task_will_free_mem(current)) {
  1336. mark_oom_victim(current);
  1337. goto unlock;
  1338. }
  1339. check_panic_on_oom(CONSTRAINT_MEMCG, gfp_mask, order, NULL, memcg);
  1340. totalpages = mem_cgroup_get_limit(memcg) ? : 1;
  1341. for_each_mem_cgroup_tree(iter, memcg) {
  1342. struct css_task_iter it;
  1343. struct task_struct *task;
  1344. css_task_iter_start(&iter->css, &it);
  1345. while ((task = css_task_iter_next(&it))) {
  1346. switch (oom_scan_process_thread(task, totalpages, NULL,
  1347. false)) {
  1348. case OOM_SCAN_SELECT:
  1349. if (chosen)
  1350. put_task_struct(chosen);
  1351. chosen = task;
  1352. chosen_points = ULONG_MAX;
  1353. get_task_struct(chosen);
  1354. /* fall through */
  1355. case OOM_SCAN_CONTINUE:
  1356. continue;
  1357. case OOM_SCAN_ABORT:
  1358. css_task_iter_end(&it);
  1359. mem_cgroup_iter_break(memcg, iter);
  1360. if (chosen)
  1361. put_task_struct(chosen);
  1362. goto unlock;
  1363. case OOM_SCAN_OK:
  1364. break;
  1365. };
  1366. points = oom_badness(task, memcg, NULL, totalpages);
  1367. if (!points || points < chosen_points)
  1368. continue;
  1369. /* Prefer thread group leaders for display purposes */
  1370. if (points == chosen_points &&
  1371. thread_group_leader(chosen))
  1372. continue;
  1373. if (chosen)
  1374. put_task_struct(chosen);
  1375. chosen = task;
  1376. chosen_points = points;
  1377. get_task_struct(chosen);
  1378. }
  1379. css_task_iter_end(&it);
  1380. }
  1381. if (chosen) {
  1382. points = chosen_points * 1000 / totalpages;
  1383. oom_kill_process(chosen, gfp_mask, order, points, totalpages,
  1384. memcg, NULL, "Memory cgroup out of memory");
  1385. }
  1386. unlock:
  1387. mutex_unlock(&oom_lock);
  1388. }
  1389. #if MAX_NUMNODES > 1
  1390. /**
  1391. * test_mem_cgroup_node_reclaimable
  1392. * @memcg: the target memcg
  1393. * @nid: the node ID to be checked.
  1394. * @noswap : specify true here if the user wants flle only information.
  1395. *
  1396. * This function returns whether the specified memcg contains any
  1397. * reclaimable pages on a node. Returns true if there are any reclaimable
  1398. * pages in the node.
  1399. */
  1400. static bool test_mem_cgroup_node_reclaimable(struct mem_cgroup *memcg,
  1401. int nid, bool noswap)
  1402. {
  1403. if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_FILE))
  1404. return true;
  1405. if (noswap || !total_swap_pages)
  1406. return false;
  1407. if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_ANON))
  1408. return true;
  1409. return false;
  1410. }
  1411. /*
  1412. * Always updating the nodemask is not very good - even if we have an empty
  1413. * list or the wrong list here, we can start from some node and traverse all
  1414. * nodes based on the zonelist. So update the list loosely once per 10 secs.
  1415. *
  1416. */
  1417. static void mem_cgroup_may_update_nodemask(struct mem_cgroup *memcg)
  1418. {
  1419. int nid;
  1420. /*
  1421. * numainfo_events > 0 means there was at least NUMAINFO_EVENTS_TARGET
  1422. * pagein/pageout changes since the last update.
  1423. */
  1424. if (!atomic_read(&memcg->numainfo_events))
  1425. return;
  1426. if (atomic_inc_return(&memcg->numainfo_updating) > 1)
  1427. return;
  1428. /* make a nodemask where this memcg uses memory from */
  1429. memcg->scan_nodes = node_states[N_MEMORY];
  1430. for_each_node_mask(nid, node_states[N_MEMORY]) {
  1431. if (!test_mem_cgroup_node_reclaimable(memcg, nid, false))
  1432. node_clear(nid, memcg->scan_nodes);
  1433. }
  1434. atomic_set(&memcg->numainfo_events, 0);
  1435. atomic_set(&memcg->numainfo_updating, 0);
  1436. }
  1437. /*
  1438. * Selecting a node where we start reclaim from. Because what we need is just
  1439. * reducing usage counter, start from anywhere is O,K. Considering
  1440. * memory reclaim from current node, there are pros. and cons.
  1441. *
  1442. * Freeing memory from current node means freeing memory from a node which
  1443. * we'll use or we've used. So, it may make LRU bad. And if several threads
  1444. * hit limits, it will see a contention on a node. But freeing from remote
  1445. * node means more costs for memory reclaim because of memory latency.
  1446. *
  1447. * Now, we use round-robin. Better algorithm is welcomed.
  1448. */
  1449. int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
  1450. {
  1451. int node;
  1452. mem_cgroup_may_update_nodemask(memcg);
  1453. node = memcg->last_scanned_node;
  1454. node = next_node(node, memcg->scan_nodes);
  1455. if (node == MAX_NUMNODES)
  1456. node = first_node(memcg->scan_nodes);
  1457. /*
  1458. * We call this when we hit limit, not when pages are added to LRU.
  1459. * No LRU may hold pages because all pages are UNEVICTABLE or
  1460. * memcg is too small and all pages are not on LRU. In that case,
  1461. * we use curret node.
  1462. */
  1463. if (unlikely(node == MAX_NUMNODES))
  1464. node = numa_node_id();
  1465. memcg->last_scanned_node = node;
  1466. return node;
  1467. }
  1468. #else
  1469. int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
  1470. {
  1471. return 0;
  1472. }
  1473. #endif
  1474. static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg,
  1475. struct zone *zone,
  1476. gfp_t gfp_mask,
  1477. unsigned long *total_scanned)
  1478. {
  1479. struct mem_cgroup *victim = NULL;
  1480. int total = 0;
  1481. int loop = 0;
  1482. unsigned long excess;
  1483. unsigned long nr_scanned;
  1484. struct mem_cgroup_reclaim_cookie reclaim = {
  1485. .zone = zone,
  1486. .priority = 0,
  1487. };
  1488. excess = soft_limit_excess(root_memcg);
  1489. while (1) {
  1490. victim = mem_cgroup_iter(root_memcg, victim, &reclaim);
  1491. if (!victim) {
  1492. loop++;
  1493. if (loop >= 2) {
  1494. /*
  1495. * If we have not been able to reclaim
  1496. * anything, it might because there are
  1497. * no reclaimable pages under this hierarchy
  1498. */
  1499. if (!total)
  1500. break;
  1501. /*
  1502. * We want to do more targeted reclaim.
  1503. * excess >> 2 is not to excessive so as to
  1504. * reclaim too much, nor too less that we keep
  1505. * coming back to reclaim from this cgroup
  1506. */
  1507. if (total >= (excess >> 2) ||
  1508. (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS))
  1509. break;
  1510. }
  1511. continue;
  1512. }
  1513. total += mem_cgroup_shrink_node_zone(victim, gfp_mask, false,
  1514. zone, &nr_scanned);
  1515. *total_scanned += nr_scanned;
  1516. if (!soft_limit_excess(root_memcg))
  1517. break;
  1518. }
  1519. mem_cgroup_iter_break(root_memcg, victim);
  1520. return total;
  1521. }
  1522. #ifdef CONFIG_LOCKDEP
  1523. static struct lockdep_map memcg_oom_lock_dep_map = {
  1524. .name = "memcg_oom_lock",
  1525. };
  1526. #endif
  1527. static DEFINE_SPINLOCK(memcg_oom_lock);
  1528. /*
  1529. * Check OOM-Killer is already running under our hierarchy.
  1530. * If someone is running, return false.
  1531. */
  1532. static bool mem_cgroup_oom_trylock(struct mem_cgroup *memcg)
  1533. {
  1534. struct mem_cgroup *iter, *failed = NULL;
  1535. spin_lock(&memcg_oom_lock);
  1536. for_each_mem_cgroup_tree(iter, memcg) {
  1537. if (iter->oom_lock) {
  1538. /*
  1539. * this subtree of our hierarchy is already locked
  1540. * so we cannot give a lock.
  1541. */
  1542. failed = iter;
  1543. mem_cgroup_iter_break(memcg, iter);
  1544. break;
  1545. } else
  1546. iter->oom_lock = true;
  1547. }
  1548. if (failed) {
  1549. /*
  1550. * OK, we failed to lock the whole subtree so we have
  1551. * to clean up what we set up to the failing subtree
  1552. */
  1553. for_each_mem_cgroup_tree(iter, memcg) {
  1554. if (iter == failed) {
  1555. mem_cgroup_iter_break(memcg, iter);
  1556. break;
  1557. }
  1558. iter->oom_lock = false;
  1559. }
  1560. } else
  1561. mutex_acquire(&memcg_oom_lock_dep_map, 0, 1, _RET_IP_);
  1562. spin_unlock(&memcg_oom_lock);
  1563. return !failed;
  1564. }
  1565. static void mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
  1566. {
  1567. struct mem_cgroup *iter;
  1568. spin_lock(&memcg_oom_lock);
  1569. mutex_release(&memcg_oom_lock_dep_map, 1, _RET_IP_);
  1570. for_each_mem_cgroup_tree(iter, memcg)
  1571. iter->oom_lock = false;
  1572. spin_unlock(&memcg_oom_lock);
  1573. }
  1574. static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
  1575. {
  1576. struct mem_cgroup *iter;
  1577. for_each_mem_cgroup_tree(iter, memcg)
  1578. atomic_inc(&iter->under_oom);
  1579. }
  1580. static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
  1581. {
  1582. struct mem_cgroup *iter;
  1583. /*
  1584. * When a new child is created while the hierarchy is under oom,
  1585. * mem_cgroup_oom_lock() may not be called. We have to use
  1586. * atomic_add_unless() here.
  1587. */
  1588. for_each_mem_cgroup_tree(iter, memcg)
  1589. atomic_add_unless(&iter->under_oom, -1, 0);
  1590. }
  1591. static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
  1592. struct oom_wait_info {
  1593. struct mem_cgroup *memcg;
  1594. wait_queue_t wait;
  1595. };
  1596. static int memcg_oom_wake_function(wait_queue_t *wait,
  1597. unsigned mode, int sync, void *arg)
  1598. {
  1599. struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg;
  1600. struct mem_cgroup *oom_wait_memcg;
  1601. struct oom_wait_info *oom_wait_info;
  1602. oom_wait_info = container_of(wait, struct oom_wait_info, wait);
  1603. oom_wait_memcg = oom_wait_info->memcg;
  1604. if (!mem_cgroup_is_descendant(wake_memcg, oom_wait_memcg) &&
  1605. !mem_cgroup_is_descendant(oom_wait_memcg, wake_memcg))
  1606. return 0;
  1607. return autoremove_wake_function(wait, mode, sync, arg);
  1608. }
  1609. static void memcg_wakeup_oom(struct mem_cgroup *memcg)
  1610. {
  1611. atomic_inc(&memcg->oom_wakeups);
  1612. /* for filtering, pass "memcg" as argument. */
  1613. __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
  1614. }
  1615. static void memcg_oom_recover(struct mem_cgroup *memcg)
  1616. {
  1617. if (memcg && atomic_read(&memcg->under_oom))
  1618. memcg_wakeup_oom(memcg);
  1619. }
  1620. static void mem_cgroup_oom(struct mem_cgroup *memcg, gfp_t mask, int order)
  1621. {
  1622. if (!current->memcg_oom.may_oom)
  1623. return;
  1624. /*
  1625. * We are in the middle of the charge context here, so we
  1626. * don't want to block when potentially sitting on a callstack
  1627. * that holds all kinds of filesystem and mm locks.
  1628. *
  1629. * Also, the caller may handle a failed allocation gracefully
  1630. * (like optional page cache readahead) and so an OOM killer
  1631. * invocation might not even be necessary.
  1632. *
  1633. * That's why we don't do anything here except remember the
  1634. * OOM context and then deal with it at the end of the page
  1635. * fault when the stack is unwound, the locks are released,
  1636. * and when we know whether the fault was overall successful.
  1637. */
  1638. css_get(&memcg->css);
  1639. current->memcg_oom.memcg = memcg;
  1640. current->memcg_oom.gfp_mask = mask;
  1641. current->memcg_oom.order = order;
  1642. }
  1643. /**
  1644. * mem_cgroup_oom_synchronize - complete memcg OOM handling
  1645. * @handle: actually kill/wait or just clean up the OOM state
  1646. *
  1647. * This has to be called at the end of a page fault if the memcg OOM
  1648. * handler was enabled.
  1649. *
  1650. * Memcg supports userspace OOM handling where failed allocations must
  1651. * sleep on a waitqueue until the userspace task resolves the
  1652. * situation. Sleeping directly in the charge context with all kinds
  1653. * of locks held is not a good idea, instead we remember an OOM state
  1654. * in the task and mem_cgroup_oom_synchronize() has to be called at
  1655. * the end of the page fault to complete the OOM handling.
  1656. *
  1657. * Returns %true if an ongoing memcg OOM situation was detected and
  1658. * completed, %false otherwise.
  1659. */
  1660. bool mem_cgroup_oom_synchronize(bool handle)
  1661. {
  1662. struct mem_cgroup *memcg = current->memcg_oom.memcg;
  1663. struct oom_wait_info owait;
  1664. bool locked;
  1665. /* OOM is global, do not handle */
  1666. if (!memcg)
  1667. return false;
  1668. if (!handle || oom_killer_disabled)
  1669. goto cleanup;
  1670. owait.memcg = memcg;
  1671. owait.wait.flags = 0;
  1672. owait.wait.func = memcg_oom_wake_function;
  1673. owait.wait.private = current;
  1674. INIT_LIST_HEAD(&owait.wait.task_list);
  1675. prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
  1676. mem_cgroup_mark_under_oom(memcg);
  1677. locked = mem_cgroup_oom_trylock(memcg);
  1678. if (locked)
  1679. mem_cgroup_oom_notify(memcg);
  1680. if (locked && !memcg->oom_kill_disable) {
  1681. mem_cgroup_unmark_under_oom(memcg);
  1682. finish_wait(&memcg_oom_waitq, &owait.wait);
  1683. mem_cgroup_out_of_memory(memcg, current->memcg_oom.gfp_mask,
  1684. current->memcg_oom.order);
  1685. } else {
  1686. schedule();
  1687. mem_cgroup_unmark_under_oom(memcg);
  1688. finish_wait(&memcg_oom_waitq, &owait.wait);
  1689. }
  1690. if (locked) {
  1691. mem_cgroup_oom_unlock(memcg);
  1692. /*
  1693. * There is no guarantee that an OOM-lock contender
  1694. * sees the wakeups triggered by the OOM kill
  1695. * uncharges. Wake any sleepers explicitely.
  1696. */
  1697. memcg_oom_recover(memcg);
  1698. }
  1699. cleanup:
  1700. current->memcg_oom.memcg = NULL;
  1701. css_put(&memcg->css);
  1702. return true;
  1703. }
  1704. /**
  1705. * mem_cgroup_begin_page_stat - begin a page state statistics transaction
  1706. * @page: page that is going to change accounted state
  1707. *
  1708. * This function must mark the beginning of an accounted page state
  1709. * change to prevent double accounting when the page is concurrently
  1710. * being moved to another memcg:
  1711. *
  1712. * memcg = mem_cgroup_begin_page_stat(page);
  1713. * if (TestClearPageState(page))
  1714. * mem_cgroup_update_page_stat(memcg, state, -1);
  1715. * mem_cgroup_end_page_stat(memcg);
  1716. */
  1717. struct mem_cgroup *mem_cgroup_begin_page_stat(struct page *page)
  1718. {
  1719. struct mem_cgroup *memcg;
  1720. unsigned long flags;
  1721. /*
  1722. * The RCU lock is held throughout the transaction. The fast
  1723. * path can get away without acquiring the memcg->move_lock
  1724. * because page moving starts with an RCU grace period.
  1725. *
  1726. * The RCU lock also protects the memcg from being freed when
  1727. * the page state that is going to change is the only thing
  1728. * preventing the page from being uncharged.
  1729. * E.g. end-writeback clearing PageWriteback(), which allows
  1730. * migration to go ahead and uncharge the page before the
  1731. * account transaction might be complete.
  1732. */
  1733. rcu_read_lock();
  1734. if (mem_cgroup_disabled())
  1735. return NULL;
  1736. again:
  1737. memcg = page->mem_cgroup;
  1738. if (unlikely(!memcg))
  1739. return NULL;
  1740. if (atomic_read(&memcg->moving_account) <= 0)
  1741. return memcg;
  1742. spin_lock_irqsave(&memcg->move_lock, flags);
  1743. if (memcg != page->mem_cgroup) {
  1744. spin_unlock_irqrestore(&memcg->move_lock, flags);
  1745. goto again;
  1746. }
  1747. /*
  1748. * When charge migration first begins, we can have locked and
  1749. * unlocked page stat updates happening concurrently. Track
  1750. * the task who has the lock for mem_cgroup_end_page_stat().
  1751. */
  1752. memcg->move_lock_task = current;
  1753. memcg->move_lock_flags = flags;
  1754. return memcg;
  1755. }
  1756. /**
  1757. * mem_cgroup_end_page_stat - finish a page state statistics transaction
  1758. * @memcg: the memcg that was accounted against
  1759. */
  1760. void mem_cgroup_end_page_stat(struct mem_cgroup *memcg)
  1761. {
  1762. if (memcg && memcg->move_lock_task == current) {
  1763. unsigned long flags = memcg->move_lock_flags;
  1764. memcg->move_lock_task = NULL;
  1765. memcg->move_lock_flags = 0;
  1766. spin_unlock_irqrestore(&memcg->move_lock, flags);
  1767. }
  1768. rcu_read_unlock();
  1769. }
  1770. /**
  1771. * mem_cgroup_update_page_stat - update page state statistics
  1772. * @memcg: memcg to account against
  1773. * @idx: page state item to account
  1774. * @val: number of pages (positive or negative)
  1775. *
  1776. * See mem_cgroup_begin_page_stat() for locking requirements.
  1777. */
  1778. void mem_cgroup_update_page_stat(struct mem_cgroup *memcg,
  1779. enum mem_cgroup_stat_index idx, int val)
  1780. {
  1781. VM_BUG_ON(!rcu_read_lock_held());
  1782. if (memcg)
  1783. this_cpu_add(memcg->stat->count[idx], val);
  1784. }
  1785. /*
  1786. * size of first charge trial. "32" comes from vmscan.c's magic value.
  1787. * TODO: maybe necessary to use big numbers in big irons.
  1788. */
  1789. #define CHARGE_BATCH 32U
  1790. struct memcg_stock_pcp {
  1791. struct mem_cgroup *cached; /* this never be root cgroup */
  1792. unsigned int nr_pages;
  1793. struct work_struct work;
  1794. unsigned long flags;
  1795. #define FLUSHING_CACHED_CHARGE 0
  1796. };
  1797. static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
  1798. static DEFINE_MUTEX(percpu_charge_mutex);
  1799. /**
  1800. * consume_stock: Try to consume stocked charge on this cpu.
  1801. * @memcg: memcg to consume from.
  1802. * @nr_pages: how many pages to charge.
  1803. *
  1804. * The charges will only happen if @memcg matches the current cpu's memcg
  1805. * stock, and at least @nr_pages are available in that stock. Failure to
  1806. * service an allocation will refill the stock.
  1807. *
  1808. * returns true if successful, false otherwise.
  1809. */
  1810. static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
  1811. {
  1812. struct memcg_stock_pcp *stock;
  1813. bool ret = false;
  1814. if (nr_pages > CHARGE_BATCH)
  1815. return ret;
  1816. stock = &get_cpu_var(memcg_stock);
  1817. if (memcg == stock->cached && stock->nr_pages >= nr_pages) {
  1818. stock->nr_pages -= nr_pages;
  1819. ret = true;
  1820. }
  1821. put_cpu_var(memcg_stock);
  1822. return ret;
  1823. }
  1824. /*
  1825. * Returns stocks cached in percpu and reset cached information.
  1826. */
  1827. static void drain_stock(struct memcg_stock_pcp *stock)
  1828. {
  1829. struct mem_cgroup *old = stock->cached;
  1830. if (stock->nr_pages) {
  1831. page_counter_uncharge(&old->memory, stock->nr_pages);
  1832. if (do_swap_account)
  1833. page_counter_uncharge(&old->memsw, stock->nr_pages);
  1834. css_put_many(&old->css, stock->nr_pages);
  1835. stock->nr_pages = 0;
  1836. }
  1837. stock->cached = NULL;
  1838. }
  1839. /*
  1840. * This must be called under preempt disabled or must be called by
  1841. * a thread which is pinned to local cpu.
  1842. */
  1843. static void drain_local_stock(struct work_struct *dummy)
  1844. {
  1845. struct memcg_stock_pcp *stock = this_cpu_ptr(&memcg_stock);
  1846. drain_stock(stock);
  1847. clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
  1848. }
  1849. /*
  1850. * Cache charges(val) to local per_cpu area.
  1851. * This will be consumed by consume_stock() function, later.
  1852. */
  1853. static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
  1854. {
  1855. struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock);
  1856. if (stock->cached != memcg) { /* reset if necessary */
  1857. drain_stock(stock);
  1858. stock->cached = memcg;
  1859. }
  1860. stock->nr_pages += nr_pages;
  1861. put_cpu_var(memcg_stock);
  1862. }
  1863. /*
  1864. * Drains all per-CPU charge caches for given root_memcg resp. subtree
  1865. * of the hierarchy under it.
  1866. */
  1867. static void drain_all_stock(struct mem_cgroup *root_memcg)
  1868. {
  1869. int cpu, curcpu;
  1870. /* If someone's already draining, avoid adding running more workers. */
  1871. if (!mutex_trylock(&percpu_charge_mutex))
  1872. return;
  1873. /* Notify other cpus that system-wide "drain" is running */
  1874. get_online_cpus();
  1875. curcpu = get_cpu();
  1876. for_each_online_cpu(cpu) {
  1877. struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
  1878. struct mem_cgroup *memcg;
  1879. memcg = stock->cached;
  1880. if (!memcg || !stock->nr_pages)
  1881. continue;
  1882. if (!mem_cgroup_is_descendant(memcg, root_memcg))
  1883. continue;
  1884. if (!test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
  1885. if (cpu == curcpu)
  1886. drain_local_stock(&stock->work);
  1887. else
  1888. schedule_work_on(cpu, &stock->work);
  1889. }
  1890. }
  1891. put_cpu();
  1892. put_online_cpus();
  1893. mutex_unlock(&percpu_charge_mutex);
  1894. }
  1895. /*
  1896. * This function drains percpu counter value from DEAD cpu and
  1897. * move it to local cpu. Note that this function can be preempted.
  1898. */
  1899. static void mem_cgroup_drain_pcp_counter(struct mem_cgroup *memcg, int cpu)
  1900. {
  1901. int i;
  1902. spin_lock(&memcg->pcp_counter_lock);
  1903. for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
  1904. long x = per_cpu(memcg->stat->count[i], cpu);
  1905. per_cpu(memcg->stat->count[i], cpu) = 0;
  1906. memcg->nocpu_base.count[i] += x;
  1907. }
  1908. for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
  1909. unsigned long x = per_cpu(memcg->stat->events[i], cpu);
  1910. per_cpu(memcg->stat->events[i], cpu) = 0;
  1911. memcg->nocpu_base.events[i] += x;
  1912. }
  1913. spin_unlock(&memcg->pcp_counter_lock);
  1914. }
  1915. static int memcg_cpu_hotplug_callback(struct notifier_block *nb,
  1916. unsigned long action,
  1917. void *hcpu)
  1918. {
  1919. int cpu = (unsigned long)hcpu;
  1920. struct memcg_stock_pcp *stock;
  1921. struct mem_cgroup *iter;
  1922. if (action == CPU_ONLINE)
  1923. return NOTIFY_OK;
  1924. if (action != CPU_DEAD && action != CPU_DEAD_FROZEN)
  1925. return NOTIFY_OK;
  1926. for_each_mem_cgroup(iter)
  1927. mem_cgroup_drain_pcp_counter(iter, cpu);
  1928. stock = &per_cpu(memcg_stock, cpu);
  1929. drain_stock(stock);
  1930. return NOTIFY_OK;
  1931. }
  1932. static int try_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
  1933. unsigned int nr_pages)
  1934. {
  1935. unsigned int batch = max(CHARGE_BATCH, nr_pages);
  1936. int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
  1937. struct mem_cgroup *mem_over_limit;
  1938. struct page_counter *counter;
  1939. unsigned long nr_reclaimed;
  1940. bool may_swap = true;
  1941. bool drained = false;
  1942. int ret = 0;
  1943. if (mem_cgroup_is_root(memcg))
  1944. goto done;
  1945. retry:
  1946. if (consume_stock(memcg, nr_pages))
  1947. goto done;
  1948. if (!do_swap_account ||
  1949. !page_counter_try_charge(&memcg->memsw, batch, &counter)) {
  1950. if (!page_counter_try_charge(&memcg->memory, batch, &counter))
  1951. goto done_restock;
  1952. if (do_swap_account)
  1953. page_counter_uncharge(&memcg->memsw, batch);
  1954. mem_over_limit = mem_cgroup_from_counter(counter, memory);
  1955. } else {
  1956. mem_over_limit = mem_cgroup_from_counter(counter, memsw);
  1957. may_swap = false;
  1958. }
  1959. if (batch > nr_pages) {
  1960. batch = nr_pages;
  1961. goto retry;
  1962. }
  1963. /*
  1964. * Unlike in global OOM situations, memcg is not in a physical
  1965. * memory shortage. Allow dying and OOM-killed tasks to
  1966. * bypass the last charges so that they can exit quickly and
  1967. * free their memory.
  1968. */
  1969. if (unlikely(test_thread_flag(TIF_MEMDIE) ||
  1970. fatal_signal_pending(current) ||
  1971. current->flags & PF_EXITING))
  1972. goto bypass;
  1973. if (unlikely(task_in_memcg_oom(current)))
  1974. goto nomem;
  1975. if (!(gfp_mask & __GFP_WAIT))
  1976. goto nomem;
  1977. mem_cgroup_events(mem_over_limit, MEMCG_MAX, 1);
  1978. nr_reclaimed = try_to_free_mem_cgroup_pages(mem_over_limit, nr_pages,
  1979. gfp_mask, may_swap);
  1980. if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
  1981. goto retry;
  1982. if (!drained) {
  1983. drain_all_stock(mem_over_limit);
  1984. drained = true;
  1985. goto retry;
  1986. }
  1987. if (gfp_mask & __GFP_NORETRY)
  1988. goto nomem;
  1989. /*
  1990. * Even though the limit is exceeded at this point, reclaim
  1991. * may have been able to free some pages. Retry the charge
  1992. * before killing the task.
  1993. *
  1994. * Only for regular pages, though: huge pages are rather
  1995. * unlikely to succeed so close to the limit, and we fall back
  1996. * to regular pages anyway in case of failure.
  1997. */
  1998. if (nr_reclaimed && nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER))
  1999. goto retry;
  2000. /*
  2001. * At task move, charge accounts can be doubly counted. So, it's
  2002. * better to wait until the end of task_move if something is going on.
  2003. */
  2004. if (mem_cgroup_wait_acct_move(mem_over_limit))
  2005. goto retry;
  2006. if (nr_retries--)
  2007. goto retry;
  2008. if (gfp_mask & __GFP_NOFAIL)
  2009. goto bypass;
  2010. if (fatal_signal_pending(current))
  2011. goto bypass;
  2012. mem_cgroup_events(mem_over_limit, MEMCG_OOM, 1);
  2013. mem_cgroup_oom(mem_over_limit, gfp_mask, get_order(nr_pages));
  2014. nomem:
  2015. if (!(gfp_mask & __GFP_NOFAIL))
  2016. return -ENOMEM;
  2017. bypass:
  2018. return -EINTR;
  2019. done_restock:
  2020. css_get_many(&memcg->css, batch);
  2021. if (batch > nr_pages)
  2022. refill_stock(memcg, batch - nr_pages);
  2023. if (!(gfp_mask & __GFP_WAIT))
  2024. goto done;
  2025. /*
  2026. * If the hierarchy is above the normal consumption range,
  2027. * make the charging task trim their excess contribution.
  2028. */
  2029. do {
  2030. if (page_counter_read(&memcg->memory) <= memcg->high)
  2031. continue;
  2032. mem_cgroup_events(memcg, MEMCG_HIGH, 1);
  2033. try_to_free_mem_cgroup_pages(memcg, nr_pages, gfp_mask, true);
  2034. } while ((memcg = parent_mem_cgroup(memcg)));
  2035. done:
  2036. return ret;
  2037. }
  2038. static void cancel_charge(struct mem_cgroup *memcg, unsigned int nr_pages)
  2039. {
  2040. if (mem_cgroup_is_root(memcg))
  2041. return;
  2042. page_counter_uncharge(&memcg->memory, nr_pages);
  2043. if (do_swap_account)
  2044. page_counter_uncharge(&memcg->memsw, nr_pages);
  2045. css_put_many(&memcg->css, nr_pages);
  2046. }
  2047. /*
  2048. * try_get_mem_cgroup_from_page - look up page's memcg association
  2049. * @page: the page
  2050. *
  2051. * Look up, get a css reference, and return the memcg that owns @page.
  2052. *
  2053. * The page must be locked to prevent racing with swap-in and page
  2054. * cache charges. If coming from an unlocked page table, the caller
  2055. * must ensure the page is on the LRU or this can race with charging.
  2056. */
  2057. struct mem_cgroup *try_get_mem_cgroup_from_page(struct page *page)
  2058. {
  2059. struct mem_cgroup *memcg;
  2060. unsigned short id;
  2061. swp_entry_t ent;
  2062. VM_BUG_ON_PAGE(!PageLocked(page), page);
  2063. memcg = page->mem_cgroup;
  2064. if (memcg) {
  2065. if (!css_tryget_online(&memcg->css))
  2066. memcg = NULL;
  2067. } else if (PageSwapCache(page)) {
  2068. ent.val = page_private(page);
  2069. id = lookup_swap_cgroup_id(ent);
  2070. rcu_read_lock();
  2071. memcg = mem_cgroup_from_id(id);
  2072. if (memcg && !css_tryget_online(&memcg->css))
  2073. memcg = NULL;
  2074. rcu_read_unlock();
  2075. }
  2076. return memcg;
  2077. }
  2078. static void lock_page_lru(struct page *page, int *isolated)
  2079. {
  2080. struct zone *zone = page_zone(page);
  2081. spin_lock_irq(&zone->lru_lock);
  2082. if (PageLRU(page)) {
  2083. struct lruvec *lruvec;
  2084. lruvec = mem_cgroup_page_lruvec(page, zone);
  2085. ClearPageLRU(page);
  2086. del_page_from_lru_list(page, lruvec, page_lru(page));
  2087. *isolated = 1;
  2088. } else
  2089. *isolated = 0;
  2090. }
  2091. static void unlock_page_lru(struct page *page, int isolated)
  2092. {
  2093. struct zone *zone = page_zone(page);
  2094. if (isolated) {
  2095. struct lruvec *lruvec;
  2096. lruvec = mem_cgroup_page_lruvec(page, zone);
  2097. VM_BUG_ON_PAGE(PageLRU(page), page);
  2098. SetPageLRU(page);
  2099. add_page_to_lru_list(page, lruvec, page_lru(page));
  2100. }
  2101. spin_unlock_irq(&zone->lru_lock);
  2102. }
  2103. static void commit_charge(struct page *page, struct mem_cgroup *memcg,
  2104. bool lrucare)
  2105. {
  2106. int isolated;
  2107. VM_BUG_ON_PAGE(page->mem_cgroup, page);
  2108. /*
  2109. * In some cases, SwapCache and FUSE(splice_buf->radixtree), the page
  2110. * may already be on some other mem_cgroup's LRU. Take care of it.
  2111. */
  2112. if (lrucare)
  2113. lock_page_lru(page, &isolated);
  2114. /*
  2115. * Nobody should be changing or seriously looking at
  2116. * page->mem_cgroup at this point:
  2117. *
  2118. * - the page is uncharged
  2119. *
  2120. * - the page is off-LRU
  2121. *
  2122. * - an anonymous fault has exclusive page access, except for
  2123. * a locked page table
  2124. *
  2125. * - a page cache insertion, a swapin fault, or a migration
  2126. * have the page locked
  2127. */
  2128. page->mem_cgroup = memcg;
  2129. if (lrucare)
  2130. unlock_page_lru(page, isolated);
  2131. }
  2132. #ifdef CONFIG_MEMCG_KMEM
  2133. int memcg_charge_kmem(struct mem_cgroup *memcg, gfp_t gfp,
  2134. unsigned long nr_pages)
  2135. {
  2136. struct page_counter *counter;
  2137. int ret = 0;
  2138. ret = page_counter_try_charge(&memcg->kmem, nr_pages, &counter);
  2139. if (ret < 0)
  2140. return ret;
  2141. ret = try_charge(memcg, gfp, nr_pages);
  2142. if (ret == -EINTR) {
  2143. /*
  2144. * try_charge() chose to bypass to root due to OOM kill or
  2145. * fatal signal. Since our only options are to either fail
  2146. * the allocation or charge it to this cgroup, do it as a
  2147. * temporary condition. But we can't fail. From a kmem/slab
  2148. * perspective, the cache has already been selected, by
  2149. * mem_cgroup_kmem_get_cache(), so it is too late to change
  2150. * our minds.
  2151. *
  2152. * This condition will only trigger if the task entered
  2153. * memcg_charge_kmem in a sane state, but was OOM-killed
  2154. * during try_charge() above. Tasks that were already dying
  2155. * when the allocation triggers should have been already
  2156. * directed to the root cgroup in memcontrol.h
  2157. */
  2158. page_counter_charge(&memcg->memory, nr_pages);
  2159. if (do_swap_account)
  2160. page_counter_charge(&memcg->memsw, nr_pages);
  2161. css_get_many(&memcg->css, nr_pages);
  2162. ret = 0;
  2163. } else if (ret)
  2164. page_counter_uncharge(&memcg->kmem, nr_pages);
  2165. return ret;
  2166. }
  2167. void memcg_uncharge_kmem(struct mem_cgroup *memcg, unsigned long nr_pages)
  2168. {
  2169. page_counter_uncharge(&memcg->memory, nr_pages);
  2170. if (do_swap_account)
  2171. page_counter_uncharge(&memcg->memsw, nr_pages);
  2172. page_counter_uncharge(&memcg->kmem, nr_pages);
  2173. css_put_many(&memcg->css, nr_pages);
  2174. }
  2175. /*
  2176. * helper for acessing a memcg's index. It will be used as an index in the
  2177. * child cache array in kmem_cache, and also to derive its name. This function
  2178. * will return -1 when this is not a kmem-limited memcg.
  2179. */
  2180. int memcg_cache_id(struct mem_cgroup *memcg)
  2181. {
  2182. return memcg ? memcg->kmemcg_id : -1;
  2183. }
  2184. static int memcg_alloc_cache_id(void)
  2185. {
  2186. int id, size;
  2187. int err;
  2188. id = ida_simple_get(&memcg_cache_ida,
  2189. 0, MEMCG_CACHES_MAX_SIZE, GFP_KERNEL);
  2190. if (id < 0)
  2191. return id;
  2192. if (id < memcg_nr_cache_ids)
  2193. return id;
  2194. /*
  2195. * There's no space for the new id in memcg_caches arrays,
  2196. * so we have to grow them.
  2197. */
  2198. down_write(&memcg_cache_ids_sem);
  2199. size = 2 * (id + 1);
  2200. if (size < MEMCG_CACHES_MIN_SIZE)
  2201. size = MEMCG_CACHES_MIN_SIZE;
  2202. else if (size > MEMCG_CACHES_MAX_SIZE)
  2203. size = MEMCG_CACHES_MAX_SIZE;
  2204. err = memcg_update_all_caches(size);
  2205. if (!err)
  2206. err = memcg_update_all_list_lrus(size);
  2207. if (!err)
  2208. memcg_nr_cache_ids = size;
  2209. up_write(&memcg_cache_ids_sem);
  2210. if (err) {
  2211. ida_simple_remove(&memcg_cache_ida, id);
  2212. return err;
  2213. }
  2214. return id;
  2215. }
  2216. static void memcg_free_cache_id(int id)
  2217. {
  2218. ida_simple_remove(&memcg_cache_ida, id);
  2219. }
  2220. struct memcg_kmem_cache_create_work {
  2221. struct mem_cgroup *memcg;
  2222. struct kmem_cache *cachep;
  2223. struct work_struct work;
  2224. };
  2225. static void memcg_kmem_cache_create_func(struct work_struct *w)
  2226. {
  2227. struct memcg_kmem_cache_create_work *cw =
  2228. container_of(w, struct memcg_kmem_cache_create_work, work);
  2229. struct mem_cgroup *memcg = cw->memcg;
  2230. struct kmem_cache *cachep = cw->cachep;
  2231. memcg_create_kmem_cache(memcg, cachep);
  2232. css_put(&memcg->css);
  2233. kfree(cw);
  2234. }
  2235. /*
  2236. * Enqueue the creation of a per-memcg kmem_cache.
  2237. */
  2238. static void __memcg_schedule_kmem_cache_create(struct mem_cgroup *memcg,
  2239. struct kmem_cache *cachep)
  2240. {
  2241. struct memcg_kmem_cache_create_work *cw;
  2242. cw = kmalloc(sizeof(*cw), GFP_NOWAIT);
  2243. if (!cw)
  2244. return;
  2245. css_get(&memcg->css);
  2246. cw->memcg = memcg;
  2247. cw->cachep = cachep;
  2248. INIT_WORK(&cw->work, memcg_kmem_cache_create_func);
  2249. schedule_work(&cw->work);
  2250. }
  2251. static void memcg_schedule_kmem_cache_create(struct mem_cgroup *memcg,
  2252. struct kmem_cache *cachep)
  2253. {
  2254. /*
  2255. * We need to stop accounting when we kmalloc, because if the
  2256. * corresponding kmalloc cache is not yet created, the first allocation
  2257. * in __memcg_schedule_kmem_cache_create will recurse.
  2258. *
  2259. * However, it is better to enclose the whole function. Depending on
  2260. * the debugging options enabled, INIT_WORK(), for instance, can
  2261. * trigger an allocation. This too, will make us recurse. Because at
  2262. * this point we can't allow ourselves back into memcg_kmem_get_cache,
  2263. * the safest choice is to do it like this, wrapping the whole function.
  2264. */
  2265. current->memcg_kmem_skip_account = 1;
  2266. __memcg_schedule_kmem_cache_create(memcg, cachep);
  2267. current->memcg_kmem_skip_account = 0;
  2268. }
  2269. /*
  2270. * Return the kmem_cache we're supposed to use for a slab allocation.
  2271. * We try to use the current memcg's version of the cache.
  2272. *
  2273. * If the cache does not exist yet, if we are the first user of it,
  2274. * we either create it immediately, if possible, or create it asynchronously
  2275. * in a workqueue.
  2276. * In the latter case, we will let the current allocation go through with
  2277. * the original cache.
  2278. *
  2279. * Can't be called in interrupt context or from kernel threads.
  2280. * This function needs to be called with rcu_read_lock() held.
  2281. */
  2282. struct kmem_cache *__memcg_kmem_get_cache(struct kmem_cache *cachep)
  2283. {
  2284. struct mem_cgroup *memcg;
  2285. struct kmem_cache *memcg_cachep;
  2286. int kmemcg_id;
  2287. VM_BUG_ON(!is_root_cache(cachep));
  2288. if (current->memcg_kmem_skip_account)
  2289. return cachep;
  2290. memcg = get_mem_cgroup_from_mm(current->mm);
  2291. kmemcg_id = READ_ONCE(memcg->kmemcg_id);
  2292. if (kmemcg_id < 0)
  2293. goto out;
  2294. memcg_cachep = cache_from_memcg_idx(cachep, kmemcg_id);
  2295. if (likely(memcg_cachep))
  2296. return memcg_cachep;
  2297. /*
  2298. * If we are in a safe context (can wait, and not in interrupt
  2299. * context), we could be be predictable and return right away.
  2300. * This would guarantee that the allocation being performed
  2301. * already belongs in the new cache.
  2302. *
  2303. * However, there are some clashes that can arrive from locking.
  2304. * For instance, because we acquire the slab_mutex while doing
  2305. * memcg_create_kmem_cache, this means no further allocation
  2306. * could happen with the slab_mutex held. So it's better to
  2307. * defer everything.
  2308. */
  2309. memcg_schedule_kmem_cache_create(memcg, cachep);
  2310. out:
  2311. css_put(&memcg->css);
  2312. return cachep;
  2313. }
  2314. void __memcg_kmem_put_cache(struct kmem_cache *cachep)
  2315. {
  2316. if (!is_root_cache(cachep))
  2317. css_put(&cachep->memcg_params.memcg->css);
  2318. }
  2319. /*
  2320. * We need to verify if the allocation against current->mm->owner's memcg is
  2321. * possible for the given order. But the page is not allocated yet, so we'll
  2322. * need a further commit step to do the final arrangements.
  2323. *
  2324. * It is possible for the task to switch cgroups in this mean time, so at
  2325. * commit time, we can't rely on task conversion any longer. We'll then use
  2326. * the handle argument to return to the caller which cgroup we should commit
  2327. * against. We could also return the memcg directly and avoid the pointer
  2328. * passing, but a boolean return value gives better semantics considering
  2329. * the compiled-out case as well.
  2330. *
  2331. * Returning true means the allocation is possible.
  2332. */
  2333. bool
  2334. __memcg_kmem_newpage_charge(gfp_t gfp, struct mem_cgroup **_memcg, int order)
  2335. {
  2336. struct mem_cgroup *memcg;
  2337. int ret;
  2338. *_memcg = NULL;
  2339. memcg = get_mem_cgroup_from_mm(current->mm);
  2340. if (!memcg_kmem_is_active(memcg)) {
  2341. css_put(&memcg->css);
  2342. return true;
  2343. }
  2344. ret = memcg_charge_kmem(memcg, gfp, 1 << order);
  2345. if (!ret)
  2346. *_memcg = memcg;
  2347. css_put(&memcg->css);
  2348. return (ret == 0);
  2349. }
  2350. void __memcg_kmem_commit_charge(struct page *page, struct mem_cgroup *memcg,
  2351. int order)
  2352. {
  2353. VM_BUG_ON(mem_cgroup_is_root(memcg));
  2354. /* The page allocation failed. Revert */
  2355. if (!page) {
  2356. memcg_uncharge_kmem(memcg, 1 << order);
  2357. return;
  2358. }
  2359. page->mem_cgroup = memcg;
  2360. }
  2361. void __memcg_kmem_uncharge_pages(struct page *page, int order)
  2362. {
  2363. struct mem_cgroup *memcg = page->mem_cgroup;
  2364. if (!memcg)
  2365. return;
  2366. VM_BUG_ON_PAGE(mem_cgroup_is_root(memcg), page);
  2367. memcg_uncharge_kmem(memcg, 1 << order);
  2368. page->mem_cgroup = NULL;
  2369. }
  2370. struct mem_cgroup *__mem_cgroup_from_kmem(void *ptr)
  2371. {
  2372. struct mem_cgroup *memcg = NULL;
  2373. struct kmem_cache *cachep;
  2374. struct page *page;
  2375. page = virt_to_head_page(ptr);
  2376. if (PageSlab(page)) {
  2377. cachep = page->slab_cache;
  2378. if (!is_root_cache(cachep))
  2379. memcg = cachep->memcg_params.memcg;
  2380. } else
  2381. /* page allocated by alloc_kmem_pages */
  2382. memcg = page->mem_cgroup;
  2383. return memcg;
  2384. }
  2385. #endif /* CONFIG_MEMCG_KMEM */
  2386. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  2387. /*
  2388. * Because tail pages are not marked as "used", set it. We're under
  2389. * zone->lru_lock, 'splitting on pmd' and compound_lock.
  2390. * charge/uncharge will be never happen and move_account() is done under
  2391. * compound_lock(), so we don't have to take care of races.
  2392. */
  2393. void mem_cgroup_split_huge_fixup(struct page *head)
  2394. {
  2395. int i;
  2396. if (mem_cgroup_disabled())
  2397. return;
  2398. for (i = 1; i < HPAGE_PMD_NR; i++)
  2399. head[i].mem_cgroup = head->mem_cgroup;
  2400. __this_cpu_sub(head->mem_cgroup->stat->count[MEM_CGROUP_STAT_RSS_HUGE],
  2401. HPAGE_PMD_NR);
  2402. }
  2403. #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
  2404. #ifdef CONFIG_MEMCG_SWAP
  2405. static void mem_cgroup_swap_statistics(struct mem_cgroup *memcg,
  2406. bool charge)
  2407. {
  2408. int val = (charge) ? 1 : -1;
  2409. this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_SWAP], val);
  2410. }
  2411. /**
  2412. * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
  2413. * @entry: swap entry to be moved
  2414. * @from: mem_cgroup which the entry is moved from
  2415. * @to: mem_cgroup which the entry is moved to
  2416. *
  2417. * It succeeds only when the swap_cgroup's record for this entry is the same
  2418. * as the mem_cgroup's id of @from.
  2419. *
  2420. * Returns 0 on success, -EINVAL on failure.
  2421. *
  2422. * The caller must have charged to @to, IOW, called page_counter_charge() about
  2423. * both res and memsw, and called css_get().
  2424. */
  2425. static int mem_cgroup_move_swap_account(swp_entry_t entry,
  2426. struct mem_cgroup *from, struct mem_cgroup *to)
  2427. {
  2428. unsigned short old_id, new_id;
  2429. old_id = mem_cgroup_id(from);
  2430. new_id = mem_cgroup_id(to);
  2431. if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
  2432. mem_cgroup_swap_statistics(from, false);
  2433. mem_cgroup_swap_statistics(to, true);
  2434. return 0;
  2435. }
  2436. return -EINVAL;
  2437. }
  2438. #else
  2439. static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
  2440. struct mem_cgroup *from, struct mem_cgroup *to)
  2441. {
  2442. return -EINVAL;
  2443. }
  2444. #endif
  2445. static DEFINE_MUTEX(memcg_limit_mutex);
  2446. static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
  2447. unsigned long limit)
  2448. {
  2449. unsigned long curusage;
  2450. unsigned long oldusage;
  2451. bool enlarge = false;
  2452. int retry_count;
  2453. int ret;
  2454. /*
  2455. * For keeping hierarchical_reclaim simple, how long we should retry
  2456. * is depends on callers. We set our retry-count to be function
  2457. * of # of children which we should visit in this loop.
  2458. */
  2459. retry_count = MEM_CGROUP_RECLAIM_RETRIES *
  2460. mem_cgroup_count_children(memcg);
  2461. oldusage = page_counter_read(&memcg->memory);
  2462. do {
  2463. if (signal_pending(current)) {
  2464. ret = -EINTR;
  2465. break;
  2466. }
  2467. mutex_lock(&memcg_limit_mutex);
  2468. if (limit > memcg->memsw.limit) {
  2469. mutex_unlock(&memcg_limit_mutex);
  2470. ret = -EINVAL;
  2471. break;
  2472. }
  2473. if (limit > memcg->memory.limit)
  2474. enlarge = true;
  2475. ret = page_counter_limit(&memcg->memory, limit);
  2476. mutex_unlock(&memcg_limit_mutex);
  2477. if (!ret)
  2478. break;
  2479. try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL, true);
  2480. curusage = page_counter_read(&memcg->memory);
  2481. /* Usage is reduced ? */
  2482. if (curusage >= oldusage)
  2483. retry_count--;
  2484. else
  2485. oldusage = curusage;
  2486. } while (retry_count);
  2487. if (!ret && enlarge)
  2488. memcg_oom_recover(memcg);
  2489. return ret;
  2490. }
  2491. static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
  2492. unsigned long limit)
  2493. {
  2494. unsigned long curusage;
  2495. unsigned long oldusage;
  2496. bool enlarge = false;
  2497. int retry_count;
  2498. int ret;
  2499. /* see mem_cgroup_resize_res_limit */
  2500. retry_count = MEM_CGROUP_RECLAIM_RETRIES *
  2501. mem_cgroup_count_children(memcg);
  2502. oldusage = page_counter_read(&memcg->memsw);
  2503. do {
  2504. if (signal_pending(current)) {
  2505. ret = -EINTR;
  2506. break;
  2507. }
  2508. mutex_lock(&memcg_limit_mutex);
  2509. if (limit < memcg->memory.limit) {
  2510. mutex_unlock(&memcg_limit_mutex);
  2511. ret = -EINVAL;
  2512. break;
  2513. }
  2514. if (limit > memcg->memsw.limit)
  2515. enlarge = true;
  2516. ret = page_counter_limit(&memcg->memsw, limit);
  2517. mutex_unlock(&memcg_limit_mutex);
  2518. if (!ret)
  2519. break;
  2520. try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL, false);
  2521. curusage = page_counter_read(&memcg->memsw);
  2522. /* Usage is reduced ? */
  2523. if (curusage >= oldusage)
  2524. retry_count--;
  2525. else
  2526. oldusage = curusage;
  2527. } while (retry_count);
  2528. if (!ret && enlarge)
  2529. memcg_oom_recover(memcg);
  2530. return ret;
  2531. }
  2532. unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
  2533. gfp_t gfp_mask,
  2534. unsigned long *total_scanned)
  2535. {
  2536. unsigned long nr_reclaimed = 0;
  2537. struct mem_cgroup_per_zone *mz, *next_mz = NULL;
  2538. unsigned long reclaimed;
  2539. int loop = 0;
  2540. struct mem_cgroup_tree_per_zone *mctz;
  2541. unsigned long excess;
  2542. unsigned long nr_scanned;
  2543. if (order > 0)
  2544. return 0;
  2545. mctz = soft_limit_tree_node_zone(zone_to_nid(zone), zone_idx(zone));
  2546. /*
  2547. * This loop can run a while, specially if mem_cgroup's continuously
  2548. * keep exceeding their soft limit and putting the system under
  2549. * pressure
  2550. */
  2551. do {
  2552. if (next_mz)
  2553. mz = next_mz;
  2554. else
  2555. mz = mem_cgroup_largest_soft_limit_node(mctz);
  2556. if (!mz)
  2557. break;
  2558. nr_scanned = 0;
  2559. reclaimed = mem_cgroup_soft_reclaim(mz->memcg, zone,
  2560. gfp_mask, &nr_scanned);
  2561. nr_reclaimed += reclaimed;
  2562. *total_scanned += nr_scanned;
  2563. spin_lock_irq(&mctz->lock);
  2564. __mem_cgroup_remove_exceeded(mz, mctz);
  2565. /*
  2566. * If we failed to reclaim anything from this memory cgroup
  2567. * it is time to move on to the next cgroup
  2568. */
  2569. next_mz = NULL;
  2570. if (!reclaimed)
  2571. next_mz = __mem_cgroup_largest_soft_limit_node(mctz);
  2572. excess = soft_limit_excess(mz->memcg);
  2573. /*
  2574. * One school of thought says that we should not add
  2575. * back the node to the tree if reclaim returns 0.
  2576. * But our reclaim could return 0, simply because due
  2577. * to priority we are exposing a smaller subset of
  2578. * memory to reclaim from. Consider this as a longer
  2579. * term TODO.
  2580. */
  2581. /* If excess == 0, no tree ops */
  2582. __mem_cgroup_insert_exceeded(mz, mctz, excess);
  2583. spin_unlock_irq(&mctz->lock);
  2584. css_put(&mz->memcg->css);
  2585. loop++;
  2586. /*
  2587. * Could not reclaim anything and there are no more
  2588. * mem cgroups to try or we seem to be looping without
  2589. * reclaiming anything.
  2590. */
  2591. if (!nr_reclaimed &&
  2592. (next_mz == NULL ||
  2593. loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
  2594. break;
  2595. } while (!nr_reclaimed);
  2596. if (next_mz)
  2597. css_put(&next_mz->memcg->css);
  2598. return nr_reclaimed;
  2599. }
  2600. /*
  2601. * Test whether @memcg has children, dead or alive. Note that this
  2602. * function doesn't care whether @memcg has use_hierarchy enabled and
  2603. * returns %true if there are child csses according to the cgroup
  2604. * hierarchy. Testing use_hierarchy is the caller's responsiblity.
  2605. */
  2606. static inline bool memcg_has_children(struct mem_cgroup *memcg)
  2607. {
  2608. bool ret;
  2609. /*
  2610. * The lock does not prevent addition or deletion of children, but
  2611. * it prevents a new child from being initialized based on this
  2612. * parent in css_online(), so it's enough to decide whether
  2613. * hierarchically inherited attributes can still be changed or not.
  2614. */
  2615. lockdep_assert_held(&memcg_create_mutex);
  2616. rcu_read_lock();
  2617. ret = css_next_child(NULL, &memcg->css);
  2618. rcu_read_unlock();
  2619. return ret;
  2620. }
  2621. /*
  2622. * Reclaims as many pages from the given memcg as possible and moves
  2623. * the rest to the parent.
  2624. *
  2625. * Caller is responsible for holding css reference for memcg.
  2626. */
  2627. static int mem_cgroup_force_empty(struct mem_cgroup *memcg)
  2628. {
  2629. int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
  2630. /* we call try-to-free pages for make this cgroup empty */
  2631. lru_add_drain_all();
  2632. /* try to free all pages in this cgroup */
  2633. while (nr_retries && page_counter_read(&memcg->memory)) {
  2634. int progress;
  2635. if (signal_pending(current))
  2636. return -EINTR;
  2637. progress = try_to_free_mem_cgroup_pages(memcg, 1,
  2638. GFP_KERNEL, true);
  2639. if (!progress) {
  2640. nr_retries--;
  2641. /* maybe some writeback is necessary */
  2642. congestion_wait(BLK_RW_ASYNC, HZ/10);
  2643. }
  2644. }
  2645. return 0;
  2646. }
  2647. static ssize_t mem_cgroup_force_empty_write(struct kernfs_open_file *of,
  2648. char *buf, size_t nbytes,
  2649. loff_t off)
  2650. {
  2651. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  2652. if (mem_cgroup_is_root(memcg))
  2653. return -EINVAL;
  2654. return mem_cgroup_force_empty(memcg) ?: nbytes;
  2655. }
  2656. static u64 mem_cgroup_hierarchy_read(struct cgroup_subsys_state *css,
  2657. struct cftype *cft)
  2658. {
  2659. return mem_cgroup_from_css(css)->use_hierarchy;
  2660. }
  2661. static int mem_cgroup_hierarchy_write(struct cgroup_subsys_state *css,
  2662. struct cftype *cft, u64 val)
  2663. {
  2664. int retval = 0;
  2665. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  2666. struct mem_cgroup *parent_memcg = mem_cgroup_from_css(memcg->css.parent);
  2667. mutex_lock(&memcg_create_mutex);
  2668. if (memcg->use_hierarchy == val)
  2669. goto out;
  2670. /*
  2671. * If parent's use_hierarchy is set, we can't make any modifications
  2672. * in the child subtrees. If it is unset, then the change can
  2673. * occur, provided the current cgroup has no children.
  2674. *
  2675. * For the root cgroup, parent_mem is NULL, we allow value to be
  2676. * set if there are no children.
  2677. */
  2678. if ((!parent_memcg || !parent_memcg->use_hierarchy) &&
  2679. (val == 1 || val == 0)) {
  2680. if (!memcg_has_children(memcg))
  2681. memcg->use_hierarchy = val;
  2682. else
  2683. retval = -EBUSY;
  2684. } else
  2685. retval = -EINVAL;
  2686. out:
  2687. mutex_unlock(&memcg_create_mutex);
  2688. return retval;
  2689. }
  2690. static unsigned long tree_stat(struct mem_cgroup *memcg,
  2691. enum mem_cgroup_stat_index idx)
  2692. {
  2693. struct mem_cgroup *iter;
  2694. long val = 0;
  2695. /* Per-cpu values can be negative, use a signed accumulator */
  2696. for_each_mem_cgroup_tree(iter, memcg)
  2697. val += mem_cgroup_read_stat(iter, idx);
  2698. if (val < 0) /* race ? */
  2699. val = 0;
  2700. return val;
  2701. }
  2702. static inline u64 mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
  2703. {
  2704. u64 val;
  2705. if (mem_cgroup_is_root(memcg)) {
  2706. val = tree_stat(memcg, MEM_CGROUP_STAT_CACHE);
  2707. val += tree_stat(memcg, MEM_CGROUP_STAT_RSS);
  2708. if (swap)
  2709. val += tree_stat(memcg, MEM_CGROUP_STAT_SWAP);
  2710. } else {
  2711. if (!swap)
  2712. val = page_counter_read(&memcg->memory);
  2713. else
  2714. val = page_counter_read(&memcg->memsw);
  2715. }
  2716. return val << PAGE_SHIFT;
  2717. }
  2718. enum {
  2719. RES_USAGE,
  2720. RES_LIMIT,
  2721. RES_MAX_USAGE,
  2722. RES_FAILCNT,
  2723. RES_SOFT_LIMIT,
  2724. };
  2725. static u64 mem_cgroup_read_u64(struct cgroup_subsys_state *css,
  2726. struct cftype *cft)
  2727. {
  2728. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  2729. struct page_counter *counter;
  2730. switch (MEMFILE_TYPE(cft->private)) {
  2731. case _MEM:
  2732. counter = &memcg->memory;
  2733. break;
  2734. case _MEMSWAP:
  2735. counter = &memcg->memsw;
  2736. break;
  2737. case _KMEM:
  2738. counter = &memcg->kmem;
  2739. break;
  2740. default:
  2741. BUG();
  2742. }
  2743. switch (MEMFILE_ATTR(cft->private)) {
  2744. case RES_USAGE:
  2745. if (counter == &memcg->memory)
  2746. return mem_cgroup_usage(memcg, false);
  2747. if (counter == &memcg->memsw)
  2748. return mem_cgroup_usage(memcg, true);
  2749. return (u64)page_counter_read(counter) * PAGE_SIZE;
  2750. case RES_LIMIT:
  2751. return (u64)counter->limit * PAGE_SIZE;
  2752. case RES_MAX_USAGE:
  2753. return (u64)counter->watermark * PAGE_SIZE;
  2754. case RES_FAILCNT:
  2755. return counter->failcnt;
  2756. case RES_SOFT_LIMIT:
  2757. return (u64)memcg->soft_limit * PAGE_SIZE;
  2758. default:
  2759. BUG();
  2760. }
  2761. }
  2762. #ifdef CONFIG_MEMCG_KMEM
  2763. static int memcg_activate_kmem(struct mem_cgroup *memcg,
  2764. unsigned long nr_pages)
  2765. {
  2766. int err = 0;
  2767. int memcg_id;
  2768. BUG_ON(memcg->kmemcg_id >= 0);
  2769. BUG_ON(memcg->kmem_acct_activated);
  2770. BUG_ON(memcg->kmem_acct_active);
  2771. /*
  2772. * For simplicity, we won't allow this to be disabled. It also can't
  2773. * be changed if the cgroup has children already, or if tasks had
  2774. * already joined.
  2775. *
  2776. * If tasks join before we set the limit, a person looking at
  2777. * kmem.usage_in_bytes will have no way to determine when it took
  2778. * place, which makes the value quite meaningless.
  2779. *
  2780. * After it first became limited, changes in the value of the limit are
  2781. * of course permitted.
  2782. */
  2783. mutex_lock(&memcg_create_mutex);
  2784. if (cgroup_has_tasks(memcg->css.cgroup) ||
  2785. (memcg->use_hierarchy && memcg_has_children(memcg)))
  2786. err = -EBUSY;
  2787. mutex_unlock(&memcg_create_mutex);
  2788. if (err)
  2789. goto out;
  2790. memcg_id = memcg_alloc_cache_id();
  2791. if (memcg_id < 0) {
  2792. err = memcg_id;
  2793. goto out;
  2794. }
  2795. /*
  2796. * We couldn't have accounted to this cgroup, because it hasn't got
  2797. * activated yet, so this should succeed.
  2798. */
  2799. err = page_counter_limit(&memcg->kmem, nr_pages);
  2800. VM_BUG_ON(err);
  2801. static_key_slow_inc(&memcg_kmem_enabled_key);
  2802. /*
  2803. * A memory cgroup is considered kmem-active as soon as it gets
  2804. * kmemcg_id. Setting the id after enabling static branching will
  2805. * guarantee no one starts accounting before all call sites are
  2806. * patched.
  2807. */
  2808. memcg->kmemcg_id = memcg_id;
  2809. memcg->kmem_acct_activated = true;
  2810. memcg->kmem_acct_active = true;
  2811. out:
  2812. return err;
  2813. }
  2814. static int memcg_update_kmem_limit(struct mem_cgroup *memcg,
  2815. unsigned long limit)
  2816. {
  2817. int ret;
  2818. mutex_lock(&memcg_limit_mutex);
  2819. if (!memcg_kmem_is_active(memcg))
  2820. ret = memcg_activate_kmem(memcg, limit);
  2821. else
  2822. ret = page_counter_limit(&memcg->kmem, limit);
  2823. mutex_unlock(&memcg_limit_mutex);
  2824. return ret;
  2825. }
  2826. static int memcg_propagate_kmem(struct mem_cgroup *memcg)
  2827. {
  2828. int ret = 0;
  2829. struct mem_cgroup *parent = parent_mem_cgroup(memcg);
  2830. if (!parent)
  2831. return 0;
  2832. mutex_lock(&memcg_limit_mutex);
  2833. /*
  2834. * If the parent cgroup is not kmem-active now, it cannot be activated
  2835. * after this point, because it has at least one child already.
  2836. */
  2837. if (memcg_kmem_is_active(parent))
  2838. ret = memcg_activate_kmem(memcg, PAGE_COUNTER_MAX);
  2839. mutex_unlock(&memcg_limit_mutex);
  2840. return ret;
  2841. }
  2842. #else
  2843. static int memcg_update_kmem_limit(struct mem_cgroup *memcg,
  2844. unsigned long limit)
  2845. {
  2846. return -EINVAL;
  2847. }
  2848. #endif /* CONFIG_MEMCG_KMEM */
  2849. /*
  2850. * The user of this function is...
  2851. * RES_LIMIT.
  2852. */
  2853. static ssize_t mem_cgroup_write(struct kernfs_open_file *of,
  2854. char *buf, size_t nbytes, loff_t off)
  2855. {
  2856. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  2857. unsigned long nr_pages;
  2858. int ret;
  2859. buf = strstrip(buf);
  2860. ret = page_counter_memparse(buf, "-1", &nr_pages);
  2861. if (ret)
  2862. return ret;
  2863. switch (MEMFILE_ATTR(of_cft(of)->private)) {
  2864. case RES_LIMIT:
  2865. if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
  2866. ret = -EINVAL;
  2867. break;
  2868. }
  2869. switch (MEMFILE_TYPE(of_cft(of)->private)) {
  2870. case _MEM:
  2871. ret = mem_cgroup_resize_limit(memcg, nr_pages);
  2872. break;
  2873. case _MEMSWAP:
  2874. ret = mem_cgroup_resize_memsw_limit(memcg, nr_pages);
  2875. break;
  2876. case _KMEM:
  2877. ret = memcg_update_kmem_limit(memcg, nr_pages);
  2878. break;
  2879. }
  2880. break;
  2881. case RES_SOFT_LIMIT:
  2882. memcg->soft_limit = nr_pages;
  2883. ret = 0;
  2884. break;
  2885. }
  2886. return ret ?: nbytes;
  2887. }
  2888. static ssize_t mem_cgroup_reset(struct kernfs_open_file *of, char *buf,
  2889. size_t nbytes, loff_t off)
  2890. {
  2891. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  2892. struct page_counter *counter;
  2893. switch (MEMFILE_TYPE(of_cft(of)->private)) {
  2894. case _MEM:
  2895. counter = &memcg->memory;
  2896. break;
  2897. case _MEMSWAP:
  2898. counter = &memcg->memsw;
  2899. break;
  2900. case _KMEM:
  2901. counter = &memcg->kmem;
  2902. break;
  2903. default:
  2904. BUG();
  2905. }
  2906. switch (MEMFILE_ATTR(of_cft(of)->private)) {
  2907. case RES_MAX_USAGE:
  2908. page_counter_reset_watermark(counter);
  2909. break;
  2910. case RES_FAILCNT:
  2911. counter->failcnt = 0;
  2912. break;
  2913. default:
  2914. BUG();
  2915. }
  2916. return nbytes;
  2917. }
  2918. static u64 mem_cgroup_move_charge_read(struct cgroup_subsys_state *css,
  2919. struct cftype *cft)
  2920. {
  2921. return mem_cgroup_from_css(css)->move_charge_at_immigrate;
  2922. }
  2923. #ifdef CONFIG_MMU
  2924. static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
  2925. struct cftype *cft, u64 val)
  2926. {
  2927. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  2928. if (val & ~MOVE_MASK)
  2929. return -EINVAL;
  2930. /*
  2931. * No kind of locking is needed in here, because ->can_attach() will
  2932. * check this value once in the beginning of the process, and then carry
  2933. * on with stale data. This means that changes to this value will only
  2934. * affect task migrations starting after the change.
  2935. */
  2936. memcg->move_charge_at_immigrate = val;
  2937. return 0;
  2938. }
  2939. #else
  2940. static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
  2941. struct cftype *cft, u64 val)
  2942. {
  2943. return -ENOSYS;
  2944. }
  2945. #endif
  2946. #ifdef CONFIG_NUMA
  2947. static int memcg_numa_stat_show(struct seq_file *m, void *v)
  2948. {
  2949. struct numa_stat {
  2950. const char *name;
  2951. unsigned int lru_mask;
  2952. };
  2953. static const struct numa_stat stats[] = {
  2954. { "total", LRU_ALL },
  2955. { "file", LRU_ALL_FILE },
  2956. { "anon", LRU_ALL_ANON },
  2957. { "unevictable", BIT(LRU_UNEVICTABLE) },
  2958. };
  2959. const struct numa_stat *stat;
  2960. int nid;
  2961. unsigned long nr;
  2962. struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
  2963. for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
  2964. nr = mem_cgroup_nr_lru_pages(memcg, stat->lru_mask);
  2965. seq_printf(m, "%s=%lu", stat->name, nr);
  2966. for_each_node_state(nid, N_MEMORY) {
  2967. nr = mem_cgroup_node_nr_lru_pages(memcg, nid,
  2968. stat->lru_mask);
  2969. seq_printf(m, " N%d=%lu", nid, nr);
  2970. }
  2971. seq_putc(m, '\n');
  2972. }
  2973. for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
  2974. struct mem_cgroup *iter;
  2975. nr = 0;
  2976. for_each_mem_cgroup_tree(iter, memcg)
  2977. nr += mem_cgroup_nr_lru_pages(iter, stat->lru_mask);
  2978. seq_printf(m, "hierarchical_%s=%lu", stat->name, nr);
  2979. for_each_node_state(nid, N_MEMORY) {
  2980. nr = 0;
  2981. for_each_mem_cgroup_tree(iter, memcg)
  2982. nr += mem_cgroup_node_nr_lru_pages(
  2983. iter, nid, stat->lru_mask);
  2984. seq_printf(m, " N%d=%lu", nid, nr);
  2985. }
  2986. seq_putc(m, '\n');
  2987. }
  2988. return 0;
  2989. }
  2990. #endif /* CONFIG_NUMA */
  2991. static int memcg_stat_show(struct seq_file *m, void *v)
  2992. {
  2993. struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
  2994. unsigned long memory, memsw;
  2995. struct mem_cgroup *mi;
  2996. unsigned int i;
  2997. BUILD_BUG_ON(ARRAY_SIZE(mem_cgroup_stat_names) !=
  2998. MEM_CGROUP_STAT_NSTATS);
  2999. BUILD_BUG_ON(ARRAY_SIZE(mem_cgroup_events_names) !=
  3000. MEM_CGROUP_EVENTS_NSTATS);
  3001. BUILD_BUG_ON(ARRAY_SIZE(mem_cgroup_lru_names) != NR_LRU_LISTS);
  3002. for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
  3003. if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
  3004. continue;
  3005. seq_printf(m, "%s %ld\n", mem_cgroup_stat_names[i],
  3006. mem_cgroup_read_stat(memcg, i) * PAGE_SIZE);
  3007. }
  3008. for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++)
  3009. seq_printf(m, "%s %lu\n", mem_cgroup_events_names[i],
  3010. mem_cgroup_read_events(memcg, i));
  3011. for (i = 0; i < NR_LRU_LISTS; i++)
  3012. seq_printf(m, "%s %lu\n", mem_cgroup_lru_names[i],
  3013. mem_cgroup_nr_lru_pages(memcg, BIT(i)) * PAGE_SIZE);
  3014. /* Hierarchical information */
  3015. memory = memsw = PAGE_COUNTER_MAX;
  3016. for (mi = memcg; mi; mi = parent_mem_cgroup(mi)) {
  3017. memory = min(memory, mi->memory.limit);
  3018. memsw = min(memsw, mi->memsw.limit);
  3019. }
  3020. seq_printf(m, "hierarchical_memory_limit %llu\n",
  3021. (u64)memory * PAGE_SIZE);
  3022. if (do_swap_account)
  3023. seq_printf(m, "hierarchical_memsw_limit %llu\n",
  3024. (u64)memsw * PAGE_SIZE);
  3025. for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
  3026. long long val = 0;
  3027. if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
  3028. continue;
  3029. for_each_mem_cgroup_tree(mi, memcg)
  3030. val += mem_cgroup_read_stat(mi, i) * PAGE_SIZE;
  3031. seq_printf(m, "total_%s %lld\n", mem_cgroup_stat_names[i], val);
  3032. }
  3033. for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
  3034. unsigned long long val = 0;
  3035. for_each_mem_cgroup_tree(mi, memcg)
  3036. val += mem_cgroup_read_events(mi, i);
  3037. seq_printf(m, "total_%s %llu\n",
  3038. mem_cgroup_events_names[i], val);
  3039. }
  3040. for (i = 0; i < NR_LRU_LISTS; i++) {
  3041. unsigned long long val = 0;
  3042. for_each_mem_cgroup_tree(mi, memcg)
  3043. val += mem_cgroup_nr_lru_pages(mi, BIT(i)) * PAGE_SIZE;
  3044. seq_printf(m, "total_%s %llu\n", mem_cgroup_lru_names[i], val);
  3045. }
  3046. #ifdef CONFIG_DEBUG_VM
  3047. {
  3048. int nid, zid;
  3049. struct mem_cgroup_per_zone *mz;
  3050. struct zone_reclaim_stat *rstat;
  3051. unsigned long recent_rotated[2] = {0, 0};
  3052. unsigned long recent_scanned[2] = {0, 0};
  3053. for_each_online_node(nid)
  3054. for (zid = 0; zid < MAX_NR_ZONES; zid++) {
  3055. mz = &memcg->nodeinfo[nid]->zoneinfo[zid];
  3056. rstat = &mz->lruvec.reclaim_stat;
  3057. recent_rotated[0] += rstat->recent_rotated[0];
  3058. recent_rotated[1] += rstat->recent_rotated[1];
  3059. recent_scanned[0] += rstat->recent_scanned[0];
  3060. recent_scanned[1] += rstat->recent_scanned[1];
  3061. }
  3062. seq_printf(m, "recent_rotated_anon %lu\n", recent_rotated[0]);
  3063. seq_printf(m, "recent_rotated_file %lu\n", recent_rotated[1]);
  3064. seq_printf(m, "recent_scanned_anon %lu\n", recent_scanned[0]);
  3065. seq_printf(m, "recent_scanned_file %lu\n", recent_scanned[1]);
  3066. }
  3067. #endif
  3068. return 0;
  3069. }
  3070. static u64 mem_cgroup_swappiness_read(struct cgroup_subsys_state *css,
  3071. struct cftype *cft)
  3072. {
  3073. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3074. return mem_cgroup_swappiness(memcg);
  3075. }
  3076. static int mem_cgroup_swappiness_write(struct cgroup_subsys_state *css,
  3077. struct cftype *cft, u64 val)
  3078. {
  3079. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3080. if (val > 100)
  3081. return -EINVAL;
  3082. if (css->parent)
  3083. memcg->swappiness = val;
  3084. else
  3085. vm_swappiness = val;
  3086. return 0;
  3087. }
  3088. static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
  3089. {
  3090. struct mem_cgroup_threshold_ary *t;
  3091. unsigned long usage;
  3092. int i;
  3093. rcu_read_lock();
  3094. if (!swap)
  3095. t = rcu_dereference(memcg->thresholds.primary);
  3096. else
  3097. t = rcu_dereference(memcg->memsw_thresholds.primary);
  3098. if (!t)
  3099. goto unlock;
  3100. usage = mem_cgroup_usage(memcg, swap);
  3101. /*
  3102. * current_threshold points to threshold just below or equal to usage.
  3103. * If it's not true, a threshold was crossed after last
  3104. * call of __mem_cgroup_threshold().
  3105. */
  3106. i = t->current_threshold;
  3107. /*
  3108. * Iterate backward over array of thresholds starting from
  3109. * current_threshold and check if a threshold is crossed.
  3110. * If none of thresholds below usage is crossed, we read
  3111. * only one element of the array here.
  3112. */
  3113. for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
  3114. eventfd_signal(t->entries[i].eventfd, 1);
  3115. /* i = current_threshold + 1 */
  3116. i++;
  3117. /*
  3118. * Iterate forward over array of thresholds starting from
  3119. * current_threshold+1 and check if a threshold is crossed.
  3120. * If none of thresholds above usage is crossed, we read
  3121. * only one element of the array here.
  3122. */
  3123. for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
  3124. eventfd_signal(t->entries[i].eventfd, 1);
  3125. /* Update current_threshold */
  3126. t->current_threshold = i - 1;
  3127. unlock:
  3128. rcu_read_unlock();
  3129. }
  3130. static void mem_cgroup_threshold(struct mem_cgroup *memcg)
  3131. {
  3132. while (memcg) {
  3133. __mem_cgroup_threshold(memcg, false);
  3134. if (do_swap_account)
  3135. __mem_cgroup_threshold(memcg, true);
  3136. memcg = parent_mem_cgroup(memcg);
  3137. }
  3138. }
  3139. static int compare_thresholds(const void *a, const void *b)
  3140. {
  3141. const struct mem_cgroup_threshold *_a = a;
  3142. const struct mem_cgroup_threshold *_b = b;
  3143. if (_a->threshold > _b->threshold)
  3144. return 1;
  3145. if (_a->threshold < _b->threshold)
  3146. return -1;
  3147. return 0;
  3148. }
  3149. static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
  3150. {
  3151. struct mem_cgroup_eventfd_list *ev;
  3152. spin_lock(&memcg_oom_lock);
  3153. list_for_each_entry(ev, &memcg->oom_notify, list)
  3154. eventfd_signal(ev->eventfd, 1);
  3155. spin_unlock(&memcg_oom_lock);
  3156. return 0;
  3157. }
  3158. static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
  3159. {
  3160. struct mem_cgroup *iter;
  3161. for_each_mem_cgroup_tree(iter, memcg)
  3162. mem_cgroup_oom_notify_cb(iter);
  3163. }
  3164. static int __mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
  3165. struct eventfd_ctx *eventfd, const char *args, enum res_type type)
  3166. {
  3167. struct mem_cgroup_thresholds *thresholds;
  3168. struct mem_cgroup_threshold_ary *new;
  3169. unsigned long threshold;
  3170. unsigned long usage;
  3171. int i, size, ret;
  3172. ret = page_counter_memparse(args, "-1", &threshold);
  3173. if (ret)
  3174. return ret;
  3175. mutex_lock(&memcg->thresholds_lock);
  3176. if (type == _MEM) {
  3177. thresholds = &memcg->thresholds;
  3178. usage = mem_cgroup_usage(memcg, false);
  3179. } else if (type == _MEMSWAP) {
  3180. thresholds = &memcg->memsw_thresholds;
  3181. usage = mem_cgroup_usage(memcg, true);
  3182. } else
  3183. BUG();
  3184. /* Check if a threshold crossed before adding a new one */
  3185. if (thresholds->primary)
  3186. __mem_cgroup_threshold(memcg, type == _MEMSWAP);
  3187. size = thresholds->primary ? thresholds->primary->size + 1 : 1;
  3188. /* Allocate memory for new array of thresholds */
  3189. new = kmalloc(sizeof(*new) + size * sizeof(struct mem_cgroup_threshold),
  3190. GFP_KERNEL);
  3191. if (!new) {
  3192. ret = -ENOMEM;
  3193. goto unlock;
  3194. }
  3195. new->size = size;
  3196. /* Copy thresholds (if any) to new array */
  3197. if (thresholds->primary) {
  3198. memcpy(new->entries, thresholds->primary->entries, (size - 1) *
  3199. sizeof(struct mem_cgroup_threshold));
  3200. }
  3201. /* Add new threshold */
  3202. new->entries[size - 1].eventfd = eventfd;
  3203. new->entries[size - 1].threshold = threshold;
  3204. /* Sort thresholds. Registering of new threshold isn't time-critical */
  3205. sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
  3206. compare_thresholds, NULL);
  3207. /* Find current threshold */
  3208. new->current_threshold = -1;
  3209. for (i = 0; i < size; i++) {
  3210. if (new->entries[i].threshold <= usage) {
  3211. /*
  3212. * new->current_threshold will not be used until
  3213. * rcu_assign_pointer(), so it's safe to increment
  3214. * it here.
  3215. */
  3216. ++new->current_threshold;
  3217. } else
  3218. break;
  3219. }
  3220. /* Free old spare buffer and save old primary buffer as spare */
  3221. kfree(thresholds->spare);
  3222. thresholds->spare = thresholds->primary;
  3223. rcu_assign_pointer(thresholds->primary, new);
  3224. /* To be sure that nobody uses thresholds */
  3225. synchronize_rcu();
  3226. unlock:
  3227. mutex_unlock(&memcg->thresholds_lock);
  3228. return ret;
  3229. }
  3230. static int mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
  3231. struct eventfd_ctx *eventfd, const char *args)
  3232. {
  3233. return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEM);
  3234. }
  3235. static int memsw_cgroup_usage_register_event(struct mem_cgroup *memcg,
  3236. struct eventfd_ctx *eventfd, const char *args)
  3237. {
  3238. return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEMSWAP);
  3239. }
  3240. static void __mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
  3241. struct eventfd_ctx *eventfd, enum res_type type)
  3242. {
  3243. struct mem_cgroup_thresholds *thresholds;
  3244. struct mem_cgroup_threshold_ary *new;
  3245. unsigned long usage;
  3246. int i, j, size;
  3247. mutex_lock(&memcg->thresholds_lock);
  3248. if (type == _MEM) {
  3249. thresholds = &memcg->thresholds;
  3250. usage = mem_cgroup_usage(memcg, false);
  3251. } else if (type == _MEMSWAP) {
  3252. thresholds = &memcg->memsw_thresholds;
  3253. usage = mem_cgroup_usage(memcg, true);
  3254. } else
  3255. BUG();
  3256. if (!thresholds->primary)
  3257. goto unlock;
  3258. /* Check if a threshold crossed before removing */
  3259. __mem_cgroup_threshold(memcg, type == _MEMSWAP);
  3260. /* Calculate new number of threshold */
  3261. size = 0;
  3262. for (i = 0; i < thresholds->primary->size; i++) {
  3263. if (thresholds->primary->entries[i].eventfd != eventfd)
  3264. size++;
  3265. }
  3266. new = thresholds->spare;
  3267. /* Set thresholds array to NULL if we don't have thresholds */
  3268. if (!size) {
  3269. kfree(new);
  3270. new = NULL;
  3271. goto swap_buffers;
  3272. }
  3273. new->size = size;
  3274. /* Copy thresholds and find current threshold */
  3275. new->current_threshold = -1;
  3276. for (i = 0, j = 0; i < thresholds->primary->size; i++) {
  3277. if (thresholds->primary->entries[i].eventfd == eventfd)
  3278. continue;
  3279. new->entries[j] = thresholds->primary->entries[i];
  3280. if (new->entries[j].threshold <= usage) {
  3281. /*
  3282. * new->current_threshold will not be used
  3283. * until rcu_assign_pointer(), so it's safe to increment
  3284. * it here.
  3285. */
  3286. ++new->current_threshold;
  3287. }
  3288. j++;
  3289. }
  3290. swap_buffers:
  3291. /* Swap primary and spare array */
  3292. thresholds->spare = thresholds->primary;
  3293. /* If all events are unregistered, free the spare array */
  3294. if (!new) {
  3295. kfree(thresholds->spare);
  3296. thresholds->spare = NULL;
  3297. }
  3298. rcu_assign_pointer(thresholds->primary, new);
  3299. /* To be sure that nobody uses thresholds */
  3300. synchronize_rcu();
  3301. unlock:
  3302. mutex_unlock(&memcg->thresholds_lock);
  3303. }
  3304. static void mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
  3305. struct eventfd_ctx *eventfd)
  3306. {
  3307. return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEM);
  3308. }
  3309. static void memsw_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
  3310. struct eventfd_ctx *eventfd)
  3311. {
  3312. return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEMSWAP);
  3313. }
  3314. static int mem_cgroup_oom_register_event(struct mem_cgroup *memcg,
  3315. struct eventfd_ctx *eventfd, const char *args)
  3316. {
  3317. struct mem_cgroup_eventfd_list *event;
  3318. event = kmalloc(sizeof(*event), GFP_KERNEL);
  3319. if (!event)
  3320. return -ENOMEM;
  3321. spin_lock(&memcg_oom_lock);
  3322. event->eventfd = eventfd;
  3323. list_add(&event->list, &memcg->oom_notify);
  3324. /* already in OOM ? */
  3325. if (atomic_read(&memcg->under_oom))
  3326. eventfd_signal(eventfd, 1);
  3327. spin_unlock(&memcg_oom_lock);
  3328. return 0;
  3329. }
  3330. static void mem_cgroup_oom_unregister_event(struct mem_cgroup *memcg,
  3331. struct eventfd_ctx *eventfd)
  3332. {
  3333. struct mem_cgroup_eventfd_list *ev, *tmp;
  3334. spin_lock(&memcg_oom_lock);
  3335. list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
  3336. if (ev->eventfd == eventfd) {
  3337. list_del(&ev->list);
  3338. kfree(ev);
  3339. }
  3340. }
  3341. spin_unlock(&memcg_oom_lock);
  3342. }
  3343. static int mem_cgroup_oom_control_read(struct seq_file *sf, void *v)
  3344. {
  3345. struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(sf));
  3346. seq_printf(sf, "oom_kill_disable %d\n", memcg->oom_kill_disable);
  3347. seq_printf(sf, "under_oom %d\n", (bool)atomic_read(&memcg->under_oom));
  3348. return 0;
  3349. }
  3350. static int mem_cgroup_oom_control_write(struct cgroup_subsys_state *css,
  3351. struct cftype *cft, u64 val)
  3352. {
  3353. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3354. /* cannot set to root cgroup and only 0 and 1 are allowed */
  3355. if (!css->parent || !((val == 0) || (val == 1)))
  3356. return -EINVAL;
  3357. memcg->oom_kill_disable = val;
  3358. if (!val)
  3359. memcg_oom_recover(memcg);
  3360. return 0;
  3361. }
  3362. #ifdef CONFIG_MEMCG_KMEM
  3363. static int memcg_init_kmem(struct mem_cgroup *memcg, struct cgroup_subsys *ss)
  3364. {
  3365. int ret;
  3366. ret = memcg_propagate_kmem(memcg);
  3367. if (ret)
  3368. return ret;
  3369. return mem_cgroup_sockets_init(memcg, ss);
  3370. }
  3371. static void memcg_deactivate_kmem(struct mem_cgroup *memcg)
  3372. {
  3373. struct cgroup_subsys_state *css;
  3374. struct mem_cgroup *parent, *child;
  3375. int kmemcg_id;
  3376. if (!memcg->kmem_acct_active)
  3377. return;
  3378. /*
  3379. * Clear the 'active' flag before clearing memcg_caches arrays entries.
  3380. * Since we take the slab_mutex in memcg_deactivate_kmem_caches(), it
  3381. * guarantees no cache will be created for this cgroup after we are
  3382. * done (see memcg_create_kmem_cache()).
  3383. */
  3384. memcg->kmem_acct_active = false;
  3385. memcg_deactivate_kmem_caches(memcg);
  3386. kmemcg_id = memcg->kmemcg_id;
  3387. BUG_ON(kmemcg_id < 0);
  3388. parent = parent_mem_cgroup(memcg);
  3389. if (!parent)
  3390. parent = root_mem_cgroup;
  3391. /*
  3392. * Change kmemcg_id of this cgroup and all its descendants to the
  3393. * parent's id, and then move all entries from this cgroup's list_lrus
  3394. * to ones of the parent. After we have finished, all list_lrus
  3395. * corresponding to this cgroup are guaranteed to remain empty. The
  3396. * ordering is imposed by list_lru_node->lock taken by
  3397. * memcg_drain_all_list_lrus().
  3398. */
  3399. css_for_each_descendant_pre(css, &memcg->css) {
  3400. child = mem_cgroup_from_css(css);
  3401. BUG_ON(child->kmemcg_id != kmemcg_id);
  3402. child->kmemcg_id = parent->kmemcg_id;
  3403. if (!memcg->use_hierarchy)
  3404. break;
  3405. }
  3406. memcg_drain_all_list_lrus(kmemcg_id, parent->kmemcg_id);
  3407. memcg_free_cache_id(kmemcg_id);
  3408. }
  3409. static void memcg_destroy_kmem(struct mem_cgroup *memcg)
  3410. {
  3411. if (memcg->kmem_acct_activated) {
  3412. memcg_destroy_kmem_caches(memcg);
  3413. static_key_slow_dec(&memcg_kmem_enabled_key);
  3414. WARN_ON(page_counter_read(&memcg->kmem));
  3415. }
  3416. mem_cgroup_sockets_destroy(memcg);
  3417. }
  3418. #else
  3419. static int memcg_init_kmem(struct mem_cgroup *memcg, struct cgroup_subsys *ss)
  3420. {
  3421. return 0;
  3422. }
  3423. static void memcg_deactivate_kmem(struct mem_cgroup *memcg)
  3424. {
  3425. }
  3426. static void memcg_destroy_kmem(struct mem_cgroup *memcg)
  3427. {
  3428. }
  3429. #endif
  3430. /*
  3431. * DO NOT USE IN NEW FILES.
  3432. *
  3433. * "cgroup.event_control" implementation.
  3434. *
  3435. * This is way over-engineered. It tries to support fully configurable
  3436. * events for each user. Such level of flexibility is completely
  3437. * unnecessary especially in the light of the planned unified hierarchy.
  3438. *
  3439. * Please deprecate this and replace with something simpler if at all
  3440. * possible.
  3441. */
  3442. /*
  3443. * Unregister event and free resources.
  3444. *
  3445. * Gets called from workqueue.
  3446. */
  3447. static void memcg_event_remove(struct work_struct *work)
  3448. {
  3449. struct mem_cgroup_event *event =
  3450. container_of(work, struct mem_cgroup_event, remove);
  3451. struct mem_cgroup *memcg = event->memcg;
  3452. remove_wait_queue(event->wqh, &event->wait);
  3453. event->unregister_event(memcg, event->eventfd);
  3454. /* Notify userspace the event is going away. */
  3455. eventfd_signal(event->eventfd, 1);
  3456. eventfd_ctx_put(event->eventfd);
  3457. kfree(event);
  3458. css_put(&memcg->css);
  3459. }
  3460. /*
  3461. * Gets called on POLLHUP on eventfd when user closes it.
  3462. *
  3463. * Called with wqh->lock held and interrupts disabled.
  3464. */
  3465. static int memcg_event_wake(wait_queue_t *wait, unsigned mode,
  3466. int sync, void *key)
  3467. {
  3468. struct mem_cgroup_event *event =
  3469. container_of(wait, struct mem_cgroup_event, wait);
  3470. struct mem_cgroup *memcg = event->memcg;
  3471. unsigned long flags = (unsigned long)key;
  3472. if (flags & POLLHUP) {
  3473. /*
  3474. * If the event has been detached at cgroup removal, we
  3475. * can simply return knowing the other side will cleanup
  3476. * for us.
  3477. *
  3478. * We can't race against event freeing since the other
  3479. * side will require wqh->lock via remove_wait_queue(),
  3480. * which we hold.
  3481. */
  3482. spin_lock(&memcg->event_list_lock);
  3483. if (!list_empty(&event->list)) {
  3484. list_del_init(&event->list);
  3485. /*
  3486. * We are in atomic context, but cgroup_event_remove()
  3487. * may sleep, so we have to call it in workqueue.
  3488. */
  3489. schedule_work(&event->remove);
  3490. }
  3491. spin_unlock(&memcg->event_list_lock);
  3492. }
  3493. return 0;
  3494. }
  3495. static void memcg_event_ptable_queue_proc(struct file *file,
  3496. wait_queue_head_t *wqh, poll_table *pt)
  3497. {
  3498. struct mem_cgroup_event *event =
  3499. container_of(pt, struct mem_cgroup_event, pt);
  3500. event->wqh = wqh;
  3501. add_wait_queue(wqh, &event->wait);
  3502. }
  3503. /*
  3504. * DO NOT USE IN NEW FILES.
  3505. *
  3506. * Parse input and register new cgroup event handler.
  3507. *
  3508. * Input must be in format '<event_fd> <control_fd> <args>'.
  3509. * Interpretation of args is defined by control file implementation.
  3510. */
  3511. static ssize_t memcg_write_event_control(struct kernfs_open_file *of,
  3512. char *buf, size_t nbytes, loff_t off)
  3513. {
  3514. struct cgroup_subsys_state *css = of_css(of);
  3515. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3516. struct mem_cgroup_event *event;
  3517. struct cgroup_subsys_state *cfile_css;
  3518. unsigned int efd, cfd;
  3519. struct fd efile;
  3520. struct fd cfile;
  3521. const char *name;
  3522. char *endp;
  3523. int ret;
  3524. buf = strstrip(buf);
  3525. efd = simple_strtoul(buf, &endp, 10);
  3526. if (*endp != ' ')
  3527. return -EINVAL;
  3528. buf = endp + 1;
  3529. cfd = simple_strtoul(buf, &endp, 10);
  3530. if ((*endp != ' ') && (*endp != '\0'))
  3531. return -EINVAL;
  3532. buf = endp + 1;
  3533. event = kzalloc(sizeof(*event), GFP_KERNEL);
  3534. if (!event)
  3535. return -ENOMEM;
  3536. event->memcg = memcg;
  3537. INIT_LIST_HEAD(&event->list);
  3538. init_poll_funcptr(&event->pt, memcg_event_ptable_queue_proc);
  3539. init_waitqueue_func_entry(&event->wait, memcg_event_wake);
  3540. INIT_WORK(&event->remove, memcg_event_remove);
  3541. efile = fdget(efd);
  3542. if (!efile.file) {
  3543. ret = -EBADF;
  3544. goto out_kfree;
  3545. }
  3546. event->eventfd = eventfd_ctx_fileget(efile.file);
  3547. if (IS_ERR(event->eventfd)) {
  3548. ret = PTR_ERR(event->eventfd);
  3549. goto out_put_efile;
  3550. }
  3551. cfile = fdget(cfd);
  3552. if (!cfile.file) {
  3553. ret = -EBADF;
  3554. goto out_put_eventfd;
  3555. }
  3556. /* the process need read permission on control file */
  3557. /* AV: shouldn't we check that it's been opened for read instead? */
  3558. ret = inode_permission(file_inode(cfile.file), MAY_READ);
  3559. if (ret < 0)
  3560. goto out_put_cfile;
  3561. /*
  3562. * Determine the event callbacks and set them in @event. This used
  3563. * to be done via struct cftype but cgroup core no longer knows
  3564. * about these events. The following is crude but the whole thing
  3565. * is for compatibility anyway.
  3566. *
  3567. * DO NOT ADD NEW FILES.
  3568. */
  3569. name = cfile.file->f_path.dentry->d_name.name;
  3570. if (!strcmp(name, "memory.usage_in_bytes")) {
  3571. event->register_event = mem_cgroup_usage_register_event;
  3572. event->unregister_event = mem_cgroup_usage_unregister_event;
  3573. } else if (!strcmp(name, "memory.oom_control")) {
  3574. event->register_event = mem_cgroup_oom_register_event;
  3575. event->unregister_event = mem_cgroup_oom_unregister_event;
  3576. } else if (!strcmp(name, "memory.pressure_level")) {
  3577. event->register_event = vmpressure_register_event;
  3578. event->unregister_event = vmpressure_unregister_event;
  3579. } else if (!strcmp(name, "memory.memsw.usage_in_bytes")) {
  3580. event->register_event = memsw_cgroup_usage_register_event;
  3581. event->unregister_event = memsw_cgroup_usage_unregister_event;
  3582. } else {
  3583. ret = -EINVAL;
  3584. goto out_put_cfile;
  3585. }
  3586. /*
  3587. * Verify @cfile should belong to @css. Also, remaining events are
  3588. * automatically removed on cgroup destruction but the removal is
  3589. * asynchronous, so take an extra ref on @css.
  3590. */
  3591. cfile_css = css_tryget_online_from_dir(cfile.file->f_path.dentry->d_parent,
  3592. &memory_cgrp_subsys);
  3593. ret = -EINVAL;
  3594. if (IS_ERR(cfile_css))
  3595. goto out_put_cfile;
  3596. if (cfile_css != css) {
  3597. css_put(cfile_css);
  3598. goto out_put_cfile;
  3599. }
  3600. ret = event->register_event(memcg, event->eventfd, buf);
  3601. if (ret)
  3602. goto out_put_css;
  3603. efile.file->f_op->poll(efile.file, &event->pt);
  3604. spin_lock(&memcg->event_list_lock);
  3605. list_add(&event->list, &memcg->event_list);
  3606. spin_unlock(&memcg->event_list_lock);
  3607. fdput(cfile);
  3608. fdput(efile);
  3609. return nbytes;
  3610. out_put_css:
  3611. css_put(css);
  3612. out_put_cfile:
  3613. fdput(cfile);
  3614. out_put_eventfd:
  3615. eventfd_ctx_put(event->eventfd);
  3616. out_put_efile:
  3617. fdput(efile);
  3618. out_kfree:
  3619. kfree(event);
  3620. return ret;
  3621. }
  3622. static struct cftype mem_cgroup_legacy_files[] = {
  3623. {
  3624. .name = "usage_in_bytes",
  3625. .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
  3626. .read_u64 = mem_cgroup_read_u64,
  3627. },
  3628. {
  3629. .name = "max_usage_in_bytes",
  3630. .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
  3631. .write = mem_cgroup_reset,
  3632. .read_u64 = mem_cgroup_read_u64,
  3633. },
  3634. {
  3635. .name = "limit_in_bytes",
  3636. .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
  3637. .write = mem_cgroup_write,
  3638. .read_u64 = mem_cgroup_read_u64,
  3639. },
  3640. {
  3641. .name = "soft_limit_in_bytes",
  3642. .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
  3643. .write = mem_cgroup_write,
  3644. .read_u64 = mem_cgroup_read_u64,
  3645. },
  3646. {
  3647. .name = "failcnt",
  3648. .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
  3649. .write = mem_cgroup_reset,
  3650. .read_u64 = mem_cgroup_read_u64,
  3651. },
  3652. {
  3653. .name = "stat",
  3654. .seq_show = memcg_stat_show,
  3655. },
  3656. {
  3657. .name = "force_empty",
  3658. .write = mem_cgroup_force_empty_write,
  3659. },
  3660. {
  3661. .name = "use_hierarchy",
  3662. .write_u64 = mem_cgroup_hierarchy_write,
  3663. .read_u64 = mem_cgroup_hierarchy_read,
  3664. },
  3665. {
  3666. .name = "cgroup.event_control", /* XXX: for compat */
  3667. .write = memcg_write_event_control,
  3668. .flags = CFTYPE_NO_PREFIX,
  3669. .mode = S_IWUGO,
  3670. },
  3671. {
  3672. .name = "swappiness",
  3673. .read_u64 = mem_cgroup_swappiness_read,
  3674. .write_u64 = mem_cgroup_swappiness_write,
  3675. },
  3676. {
  3677. .name = "move_charge_at_immigrate",
  3678. .read_u64 = mem_cgroup_move_charge_read,
  3679. .write_u64 = mem_cgroup_move_charge_write,
  3680. },
  3681. {
  3682. .name = "oom_control",
  3683. .seq_show = mem_cgroup_oom_control_read,
  3684. .write_u64 = mem_cgroup_oom_control_write,
  3685. .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
  3686. },
  3687. {
  3688. .name = "pressure_level",
  3689. },
  3690. #ifdef CONFIG_NUMA
  3691. {
  3692. .name = "numa_stat",
  3693. .seq_show = memcg_numa_stat_show,
  3694. },
  3695. #endif
  3696. #ifdef CONFIG_MEMCG_KMEM
  3697. {
  3698. .name = "kmem.limit_in_bytes",
  3699. .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
  3700. .write = mem_cgroup_write,
  3701. .read_u64 = mem_cgroup_read_u64,
  3702. },
  3703. {
  3704. .name = "kmem.usage_in_bytes",
  3705. .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
  3706. .read_u64 = mem_cgroup_read_u64,
  3707. },
  3708. {
  3709. .name = "kmem.failcnt",
  3710. .private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
  3711. .write = mem_cgroup_reset,
  3712. .read_u64 = mem_cgroup_read_u64,
  3713. },
  3714. {
  3715. .name = "kmem.max_usage_in_bytes",
  3716. .private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
  3717. .write = mem_cgroup_reset,
  3718. .read_u64 = mem_cgroup_read_u64,
  3719. },
  3720. #ifdef CONFIG_SLABINFO
  3721. {
  3722. .name = "kmem.slabinfo",
  3723. .seq_start = slab_start,
  3724. .seq_next = slab_next,
  3725. .seq_stop = slab_stop,
  3726. .seq_show = memcg_slab_show,
  3727. },
  3728. #endif
  3729. #endif
  3730. { }, /* terminate */
  3731. };
  3732. static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
  3733. {
  3734. struct mem_cgroup_per_node *pn;
  3735. struct mem_cgroup_per_zone *mz;
  3736. int zone, tmp = node;
  3737. /*
  3738. * This routine is called against possible nodes.
  3739. * But it's BUG to call kmalloc() against offline node.
  3740. *
  3741. * TODO: this routine can waste much memory for nodes which will
  3742. * never be onlined. It's better to use memory hotplug callback
  3743. * function.
  3744. */
  3745. if (!node_state(node, N_NORMAL_MEMORY))
  3746. tmp = -1;
  3747. pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
  3748. if (!pn)
  3749. return 1;
  3750. for (zone = 0; zone < MAX_NR_ZONES; zone++) {
  3751. mz = &pn->zoneinfo[zone];
  3752. lruvec_init(&mz->lruvec);
  3753. mz->usage_in_excess = 0;
  3754. mz->on_tree = false;
  3755. mz->memcg = memcg;
  3756. }
  3757. memcg->nodeinfo[node] = pn;
  3758. return 0;
  3759. }
  3760. static void free_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
  3761. {
  3762. kfree(memcg->nodeinfo[node]);
  3763. }
  3764. static struct mem_cgroup *mem_cgroup_alloc(void)
  3765. {
  3766. struct mem_cgroup *memcg;
  3767. size_t size;
  3768. size = sizeof(struct mem_cgroup);
  3769. size += nr_node_ids * sizeof(struct mem_cgroup_per_node *);
  3770. memcg = kzalloc(size, GFP_KERNEL);
  3771. if (!memcg)
  3772. return NULL;
  3773. memcg->stat = alloc_percpu(struct mem_cgroup_stat_cpu);
  3774. if (!memcg->stat)
  3775. goto out_free;
  3776. spin_lock_init(&memcg->pcp_counter_lock);
  3777. return memcg;
  3778. out_free:
  3779. kfree(memcg);
  3780. return NULL;
  3781. }
  3782. /*
  3783. * At destroying mem_cgroup, references from swap_cgroup can remain.
  3784. * (scanning all at force_empty is too costly...)
  3785. *
  3786. * Instead of clearing all references at force_empty, we remember
  3787. * the number of reference from swap_cgroup and free mem_cgroup when
  3788. * it goes down to 0.
  3789. *
  3790. * Removal of cgroup itself succeeds regardless of refs from swap.
  3791. */
  3792. static void __mem_cgroup_free(struct mem_cgroup *memcg)
  3793. {
  3794. int node;
  3795. mem_cgroup_remove_from_trees(memcg);
  3796. for_each_node(node)
  3797. free_mem_cgroup_per_zone_info(memcg, node);
  3798. free_percpu(memcg->stat);
  3799. kfree(memcg);
  3800. }
  3801. /*
  3802. * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
  3803. */
  3804. struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *memcg)
  3805. {
  3806. if (!memcg->memory.parent)
  3807. return NULL;
  3808. return mem_cgroup_from_counter(memcg->memory.parent, memory);
  3809. }
  3810. EXPORT_SYMBOL(parent_mem_cgroup);
  3811. static struct cgroup_subsys_state * __ref
  3812. mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
  3813. {
  3814. struct mem_cgroup *memcg;
  3815. long error = -ENOMEM;
  3816. int node;
  3817. memcg = mem_cgroup_alloc();
  3818. if (!memcg)
  3819. return ERR_PTR(error);
  3820. for_each_node(node)
  3821. if (alloc_mem_cgroup_per_zone_info(memcg, node))
  3822. goto free_out;
  3823. /* root ? */
  3824. if (parent_css == NULL) {
  3825. root_mem_cgroup = memcg;
  3826. page_counter_init(&memcg->memory, NULL);
  3827. memcg->high = PAGE_COUNTER_MAX;
  3828. memcg->soft_limit = PAGE_COUNTER_MAX;
  3829. page_counter_init(&memcg->memsw, NULL);
  3830. page_counter_init(&memcg->kmem, NULL);
  3831. }
  3832. memcg->last_scanned_node = MAX_NUMNODES;
  3833. INIT_LIST_HEAD(&memcg->oom_notify);
  3834. memcg->move_charge_at_immigrate = 0;
  3835. mutex_init(&memcg->thresholds_lock);
  3836. spin_lock_init(&memcg->move_lock);
  3837. vmpressure_init(&memcg->vmpressure);
  3838. INIT_LIST_HEAD(&memcg->event_list);
  3839. spin_lock_init(&memcg->event_list_lock);
  3840. #ifdef CONFIG_MEMCG_KMEM
  3841. memcg->kmemcg_id = -1;
  3842. #endif
  3843. return &memcg->css;
  3844. free_out:
  3845. __mem_cgroup_free(memcg);
  3846. return ERR_PTR(error);
  3847. }
  3848. static int
  3849. mem_cgroup_css_online(struct cgroup_subsys_state *css)
  3850. {
  3851. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3852. struct mem_cgroup *parent = mem_cgroup_from_css(css->parent);
  3853. int ret;
  3854. if (css->id > MEM_CGROUP_ID_MAX)
  3855. return -ENOSPC;
  3856. if (!parent)
  3857. return 0;
  3858. mutex_lock(&memcg_create_mutex);
  3859. memcg->use_hierarchy = parent->use_hierarchy;
  3860. memcg->oom_kill_disable = parent->oom_kill_disable;
  3861. memcg->swappiness = mem_cgroup_swappiness(parent);
  3862. if (parent->use_hierarchy) {
  3863. page_counter_init(&memcg->memory, &parent->memory);
  3864. memcg->high = PAGE_COUNTER_MAX;
  3865. memcg->soft_limit = PAGE_COUNTER_MAX;
  3866. page_counter_init(&memcg->memsw, &parent->memsw);
  3867. page_counter_init(&memcg->kmem, &parent->kmem);
  3868. /*
  3869. * No need to take a reference to the parent because cgroup
  3870. * core guarantees its existence.
  3871. */
  3872. } else {
  3873. page_counter_init(&memcg->memory, NULL);
  3874. memcg->high = PAGE_COUNTER_MAX;
  3875. memcg->soft_limit = PAGE_COUNTER_MAX;
  3876. page_counter_init(&memcg->memsw, NULL);
  3877. page_counter_init(&memcg->kmem, NULL);
  3878. /*
  3879. * Deeper hierachy with use_hierarchy == false doesn't make
  3880. * much sense so let cgroup subsystem know about this
  3881. * unfortunate state in our controller.
  3882. */
  3883. if (parent != root_mem_cgroup)
  3884. memory_cgrp_subsys.broken_hierarchy = true;
  3885. }
  3886. mutex_unlock(&memcg_create_mutex);
  3887. ret = memcg_init_kmem(memcg, &memory_cgrp_subsys);
  3888. if (ret)
  3889. return ret;
  3890. /*
  3891. * Make sure the memcg is initialized: mem_cgroup_iter()
  3892. * orders reading memcg->initialized against its callers
  3893. * reading the memcg members.
  3894. */
  3895. smp_store_release(&memcg->initialized, 1);
  3896. return 0;
  3897. }
  3898. static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
  3899. {
  3900. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3901. struct mem_cgroup_event *event, *tmp;
  3902. /*
  3903. * Unregister events and notify userspace.
  3904. * Notify userspace about cgroup removing only after rmdir of cgroup
  3905. * directory to avoid race between userspace and kernelspace.
  3906. */
  3907. spin_lock(&memcg->event_list_lock);
  3908. list_for_each_entry_safe(event, tmp, &memcg->event_list, list) {
  3909. list_del_init(&event->list);
  3910. schedule_work(&event->remove);
  3911. }
  3912. spin_unlock(&memcg->event_list_lock);
  3913. vmpressure_cleanup(&memcg->vmpressure);
  3914. memcg_deactivate_kmem(memcg);
  3915. }
  3916. static void mem_cgroup_css_free(struct cgroup_subsys_state *css)
  3917. {
  3918. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3919. memcg_destroy_kmem(memcg);
  3920. __mem_cgroup_free(memcg);
  3921. }
  3922. /**
  3923. * mem_cgroup_css_reset - reset the states of a mem_cgroup
  3924. * @css: the target css
  3925. *
  3926. * Reset the states of the mem_cgroup associated with @css. This is
  3927. * invoked when the userland requests disabling on the default hierarchy
  3928. * but the memcg is pinned through dependency. The memcg should stop
  3929. * applying policies and should revert to the vanilla state as it may be
  3930. * made visible again.
  3931. *
  3932. * The current implementation only resets the essential configurations.
  3933. * This needs to be expanded to cover all the visible parts.
  3934. */
  3935. static void mem_cgroup_css_reset(struct cgroup_subsys_state *css)
  3936. {
  3937. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3938. mem_cgroup_resize_limit(memcg, PAGE_COUNTER_MAX);
  3939. mem_cgroup_resize_memsw_limit(memcg, PAGE_COUNTER_MAX);
  3940. memcg_update_kmem_limit(memcg, PAGE_COUNTER_MAX);
  3941. memcg->low = 0;
  3942. memcg->high = PAGE_COUNTER_MAX;
  3943. memcg->soft_limit = PAGE_COUNTER_MAX;
  3944. }
  3945. #ifdef CONFIG_MMU
  3946. /* Handlers for move charge at task migration. */
  3947. static int mem_cgroup_do_precharge(unsigned long count)
  3948. {
  3949. int ret;
  3950. /* Try a single bulk charge without reclaim first */
  3951. ret = try_charge(mc.to, GFP_KERNEL & ~__GFP_WAIT, count);
  3952. if (!ret) {
  3953. mc.precharge += count;
  3954. return ret;
  3955. }
  3956. if (ret == -EINTR) {
  3957. cancel_charge(root_mem_cgroup, count);
  3958. return ret;
  3959. }
  3960. /* Try charges one by one with reclaim */
  3961. while (count--) {
  3962. ret = try_charge(mc.to, GFP_KERNEL & ~__GFP_NORETRY, 1);
  3963. /*
  3964. * In case of failure, any residual charges against
  3965. * mc.to will be dropped by mem_cgroup_clear_mc()
  3966. * later on. However, cancel any charges that are
  3967. * bypassed to root right away or they'll be lost.
  3968. */
  3969. if (ret == -EINTR)
  3970. cancel_charge(root_mem_cgroup, 1);
  3971. if (ret)
  3972. return ret;
  3973. mc.precharge++;
  3974. cond_resched();
  3975. }
  3976. return 0;
  3977. }
  3978. /**
  3979. * get_mctgt_type - get target type of moving charge
  3980. * @vma: the vma the pte to be checked belongs
  3981. * @addr: the address corresponding to the pte to be checked
  3982. * @ptent: the pte to be checked
  3983. * @target: the pointer the target page or swap ent will be stored(can be NULL)
  3984. *
  3985. * Returns
  3986. * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
  3987. * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
  3988. * move charge. if @target is not NULL, the page is stored in target->page
  3989. * with extra refcnt got(Callers should handle it).
  3990. * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
  3991. * target for charge migration. if @target is not NULL, the entry is stored
  3992. * in target->ent.
  3993. *
  3994. * Called with pte lock held.
  3995. */
  3996. union mc_target {
  3997. struct page *page;
  3998. swp_entry_t ent;
  3999. };
  4000. enum mc_target_type {
  4001. MC_TARGET_NONE = 0,
  4002. MC_TARGET_PAGE,
  4003. MC_TARGET_SWAP,
  4004. };
  4005. static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
  4006. unsigned long addr, pte_t ptent)
  4007. {
  4008. struct page *page = vm_normal_page(vma, addr, ptent);
  4009. if (!page || !page_mapped(page))
  4010. return NULL;
  4011. if (PageAnon(page)) {
  4012. if (!(mc.flags & MOVE_ANON))
  4013. return NULL;
  4014. } else {
  4015. if (!(mc.flags & MOVE_FILE))
  4016. return NULL;
  4017. }
  4018. if (!get_page_unless_zero(page))
  4019. return NULL;
  4020. return page;
  4021. }
  4022. #ifdef CONFIG_SWAP
  4023. static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
  4024. unsigned long addr, pte_t ptent, swp_entry_t *entry)
  4025. {
  4026. struct page *page = NULL;
  4027. swp_entry_t ent = pte_to_swp_entry(ptent);
  4028. if (!(mc.flags & MOVE_ANON) || non_swap_entry(ent))
  4029. return NULL;
  4030. /*
  4031. * Because lookup_swap_cache() updates some statistics counter,
  4032. * we call find_get_page() with swapper_space directly.
  4033. */
  4034. page = find_get_page(swap_address_space(ent), ent.val);
  4035. if (do_swap_account)
  4036. entry->val = ent.val;
  4037. return page;
  4038. }
  4039. #else
  4040. static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
  4041. unsigned long addr, pte_t ptent, swp_entry_t *entry)
  4042. {
  4043. return NULL;
  4044. }
  4045. #endif
  4046. static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
  4047. unsigned long addr, pte_t ptent, swp_entry_t *entry)
  4048. {
  4049. struct page *page = NULL;
  4050. struct address_space *mapping;
  4051. pgoff_t pgoff;
  4052. if (!vma->vm_file) /* anonymous vma */
  4053. return NULL;
  4054. if (!(mc.flags & MOVE_FILE))
  4055. return NULL;
  4056. mapping = vma->vm_file->f_mapping;
  4057. pgoff = linear_page_index(vma, addr);
  4058. /* page is moved even if it's not RSS of this task(page-faulted). */
  4059. #ifdef CONFIG_SWAP
  4060. /* shmem/tmpfs may report page out on swap: account for that too. */
  4061. if (shmem_mapping(mapping)) {
  4062. page = find_get_entry(mapping, pgoff);
  4063. if (radix_tree_exceptional_entry(page)) {
  4064. swp_entry_t swp = radix_to_swp_entry(page);
  4065. if (do_swap_account)
  4066. *entry = swp;
  4067. page = find_get_page(swap_address_space(swp), swp.val);
  4068. }
  4069. } else
  4070. page = find_get_page(mapping, pgoff);
  4071. #else
  4072. page = find_get_page(mapping, pgoff);
  4073. #endif
  4074. return page;
  4075. }
  4076. /**
  4077. * mem_cgroup_move_account - move account of the page
  4078. * @page: the page
  4079. * @nr_pages: number of regular pages (>1 for huge pages)
  4080. * @from: mem_cgroup which the page is moved from.
  4081. * @to: mem_cgroup which the page is moved to. @from != @to.
  4082. *
  4083. * The caller must confirm following.
  4084. * - page is not on LRU (isolate_page() is useful.)
  4085. * - compound_lock is held when nr_pages > 1
  4086. *
  4087. * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
  4088. * from old cgroup.
  4089. */
  4090. static int mem_cgroup_move_account(struct page *page,
  4091. unsigned int nr_pages,
  4092. struct mem_cgroup *from,
  4093. struct mem_cgroup *to)
  4094. {
  4095. unsigned long flags;
  4096. int ret;
  4097. VM_BUG_ON(from == to);
  4098. VM_BUG_ON_PAGE(PageLRU(page), page);
  4099. /*
  4100. * The page is isolated from LRU. So, collapse function
  4101. * will not handle this page. But page splitting can happen.
  4102. * Do this check under compound_page_lock(). The caller should
  4103. * hold it.
  4104. */
  4105. ret = -EBUSY;
  4106. if (nr_pages > 1 && !PageTransHuge(page))
  4107. goto out;
  4108. /*
  4109. * Prevent mem_cgroup_migrate() from looking at page->mem_cgroup
  4110. * of its source page while we change it: page migration takes
  4111. * both pages off the LRU, but page cache replacement doesn't.
  4112. */
  4113. if (!trylock_page(page))
  4114. goto out;
  4115. ret = -EINVAL;
  4116. if (page->mem_cgroup != from)
  4117. goto out_unlock;
  4118. spin_lock_irqsave(&from->move_lock, flags);
  4119. if (!PageAnon(page) && page_mapped(page)) {
  4120. __this_cpu_sub(from->stat->count[MEM_CGROUP_STAT_FILE_MAPPED],
  4121. nr_pages);
  4122. __this_cpu_add(to->stat->count[MEM_CGROUP_STAT_FILE_MAPPED],
  4123. nr_pages);
  4124. }
  4125. if (PageWriteback(page)) {
  4126. __this_cpu_sub(from->stat->count[MEM_CGROUP_STAT_WRITEBACK],
  4127. nr_pages);
  4128. __this_cpu_add(to->stat->count[MEM_CGROUP_STAT_WRITEBACK],
  4129. nr_pages);
  4130. }
  4131. /*
  4132. * It is safe to change page->mem_cgroup here because the page
  4133. * is referenced, charged, and isolated - we can't race with
  4134. * uncharging, charging, migration, or LRU putback.
  4135. */
  4136. /* caller should have done css_get */
  4137. page->mem_cgroup = to;
  4138. spin_unlock_irqrestore(&from->move_lock, flags);
  4139. ret = 0;
  4140. local_irq_disable();
  4141. mem_cgroup_charge_statistics(to, page, nr_pages);
  4142. memcg_check_events(to, page);
  4143. mem_cgroup_charge_statistics(from, page, -nr_pages);
  4144. memcg_check_events(from, page);
  4145. local_irq_enable();
  4146. out_unlock:
  4147. unlock_page(page);
  4148. out:
  4149. return ret;
  4150. }
  4151. static enum mc_target_type get_mctgt_type(struct vm_area_struct *vma,
  4152. unsigned long addr, pte_t ptent, union mc_target *target)
  4153. {
  4154. struct page *page = NULL;
  4155. enum mc_target_type ret = MC_TARGET_NONE;
  4156. swp_entry_t ent = { .val = 0 };
  4157. if (pte_present(ptent))
  4158. page = mc_handle_present_pte(vma, addr, ptent);
  4159. else if (is_swap_pte(ptent))
  4160. page = mc_handle_swap_pte(vma, addr, ptent, &ent);
  4161. else if (pte_none(ptent))
  4162. page = mc_handle_file_pte(vma, addr, ptent, &ent);
  4163. if (!page && !ent.val)
  4164. return ret;
  4165. if (page) {
  4166. /*
  4167. * Do only loose check w/o serialization.
  4168. * mem_cgroup_move_account() checks the page is valid or
  4169. * not under LRU exclusion.
  4170. */
  4171. if (page->mem_cgroup == mc.from) {
  4172. ret = MC_TARGET_PAGE;
  4173. if (target)
  4174. target->page = page;
  4175. }
  4176. if (!ret || !target)
  4177. put_page(page);
  4178. }
  4179. /* There is a swap entry and a page doesn't exist or isn't charged */
  4180. if (ent.val && !ret &&
  4181. mem_cgroup_id(mc.from) == lookup_swap_cgroup_id(ent)) {
  4182. ret = MC_TARGET_SWAP;
  4183. if (target)
  4184. target->ent = ent;
  4185. }
  4186. return ret;
  4187. }
  4188. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  4189. /*
  4190. * We don't consider swapping or file mapped pages because THP does not
  4191. * support them for now.
  4192. * Caller should make sure that pmd_trans_huge(pmd) is true.
  4193. */
  4194. static enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
  4195. unsigned long addr, pmd_t pmd, union mc_target *target)
  4196. {
  4197. struct page *page = NULL;
  4198. enum mc_target_type ret = MC_TARGET_NONE;
  4199. page = pmd_page(pmd);
  4200. VM_BUG_ON_PAGE(!page || !PageHead(page), page);
  4201. if (!(mc.flags & MOVE_ANON))
  4202. return ret;
  4203. if (page->mem_cgroup == mc.from) {
  4204. ret = MC_TARGET_PAGE;
  4205. if (target) {
  4206. get_page(page);
  4207. target->page = page;
  4208. }
  4209. }
  4210. return ret;
  4211. }
  4212. #else
  4213. static inline enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
  4214. unsigned long addr, pmd_t pmd, union mc_target *target)
  4215. {
  4216. return MC_TARGET_NONE;
  4217. }
  4218. #endif
  4219. static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
  4220. unsigned long addr, unsigned long end,
  4221. struct mm_walk *walk)
  4222. {
  4223. struct vm_area_struct *vma = walk->vma;
  4224. pte_t *pte;
  4225. spinlock_t *ptl;
  4226. if (pmd_trans_huge_lock(pmd, vma, &ptl) == 1) {
  4227. if (get_mctgt_type_thp(vma, addr, *pmd, NULL) == MC_TARGET_PAGE)
  4228. mc.precharge += HPAGE_PMD_NR;
  4229. spin_unlock(ptl);
  4230. return 0;
  4231. }
  4232. if (pmd_trans_unstable(pmd))
  4233. return 0;
  4234. pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
  4235. for (; addr != end; pte++, addr += PAGE_SIZE)
  4236. if (get_mctgt_type(vma, addr, *pte, NULL))
  4237. mc.precharge++; /* increment precharge temporarily */
  4238. pte_unmap_unlock(pte - 1, ptl);
  4239. cond_resched();
  4240. return 0;
  4241. }
  4242. static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
  4243. {
  4244. unsigned long precharge;
  4245. struct mm_walk mem_cgroup_count_precharge_walk = {
  4246. .pmd_entry = mem_cgroup_count_precharge_pte_range,
  4247. .mm = mm,
  4248. };
  4249. down_read(&mm->mmap_sem);
  4250. walk_page_range(0, ~0UL, &mem_cgroup_count_precharge_walk);
  4251. up_read(&mm->mmap_sem);
  4252. precharge = mc.precharge;
  4253. mc.precharge = 0;
  4254. return precharge;
  4255. }
  4256. static int mem_cgroup_precharge_mc(struct mm_struct *mm)
  4257. {
  4258. unsigned long precharge = mem_cgroup_count_precharge(mm);
  4259. VM_BUG_ON(mc.moving_task);
  4260. mc.moving_task = current;
  4261. return mem_cgroup_do_precharge(precharge);
  4262. }
  4263. /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
  4264. static void __mem_cgroup_clear_mc(void)
  4265. {
  4266. struct mem_cgroup *from = mc.from;
  4267. struct mem_cgroup *to = mc.to;
  4268. /* we must uncharge all the leftover precharges from mc.to */
  4269. if (mc.precharge) {
  4270. cancel_charge(mc.to, mc.precharge);
  4271. mc.precharge = 0;
  4272. }
  4273. /*
  4274. * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
  4275. * we must uncharge here.
  4276. */
  4277. if (mc.moved_charge) {
  4278. cancel_charge(mc.from, mc.moved_charge);
  4279. mc.moved_charge = 0;
  4280. }
  4281. /* we must fixup refcnts and charges */
  4282. if (mc.moved_swap) {
  4283. /* uncharge swap account from the old cgroup */
  4284. if (!mem_cgroup_is_root(mc.from))
  4285. page_counter_uncharge(&mc.from->memsw, mc.moved_swap);
  4286. /*
  4287. * we charged both to->memory and to->memsw, so we
  4288. * should uncharge to->memory.
  4289. */
  4290. if (!mem_cgroup_is_root(mc.to))
  4291. page_counter_uncharge(&mc.to->memory, mc.moved_swap);
  4292. css_put_many(&mc.from->css, mc.moved_swap);
  4293. /* we've already done css_get(mc.to) */
  4294. mc.moved_swap = 0;
  4295. }
  4296. memcg_oom_recover(from);
  4297. memcg_oom_recover(to);
  4298. wake_up_all(&mc.waitq);
  4299. }
  4300. static void mem_cgroup_clear_mc(void)
  4301. {
  4302. /*
  4303. * we must clear moving_task before waking up waiters at the end of
  4304. * task migration.
  4305. */
  4306. mc.moving_task = NULL;
  4307. __mem_cgroup_clear_mc();
  4308. spin_lock(&mc.lock);
  4309. mc.from = NULL;
  4310. mc.to = NULL;
  4311. spin_unlock(&mc.lock);
  4312. }
  4313. static int mem_cgroup_can_attach(struct cgroup_subsys_state *css,
  4314. struct cgroup_taskset *tset)
  4315. {
  4316. struct task_struct *p = cgroup_taskset_first(tset);
  4317. int ret = 0;
  4318. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  4319. unsigned long move_flags;
  4320. /*
  4321. * We are now commited to this value whatever it is. Changes in this
  4322. * tunable will only affect upcoming migrations, not the current one.
  4323. * So we need to save it, and keep it going.
  4324. */
  4325. move_flags = READ_ONCE(memcg->move_charge_at_immigrate);
  4326. if (move_flags) {
  4327. struct mm_struct *mm;
  4328. struct mem_cgroup *from = mem_cgroup_from_task(p);
  4329. VM_BUG_ON(from == memcg);
  4330. mm = get_task_mm(p);
  4331. if (!mm)
  4332. return 0;
  4333. /* We move charges only when we move a owner of the mm */
  4334. if (mm->owner == p) {
  4335. VM_BUG_ON(mc.from);
  4336. VM_BUG_ON(mc.to);
  4337. VM_BUG_ON(mc.precharge);
  4338. VM_BUG_ON(mc.moved_charge);
  4339. VM_BUG_ON(mc.moved_swap);
  4340. spin_lock(&mc.lock);
  4341. mc.from = from;
  4342. mc.to = memcg;
  4343. mc.flags = move_flags;
  4344. spin_unlock(&mc.lock);
  4345. /* We set mc.moving_task later */
  4346. ret = mem_cgroup_precharge_mc(mm);
  4347. if (ret)
  4348. mem_cgroup_clear_mc();
  4349. }
  4350. mmput(mm);
  4351. }
  4352. return ret;
  4353. }
  4354. static void mem_cgroup_cancel_attach(struct cgroup_subsys_state *css,
  4355. struct cgroup_taskset *tset)
  4356. {
  4357. if (mc.to)
  4358. mem_cgroup_clear_mc();
  4359. }
  4360. static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
  4361. unsigned long addr, unsigned long end,
  4362. struct mm_walk *walk)
  4363. {
  4364. int ret = 0;
  4365. struct vm_area_struct *vma = walk->vma;
  4366. pte_t *pte;
  4367. spinlock_t *ptl;
  4368. enum mc_target_type target_type;
  4369. union mc_target target;
  4370. struct page *page;
  4371. /*
  4372. * We don't take compound_lock() here but no race with splitting thp
  4373. * happens because:
  4374. * - if pmd_trans_huge_lock() returns 1, the relevant thp is not
  4375. * under splitting, which means there's no concurrent thp split,
  4376. * - if another thread runs into split_huge_page() just after we
  4377. * entered this if-block, the thread must wait for page table lock
  4378. * to be unlocked in __split_huge_page_splitting(), where the main
  4379. * part of thp split is not executed yet.
  4380. */
  4381. if (pmd_trans_huge_lock(pmd, vma, &ptl) == 1) {
  4382. if (mc.precharge < HPAGE_PMD_NR) {
  4383. spin_unlock(ptl);
  4384. return 0;
  4385. }
  4386. target_type = get_mctgt_type_thp(vma, addr, *pmd, &target);
  4387. if (target_type == MC_TARGET_PAGE) {
  4388. page = target.page;
  4389. if (!isolate_lru_page(page)) {
  4390. if (!mem_cgroup_move_account(page, HPAGE_PMD_NR,
  4391. mc.from, mc.to)) {
  4392. mc.precharge -= HPAGE_PMD_NR;
  4393. mc.moved_charge += HPAGE_PMD_NR;
  4394. }
  4395. putback_lru_page(page);
  4396. }
  4397. put_page(page);
  4398. }
  4399. spin_unlock(ptl);
  4400. return 0;
  4401. }
  4402. if (pmd_trans_unstable(pmd))
  4403. return 0;
  4404. retry:
  4405. pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
  4406. for (; addr != end; addr += PAGE_SIZE) {
  4407. pte_t ptent = *(pte++);
  4408. swp_entry_t ent;
  4409. if (!mc.precharge)
  4410. break;
  4411. switch (get_mctgt_type(vma, addr, ptent, &target)) {
  4412. case MC_TARGET_PAGE:
  4413. page = target.page;
  4414. if (isolate_lru_page(page))
  4415. goto put;
  4416. if (!mem_cgroup_move_account(page, 1, mc.from, mc.to)) {
  4417. mc.precharge--;
  4418. /* we uncharge from mc.from later. */
  4419. mc.moved_charge++;
  4420. }
  4421. putback_lru_page(page);
  4422. put: /* get_mctgt_type() gets the page */
  4423. put_page(page);
  4424. break;
  4425. case MC_TARGET_SWAP:
  4426. ent = target.ent;
  4427. if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to)) {
  4428. mc.precharge--;
  4429. /* we fixup refcnts and charges later. */
  4430. mc.moved_swap++;
  4431. }
  4432. break;
  4433. default:
  4434. break;
  4435. }
  4436. }
  4437. pte_unmap_unlock(pte - 1, ptl);
  4438. cond_resched();
  4439. if (addr != end) {
  4440. /*
  4441. * We have consumed all precharges we got in can_attach().
  4442. * We try charge one by one, but don't do any additional
  4443. * charges to mc.to if we have failed in charge once in attach()
  4444. * phase.
  4445. */
  4446. ret = mem_cgroup_do_precharge(1);
  4447. if (!ret)
  4448. goto retry;
  4449. }
  4450. return ret;
  4451. }
  4452. static void mem_cgroup_move_charge(struct mm_struct *mm)
  4453. {
  4454. struct mm_walk mem_cgroup_move_charge_walk = {
  4455. .pmd_entry = mem_cgroup_move_charge_pte_range,
  4456. .mm = mm,
  4457. };
  4458. lru_add_drain_all();
  4459. /*
  4460. * Signal mem_cgroup_begin_page_stat() to take the memcg's
  4461. * move_lock while we're moving its pages to another memcg.
  4462. * Then wait for already started RCU-only updates to finish.
  4463. */
  4464. atomic_inc(&mc.from->moving_account);
  4465. synchronize_rcu();
  4466. retry:
  4467. if (unlikely(!down_read_trylock(&mm->mmap_sem))) {
  4468. /*
  4469. * Someone who are holding the mmap_sem might be waiting in
  4470. * waitq. So we cancel all extra charges, wake up all waiters,
  4471. * and retry. Because we cancel precharges, we might not be able
  4472. * to move enough charges, but moving charge is a best-effort
  4473. * feature anyway, so it wouldn't be a big problem.
  4474. */
  4475. __mem_cgroup_clear_mc();
  4476. cond_resched();
  4477. goto retry;
  4478. }
  4479. /*
  4480. * When we have consumed all precharges and failed in doing
  4481. * additional charge, the page walk just aborts.
  4482. */
  4483. walk_page_range(0, ~0UL, &mem_cgroup_move_charge_walk);
  4484. up_read(&mm->mmap_sem);
  4485. atomic_dec(&mc.from->moving_account);
  4486. }
  4487. static void mem_cgroup_move_task(struct cgroup_subsys_state *css,
  4488. struct cgroup_taskset *tset)
  4489. {
  4490. struct task_struct *p = cgroup_taskset_first(tset);
  4491. struct mm_struct *mm = get_task_mm(p);
  4492. if (mm) {
  4493. if (mc.to)
  4494. mem_cgroup_move_charge(mm);
  4495. mmput(mm);
  4496. }
  4497. if (mc.to)
  4498. mem_cgroup_clear_mc();
  4499. }
  4500. #else /* !CONFIG_MMU */
  4501. static int mem_cgroup_can_attach(struct cgroup_subsys_state *css,
  4502. struct cgroup_taskset *tset)
  4503. {
  4504. return 0;
  4505. }
  4506. static void mem_cgroup_cancel_attach(struct cgroup_subsys_state *css,
  4507. struct cgroup_taskset *tset)
  4508. {
  4509. }
  4510. static void mem_cgroup_move_task(struct cgroup_subsys_state *css,
  4511. struct cgroup_taskset *tset)
  4512. {
  4513. }
  4514. #endif
  4515. /*
  4516. * Cgroup retains root cgroups across [un]mount cycles making it necessary
  4517. * to verify whether we're attached to the default hierarchy on each mount
  4518. * attempt.
  4519. */
  4520. static void mem_cgroup_bind(struct cgroup_subsys_state *root_css)
  4521. {
  4522. /*
  4523. * use_hierarchy is forced on the default hierarchy. cgroup core
  4524. * guarantees that @root doesn't have any children, so turning it
  4525. * on for the root memcg is enough.
  4526. */
  4527. if (cgroup_on_dfl(root_css->cgroup))
  4528. root_mem_cgroup->use_hierarchy = true;
  4529. else
  4530. root_mem_cgroup->use_hierarchy = false;
  4531. }
  4532. static u64 memory_current_read(struct cgroup_subsys_state *css,
  4533. struct cftype *cft)
  4534. {
  4535. return mem_cgroup_usage(mem_cgroup_from_css(css), false);
  4536. }
  4537. static int memory_low_show(struct seq_file *m, void *v)
  4538. {
  4539. struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
  4540. unsigned long low = READ_ONCE(memcg->low);
  4541. if (low == PAGE_COUNTER_MAX)
  4542. seq_puts(m, "max\n");
  4543. else
  4544. seq_printf(m, "%llu\n", (u64)low * PAGE_SIZE);
  4545. return 0;
  4546. }
  4547. static ssize_t memory_low_write(struct kernfs_open_file *of,
  4548. char *buf, size_t nbytes, loff_t off)
  4549. {
  4550. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  4551. unsigned long low;
  4552. int err;
  4553. buf = strstrip(buf);
  4554. err = page_counter_memparse(buf, "max", &low);
  4555. if (err)
  4556. return err;
  4557. memcg->low = low;
  4558. return nbytes;
  4559. }
  4560. static int memory_high_show(struct seq_file *m, void *v)
  4561. {
  4562. struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
  4563. unsigned long high = READ_ONCE(memcg->high);
  4564. if (high == PAGE_COUNTER_MAX)
  4565. seq_puts(m, "max\n");
  4566. else
  4567. seq_printf(m, "%llu\n", (u64)high * PAGE_SIZE);
  4568. return 0;
  4569. }
  4570. static ssize_t memory_high_write(struct kernfs_open_file *of,
  4571. char *buf, size_t nbytes, loff_t off)
  4572. {
  4573. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  4574. unsigned long high;
  4575. int err;
  4576. buf = strstrip(buf);
  4577. err = page_counter_memparse(buf, "max", &high);
  4578. if (err)
  4579. return err;
  4580. memcg->high = high;
  4581. return nbytes;
  4582. }
  4583. static int memory_max_show(struct seq_file *m, void *v)
  4584. {
  4585. struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
  4586. unsigned long max = READ_ONCE(memcg->memory.limit);
  4587. if (max == PAGE_COUNTER_MAX)
  4588. seq_puts(m, "max\n");
  4589. else
  4590. seq_printf(m, "%llu\n", (u64)max * PAGE_SIZE);
  4591. return 0;
  4592. }
  4593. static ssize_t memory_max_write(struct kernfs_open_file *of,
  4594. char *buf, size_t nbytes, loff_t off)
  4595. {
  4596. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  4597. unsigned long max;
  4598. int err;
  4599. buf = strstrip(buf);
  4600. err = page_counter_memparse(buf, "max", &max);
  4601. if (err)
  4602. return err;
  4603. err = mem_cgroup_resize_limit(memcg, max);
  4604. if (err)
  4605. return err;
  4606. return nbytes;
  4607. }
  4608. static int memory_events_show(struct seq_file *m, void *v)
  4609. {
  4610. struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
  4611. seq_printf(m, "low %lu\n", mem_cgroup_read_events(memcg, MEMCG_LOW));
  4612. seq_printf(m, "high %lu\n", mem_cgroup_read_events(memcg, MEMCG_HIGH));
  4613. seq_printf(m, "max %lu\n", mem_cgroup_read_events(memcg, MEMCG_MAX));
  4614. seq_printf(m, "oom %lu\n", mem_cgroup_read_events(memcg, MEMCG_OOM));
  4615. return 0;
  4616. }
  4617. static struct cftype memory_files[] = {
  4618. {
  4619. .name = "current",
  4620. .read_u64 = memory_current_read,
  4621. },
  4622. {
  4623. .name = "low",
  4624. .flags = CFTYPE_NOT_ON_ROOT,
  4625. .seq_show = memory_low_show,
  4626. .write = memory_low_write,
  4627. },
  4628. {
  4629. .name = "high",
  4630. .flags = CFTYPE_NOT_ON_ROOT,
  4631. .seq_show = memory_high_show,
  4632. .write = memory_high_write,
  4633. },
  4634. {
  4635. .name = "max",
  4636. .flags = CFTYPE_NOT_ON_ROOT,
  4637. .seq_show = memory_max_show,
  4638. .write = memory_max_write,
  4639. },
  4640. {
  4641. .name = "events",
  4642. .flags = CFTYPE_NOT_ON_ROOT,
  4643. .seq_show = memory_events_show,
  4644. },
  4645. { } /* terminate */
  4646. };
  4647. struct cgroup_subsys memory_cgrp_subsys = {
  4648. .css_alloc = mem_cgroup_css_alloc,
  4649. .css_online = mem_cgroup_css_online,
  4650. .css_offline = mem_cgroup_css_offline,
  4651. .css_free = mem_cgroup_css_free,
  4652. .css_reset = mem_cgroup_css_reset,
  4653. .can_attach = mem_cgroup_can_attach,
  4654. .cancel_attach = mem_cgroup_cancel_attach,
  4655. .attach = mem_cgroup_move_task,
  4656. .bind = mem_cgroup_bind,
  4657. .dfl_cftypes = memory_files,
  4658. .legacy_cftypes = mem_cgroup_legacy_files,
  4659. .early_init = 0,
  4660. };
  4661. /**
  4662. * mem_cgroup_events - count memory events against a cgroup
  4663. * @memcg: the memory cgroup
  4664. * @idx: the event index
  4665. * @nr: the number of events to account for
  4666. */
  4667. void mem_cgroup_events(struct mem_cgroup *memcg,
  4668. enum mem_cgroup_events_index idx,
  4669. unsigned int nr)
  4670. {
  4671. this_cpu_add(memcg->stat->events[idx], nr);
  4672. }
  4673. /**
  4674. * mem_cgroup_low - check if memory consumption is below the normal range
  4675. * @root: the highest ancestor to consider
  4676. * @memcg: the memory cgroup to check
  4677. *
  4678. * Returns %true if memory consumption of @memcg, and that of all
  4679. * configurable ancestors up to @root, is below the normal range.
  4680. */
  4681. bool mem_cgroup_low(struct mem_cgroup *root, struct mem_cgroup *memcg)
  4682. {
  4683. if (mem_cgroup_disabled())
  4684. return false;
  4685. /*
  4686. * The toplevel group doesn't have a configurable range, so
  4687. * it's never low when looked at directly, and it is not
  4688. * considered an ancestor when assessing the hierarchy.
  4689. */
  4690. if (memcg == root_mem_cgroup)
  4691. return false;
  4692. if (page_counter_read(&memcg->memory) >= memcg->low)
  4693. return false;
  4694. while (memcg != root) {
  4695. memcg = parent_mem_cgroup(memcg);
  4696. if (memcg == root_mem_cgroup)
  4697. break;
  4698. if (page_counter_read(&memcg->memory) >= memcg->low)
  4699. return false;
  4700. }
  4701. return true;
  4702. }
  4703. /**
  4704. * mem_cgroup_try_charge - try charging a page
  4705. * @page: page to charge
  4706. * @mm: mm context of the victim
  4707. * @gfp_mask: reclaim mode
  4708. * @memcgp: charged memcg return
  4709. *
  4710. * Try to charge @page to the memcg that @mm belongs to, reclaiming
  4711. * pages according to @gfp_mask if necessary.
  4712. *
  4713. * Returns 0 on success, with *@memcgp pointing to the charged memcg.
  4714. * Otherwise, an error code is returned.
  4715. *
  4716. * After page->mapping has been set up, the caller must finalize the
  4717. * charge with mem_cgroup_commit_charge(). Or abort the transaction
  4718. * with mem_cgroup_cancel_charge() in case page instantiation fails.
  4719. */
  4720. int mem_cgroup_try_charge(struct page *page, struct mm_struct *mm,
  4721. gfp_t gfp_mask, struct mem_cgroup **memcgp)
  4722. {
  4723. struct mem_cgroup *memcg = NULL;
  4724. unsigned int nr_pages = 1;
  4725. int ret = 0;
  4726. if (mem_cgroup_disabled())
  4727. goto out;
  4728. if (PageSwapCache(page)) {
  4729. /*
  4730. * Every swap fault against a single page tries to charge the
  4731. * page, bail as early as possible. shmem_unuse() encounters
  4732. * already charged pages, too. The USED bit is protected by
  4733. * the page lock, which serializes swap cache removal, which
  4734. * in turn serializes uncharging.
  4735. */
  4736. if (page->mem_cgroup)
  4737. goto out;
  4738. }
  4739. if (PageTransHuge(page)) {
  4740. nr_pages <<= compound_order(page);
  4741. VM_BUG_ON_PAGE(!PageTransHuge(page), page);
  4742. }
  4743. if (do_swap_account && PageSwapCache(page))
  4744. memcg = try_get_mem_cgroup_from_page(page);
  4745. if (!memcg)
  4746. memcg = get_mem_cgroup_from_mm(mm);
  4747. ret = try_charge(memcg, gfp_mask, nr_pages);
  4748. css_put(&memcg->css);
  4749. if (ret == -EINTR) {
  4750. memcg = root_mem_cgroup;
  4751. ret = 0;
  4752. }
  4753. out:
  4754. *memcgp = memcg;
  4755. return ret;
  4756. }
  4757. /**
  4758. * mem_cgroup_commit_charge - commit a page charge
  4759. * @page: page to charge
  4760. * @memcg: memcg to charge the page to
  4761. * @lrucare: page might be on LRU already
  4762. *
  4763. * Finalize a charge transaction started by mem_cgroup_try_charge(),
  4764. * after page->mapping has been set up. This must happen atomically
  4765. * as part of the page instantiation, i.e. under the page table lock
  4766. * for anonymous pages, under the page lock for page and swap cache.
  4767. *
  4768. * In addition, the page must not be on the LRU during the commit, to
  4769. * prevent racing with task migration. If it might be, use @lrucare.
  4770. *
  4771. * Use mem_cgroup_cancel_charge() to cancel the transaction instead.
  4772. */
  4773. void mem_cgroup_commit_charge(struct page *page, struct mem_cgroup *memcg,
  4774. bool lrucare)
  4775. {
  4776. unsigned int nr_pages = 1;
  4777. VM_BUG_ON_PAGE(!page->mapping, page);
  4778. VM_BUG_ON_PAGE(PageLRU(page) && !lrucare, page);
  4779. if (mem_cgroup_disabled())
  4780. return;
  4781. /*
  4782. * Swap faults will attempt to charge the same page multiple
  4783. * times. But reuse_swap_page() might have removed the page
  4784. * from swapcache already, so we can't check PageSwapCache().
  4785. */
  4786. if (!memcg)
  4787. return;
  4788. commit_charge(page, memcg, lrucare);
  4789. if (PageTransHuge(page)) {
  4790. nr_pages <<= compound_order(page);
  4791. VM_BUG_ON_PAGE(!PageTransHuge(page), page);
  4792. }
  4793. local_irq_disable();
  4794. mem_cgroup_charge_statistics(memcg, page, nr_pages);
  4795. memcg_check_events(memcg, page);
  4796. local_irq_enable();
  4797. if (do_swap_account && PageSwapCache(page)) {
  4798. swp_entry_t entry = { .val = page_private(page) };
  4799. /*
  4800. * The swap entry might not get freed for a long time,
  4801. * let's not wait for it. The page already received a
  4802. * memory+swap charge, drop the swap entry duplicate.
  4803. */
  4804. mem_cgroup_uncharge_swap(entry);
  4805. }
  4806. }
  4807. /**
  4808. * mem_cgroup_cancel_charge - cancel a page charge
  4809. * @page: page to charge
  4810. * @memcg: memcg to charge the page to
  4811. *
  4812. * Cancel a charge transaction started by mem_cgroup_try_charge().
  4813. */
  4814. void mem_cgroup_cancel_charge(struct page *page, struct mem_cgroup *memcg)
  4815. {
  4816. unsigned int nr_pages = 1;
  4817. if (mem_cgroup_disabled())
  4818. return;
  4819. /*
  4820. * Swap faults will attempt to charge the same page multiple
  4821. * times. But reuse_swap_page() might have removed the page
  4822. * from swapcache already, so we can't check PageSwapCache().
  4823. */
  4824. if (!memcg)
  4825. return;
  4826. if (PageTransHuge(page)) {
  4827. nr_pages <<= compound_order(page);
  4828. VM_BUG_ON_PAGE(!PageTransHuge(page), page);
  4829. }
  4830. cancel_charge(memcg, nr_pages);
  4831. }
  4832. static void uncharge_batch(struct mem_cgroup *memcg, unsigned long pgpgout,
  4833. unsigned long nr_anon, unsigned long nr_file,
  4834. unsigned long nr_huge, struct page *dummy_page)
  4835. {
  4836. unsigned long nr_pages = nr_anon + nr_file;
  4837. unsigned long flags;
  4838. if (!mem_cgroup_is_root(memcg)) {
  4839. page_counter_uncharge(&memcg->memory, nr_pages);
  4840. if (do_swap_account)
  4841. page_counter_uncharge(&memcg->memsw, nr_pages);
  4842. memcg_oom_recover(memcg);
  4843. }
  4844. local_irq_save(flags);
  4845. __this_cpu_sub(memcg->stat->count[MEM_CGROUP_STAT_RSS], nr_anon);
  4846. __this_cpu_sub(memcg->stat->count[MEM_CGROUP_STAT_CACHE], nr_file);
  4847. __this_cpu_sub(memcg->stat->count[MEM_CGROUP_STAT_RSS_HUGE], nr_huge);
  4848. __this_cpu_add(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGOUT], pgpgout);
  4849. __this_cpu_add(memcg->stat->nr_page_events, nr_pages);
  4850. memcg_check_events(memcg, dummy_page);
  4851. local_irq_restore(flags);
  4852. if (!mem_cgroup_is_root(memcg))
  4853. css_put_many(&memcg->css, nr_pages);
  4854. }
  4855. static void uncharge_list(struct list_head *page_list)
  4856. {
  4857. struct mem_cgroup *memcg = NULL;
  4858. unsigned long nr_anon = 0;
  4859. unsigned long nr_file = 0;
  4860. unsigned long nr_huge = 0;
  4861. unsigned long pgpgout = 0;
  4862. struct list_head *next;
  4863. struct page *page;
  4864. next = page_list->next;
  4865. do {
  4866. unsigned int nr_pages = 1;
  4867. page = list_entry(next, struct page, lru);
  4868. next = page->lru.next;
  4869. VM_BUG_ON_PAGE(PageLRU(page), page);
  4870. VM_BUG_ON_PAGE(page_count(page), page);
  4871. if (!page->mem_cgroup)
  4872. continue;
  4873. /*
  4874. * Nobody should be changing or seriously looking at
  4875. * page->mem_cgroup at this point, we have fully
  4876. * exclusive access to the page.
  4877. */
  4878. if (memcg != page->mem_cgroup) {
  4879. if (memcg) {
  4880. uncharge_batch(memcg, pgpgout, nr_anon, nr_file,
  4881. nr_huge, page);
  4882. pgpgout = nr_anon = nr_file = nr_huge = 0;
  4883. }
  4884. memcg = page->mem_cgroup;
  4885. }
  4886. if (PageTransHuge(page)) {
  4887. nr_pages <<= compound_order(page);
  4888. VM_BUG_ON_PAGE(!PageTransHuge(page), page);
  4889. nr_huge += nr_pages;
  4890. }
  4891. if (PageAnon(page))
  4892. nr_anon += nr_pages;
  4893. else
  4894. nr_file += nr_pages;
  4895. page->mem_cgroup = NULL;
  4896. pgpgout++;
  4897. } while (next != page_list);
  4898. if (memcg)
  4899. uncharge_batch(memcg, pgpgout, nr_anon, nr_file,
  4900. nr_huge, page);
  4901. }
  4902. /**
  4903. * mem_cgroup_uncharge - uncharge a page
  4904. * @page: page to uncharge
  4905. *
  4906. * Uncharge a page previously charged with mem_cgroup_try_charge() and
  4907. * mem_cgroup_commit_charge().
  4908. */
  4909. void mem_cgroup_uncharge(struct page *page)
  4910. {
  4911. if (mem_cgroup_disabled())
  4912. return;
  4913. /* Don't touch page->lru of any random page, pre-check: */
  4914. if (!page->mem_cgroup)
  4915. return;
  4916. INIT_LIST_HEAD(&page->lru);
  4917. uncharge_list(&page->lru);
  4918. }
  4919. /**
  4920. * mem_cgroup_uncharge_list - uncharge a list of page
  4921. * @page_list: list of pages to uncharge
  4922. *
  4923. * Uncharge a list of pages previously charged with
  4924. * mem_cgroup_try_charge() and mem_cgroup_commit_charge().
  4925. */
  4926. void mem_cgroup_uncharge_list(struct list_head *page_list)
  4927. {
  4928. if (mem_cgroup_disabled())
  4929. return;
  4930. if (!list_empty(page_list))
  4931. uncharge_list(page_list);
  4932. }
  4933. /**
  4934. * mem_cgroup_migrate - migrate a charge to another page
  4935. * @oldpage: currently charged page
  4936. * @newpage: page to transfer the charge to
  4937. * @lrucare: either or both pages might be on the LRU already
  4938. *
  4939. * Migrate the charge from @oldpage to @newpage.
  4940. *
  4941. * Both pages must be locked, @newpage->mapping must be set up.
  4942. */
  4943. void mem_cgroup_migrate(struct page *oldpage, struct page *newpage,
  4944. bool lrucare)
  4945. {
  4946. struct mem_cgroup *memcg;
  4947. int isolated;
  4948. VM_BUG_ON_PAGE(!PageLocked(oldpage), oldpage);
  4949. VM_BUG_ON_PAGE(!PageLocked(newpage), newpage);
  4950. VM_BUG_ON_PAGE(!lrucare && PageLRU(oldpage), oldpage);
  4951. VM_BUG_ON_PAGE(!lrucare && PageLRU(newpage), newpage);
  4952. VM_BUG_ON_PAGE(PageAnon(oldpage) != PageAnon(newpage), newpage);
  4953. VM_BUG_ON_PAGE(PageTransHuge(oldpage) != PageTransHuge(newpage),
  4954. newpage);
  4955. if (mem_cgroup_disabled())
  4956. return;
  4957. /* Page cache replacement: new page already charged? */
  4958. if (newpage->mem_cgroup)
  4959. return;
  4960. /*
  4961. * Swapcache readahead pages can get migrated before being
  4962. * charged, and migration from compaction can happen to an
  4963. * uncharged page when the PFN walker finds a page that
  4964. * reclaim just put back on the LRU but has not released yet.
  4965. */
  4966. memcg = oldpage->mem_cgroup;
  4967. if (!memcg)
  4968. return;
  4969. if (lrucare)
  4970. lock_page_lru(oldpage, &isolated);
  4971. oldpage->mem_cgroup = NULL;
  4972. if (lrucare)
  4973. unlock_page_lru(oldpage, isolated);
  4974. commit_charge(newpage, memcg, lrucare);
  4975. }
  4976. /*
  4977. * subsys_initcall() for memory controller.
  4978. *
  4979. * Some parts like hotcpu_notifier() have to be initialized from this context
  4980. * because of lock dependencies (cgroup_lock -> cpu hotplug) but basically
  4981. * everything that doesn't depend on a specific mem_cgroup structure should
  4982. * be initialized from here.
  4983. */
  4984. static int __init mem_cgroup_init(void)
  4985. {
  4986. int cpu, node;
  4987. hotcpu_notifier(memcg_cpu_hotplug_callback, 0);
  4988. for_each_possible_cpu(cpu)
  4989. INIT_WORK(&per_cpu_ptr(&memcg_stock, cpu)->work,
  4990. drain_local_stock);
  4991. for_each_node(node) {
  4992. struct mem_cgroup_tree_per_node *rtpn;
  4993. int zone;
  4994. rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL,
  4995. node_online(node) ? node : NUMA_NO_NODE);
  4996. for (zone = 0; zone < MAX_NR_ZONES; zone++) {
  4997. struct mem_cgroup_tree_per_zone *rtpz;
  4998. rtpz = &rtpn->rb_tree_per_zone[zone];
  4999. rtpz->rb_root = RB_ROOT;
  5000. spin_lock_init(&rtpz->lock);
  5001. }
  5002. soft_limit_tree.rb_tree_per_node[node] = rtpn;
  5003. }
  5004. return 0;
  5005. }
  5006. subsys_initcall(mem_cgroup_init);
  5007. #ifdef CONFIG_MEMCG_SWAP
  5008. /**
  5009. * mem_cgroup_swapout - transfer a memsw charge to swap
  5010. * @page: page whose memsw charge to transfer
  5011. * @entry: swap entry to move the charge to
  5012. *
  5013. * Transfer the memsw charge of @page to @entry.
  5014. */
  5015. void mem_cgroup_swapout(struct page *page, swp_entry_t entry)
  5016. {
  5017. struct mem_cgroup *memcg;
  5018. unsigned short oldid;
  5019. VM_BUG_ON_PAGE(PageLRU(page), page);
  5020. VM_BUG_ON_PAGE(page_count(page), page);
  5021. if (!do_swap_account)
  5022. return;
  5023. memcg = page->mem_cgroup;
  5024. /* Readahead page, never charged */
  5025. if (!memcg)
  5026. return;
  5027. oldid = swap_cgroup_record(entry, mem_cgroup_id(memcg));
  5028. VM_BUG_ON_PAGE(oldid, page);
  5029. mem_cgroup_swap_statistics(memcg, true);
  5030. page->mem_cgroup = NULL;
  5031. if (!mem_cgroup_is_root(memcg))
  5032. page_counter_uncharge(&memcg->memory, 1);
  5033. /* Caller disabled preemption with mapping->tree_lock */
  5034. mem_cgroup_charge_statistics(memcg, page, -1);
  5035. memcg_check_events(memcg, page);
  5036. }
  5037. /**
  5038. * mem_cgroup_uncharge_swap - uncharge a swap entry
  5039. * @entry: swap entry to uncharge
  5040. *
  5041. * Drop the memsw charge associated with @entry.
  5042. */
  5043. void mem_cgroup_uncharge_swap(swp_entry_t entry)
  5044. {
  5045. struct mem_cgroup *memcg;
  5046. unsigned short id;
  5047. if (!do_swap_account)
  5048. return;
  5049. id = swap_cgroup_record(entry, 0);
  5050. rcu_read_lock();
  5051. memcg = mem_cgroup_from_id(id);
  5052. if (memcg) {
  5053. if (!mem_cgroup_is_root(memcg))
  5054. page_counter_uncharge(&memcg->memsw, 1);
  5055. mem_cgroup_swap_statistics(memcg, false);
  5056. css_put(&memcg->css);
  5057. }
  5058. rcu_read_unlock();
  5059. }
  5060. /* for remember boot option*/
  5061. #ifdef CONFIG_MEMCG_SWAP_ENABLED
  5062. static int really_do_swap_account __initdata = 1;
  5063. #else
  5064. static int really_do_swap_account __initdata;
  5065. #endif
  5066. static int __init enable_swap_account(char *s)
  5067. {
  5068. if (!strcmp(s, "1"))
  5069. really_do_swap_account = 1;
  5070. else if (!strcmp(s, "0"))
  5071. really_do_swap_account = 0;
  5072. return 1;
  5073. }
  5074. __setup("swapaccount=", enable_swap_account);
  5075. static struct cftype memsw_cgroup_files[] = {
  5076. {
  5077. .name = "memsw.usage_in_bytes",
  5078. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
  5079. .read_u64 = mem_cgroup_read_u64,
  5080. },
  5081. {
  5082. .name = "memsw.max_usage_in_bytes",
  5083. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
  5084. .write = mem_cgroup_reset,
  5085. .read_u64 = mem_cgroup_read_u64,
  5086. },
  5087. {
  5088. .name = "memsw.limit_in_bytes",
  5089. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
  5090. .write = mem_cgroup_write,
  5091. .read_u64 = mem_cgroup_read_u64,
  5092. },
  5093. {
  5094. .name = "memsw.failcnt",
  5095. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
  5096. .write = mem_cgroup_reset,
  5097. .read_u64 = mem_cgroup_read_u64,
  5098. },
  5099. { }, /* terminate */
  5100. };
  5101. static int __init mem_cgroup_swap_init(void)
  5102. {
  5103. if (!mem_cgroup_disabled() && really_do_swap_account) {
  5104. do_swap_account = 1;
  5105. WARN_ON(cgroup_add_legacy_cftypes(&memory_cgrp_subsys,
  5106. memsw_cgroup_files));
  5107. }
  5108. return 0;
  5109. }
  5110. subsys_initcall(mem_cgroup_swap_init);
  5111. #endif /* CONFIG_MEMCG_SWAP */