memcontrol.c 145 KB

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