memcontrol.c 142 KB

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