memcontrol.c 146 KB

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