memcontrol.c 145 KB

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