memcontrol.c 145 KB

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