memcontrol.c 145 KB

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