memcontrol.c 145 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679
  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. int lock_count = -1;
  1608. struct mem_cgroup *iter, *failed = NULL;
  1609. bool cond = true;
  1610. for_each_mem_cgroup_tree_cond(iter, mem, cond) {
  1611. bool locked = iter->oom_lock;
  1612. iter->oom_lock = true;
  1613. if (lock_count == -1)
  1614. lock_count = iter->oom_lock;
  1615. else if (lock_count != locked) {
  1616. /*
  1617. * this subtree of our hierarchy is already locked
  1618. * so we cannot give a lock.
  1619. */
  1620. lock_count = 0;
  1621. failed = iter;
  1622. cond = false;
  1623. }
  1624. }
  1625. if (!failed)
  1626. goto done;
  1627. /*
  1628. * OK, we failed to lock the whole subtree so we have to clean up
  1629. * what we set up to the failing subtree
  1630. */
  1631. cond = true;
  1632. for_each_mem_cgroup_tree_cond(iter, mem, cond) {
  1633. if (iter == failed) {
  1634. cond = false;
  1635. continue;
  1636. }
  1637. iter->oom_lock = false;
  1638. }
  1639. done:
  1640. return lock_count;
  1641. }
  1642. /*
  1643. * Has to be called with memcg_oom_lock
  1644. */
  1645. static int mem_cgroup_oom_unlock(struct mem_cgroup *mem)
  1646. {
  1647. struct mem_cgroup *iter;
  1648. for_each_mem_cgroup_tree(iter, mem)
  1649. iter->oom_lock = false;
  1650. return 0;
  1651. }
  1652. static void mem_cgroup_mark_under_oom(struct mem_cgroup *mem)
  1653. {
  1654. struct mem_cgroup *iter;
  1655. for_each_mem_cgroup_tree(iter, mem)
  1656. atomic_inc(&iter->under_oom);
  1657. }
  1658. static void mem_cgroup_unmark_under_oom(struct mem_cgroup *mem)
  1659. {
  1660. struct mem_cgroup *iter;
  1661. /*
  1662. * When a new child is created while the hierarchy is under oom,
  1663. * mem_cgroup_oom_lock() may not be called. We have to use
  1664. * atomic_add_unless() here.
  1665. */
  1666. for_each_mem_cgroup_tree(iter, mem)
  1667. atomic_add_unless(&iter->under_oom, -1, 0);
  1668. }
  1669. static DEFINE_SPINLOCK(memcg_oom_lock);
  1670. static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
  1671. struct oom_wait_info {
  1672. struct mem_cgroup *mem;
  1673. wait_queue_t wait;
  1674. };
  1675. static int memcg_oom_wake_function(wait_queue_t *wait,
  1676. unsigned mode, int sync, void *arg)
  1677. {
  1678. struct mem_cgroup *wake_mem = (struct mem_cgroup *)arg,
  1679. *oom_wait_mem;
  1680. struct oom_wait_info *oom_wait_info;
  1681. oom_wait_info = container_of(wait, struct oom_wait_info, wait);
  1682. oom_wait_mem = oom_wait_info->mem;
  1683. /*
  1684. * Both of oom_wait_info->mem and wake_mem are stable under us.
  1685. * Then we can use css_is_ancestor without taking care of RCU.
  1686. */
  1687. if (!mem_cgroup_same_or_subtree(oom_wait_mem, wake_mem)
  1688. && !mem_cgroup_same_or_subtree(wake_mem, oom_wait_mem))
  1689. return 0;
  1690. return autoremove_wake_function(wait, mode, sync, arg);
  1691. }
  1692. static void memcg_wakeup_oom(struct mem_cgroup *mem)
  1693. {
  1694. /* for filtering, pass "mem" as argument. */
  1695. __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, mem);
  1696. }
  1697. static void memcg_oom_recover(struct mem_cgroup *mem)
  1698. {
  1699. if (mem && atomic_read(&mem->under_oom))
  1700. memcg_wakeup_oom(mem);
  1701. }
  1702. /*
  1703. * try to call OOM killer. returns false if we should exit memory-reclaim loop.
  1704. */
  1705. bool mem_cgroup_handle_oom(struct mem_cgroup *mem, gfp_t mask)
  1706. {
  1707. struct oom_wait_info owait;
  1708. bool locked, need_to_kill;
  1709. owait.mem = mem;
  1710. owait.wait.flags = 0;
  1711. owait.wait.func = memcg_oom_wake_function;
  1712. owait.wait.private = current;
  1713. INIT_LIST_HEAD(&owait.wait.task_list);
  1714. need_to_kill = true;
  1715. mem_cgroup_mark_under_oom(mem);
  1716. /* At first, try to OOM lock hierarchy under mem.*/
  1717. spin_lock(&memcg_oom_lock);
  1718. locked = mem_cgroup_oom_lock(mem);
  1719. /*
  1720. * Even if signal_pending(), we can't quit charge() loop without
  1721. * accounting. So, UNINTERRUPTIBLE is appropriate. But SIGKILL
  1722. * under OOM is always welcomed, use TASK_KILLABLE here.
  1723. */
  1724. prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
  1725. if (!locked || mem->oom_kill_disable)
  1726. need_to_kill = false;
  1727. if (locked)
  1728. mem_cgroup_oom_notify(mem);
  1729. spin_unlock(&memcg_oom_lock);
  1730. if (need_to_kill) {
  1731. finish_wait(&memcg_oom_waitq, &owait.wait);
  1732. mem_cgroup_out_of_memory(mem, mask);
  1733. } else {
  1734. schedule();
  1735. finish_wait(&memcg_oom_waitq, &owait.wait);
  1736. }
  1737. spin_lock(&memcg_oom_lock);
  1738. if (locked)
  1739. mem_cgroup_oom_unlock(mem);
  1740. memcg_wakeup_oom(mem);
  1741. spin_unlock(&memcg_oom_lock);
  1742. mem_cgroup_unmark_under_oom(mem);
  1743. if (test_thread_flag(TIF_MEMDIE) || fatal_signal_pending(current))
  1744. return false;
  1745. /* Give chance to dying process */
  1746. schedule_timeout(1);
  1747. return true;
  1748. }
  1749. /*
  1750. * Currently used to update mapped file statistics, but the routine can be
  1751. * generalized to update other statistics as well.
  1752. *
  1753. * Notes: Race condition
  1754. *
  1755. * We usually use page_cgroup_lock() for accessing page_cgroup member but
  1756. * it tends to be costly. But considering some conditions, we doesn't need
  1757. * to do so _always_.
  1758. *
  1759. * Considering "charge", lock_page_cgroup() is not required because all
  1760. * file-stat operations happen after a page is attached to radix-tree. There
  1761. * are no race with "charge".
  1762. *
  1763. * Considering "uncharge", we know that memcg doesn't clear pc->mem_cgroup
  1764. * at "uncharge" intentionally. So, we always see valid pc->mem_cgroup even
  1765. * if there are race with "uncharge". Statistics itself is properly handled
  1766. * by flags.
  1767. *
  1768. * Considering "move", this is an only case we see a race. To make the race
  1769. * small, we check MEM_CGROUP_ON_MOVE percpu value and detect there are
  1770. * possibility of race condition. If there is, we take a lock.
  1771. */
  1772. void mem_cgroup_update_page_stat(struct page *page,
  1773. enum mem_cgroup_page_stat_item idx, int val)
  1774. {
  1775. struct mem_cgroup *mem;
  1776. struct page_cgroup *pc = lookup_page_cgroup(page);
  1777. bool need_unlock = false;
  1778. unsigned long uninitialized_var(flags);
  1779. if (unlikely(!pc))
  1780. return;
  1781. rcu_read_lock();
  1782. mem = pc->mem_cgroup;
  1783. if (unlikely(!mem || !PageCgroupUsed(pc)))
  1784. goto out;
  1785. /* pc->mem_cgroup is unstable ? */
  1786. if (unlikely(mem_cgroup_stealed(mem)) || PageTransHuge(page)) {
  1787. /* take a lock against to access pc->mem_cgroup */
  1788. move_lock_page_cgroup(pc, &flags);
  1789. need_unlock = true;
  1790. mem = pc->mem_cgroup;
  1791. if (!mem || !PageCgroupUsed(pc))
  1792. goto out;
  1793. }
  1794. switch (idx) {
  1795. case MEMCG_NR_FILE_MAPPED:
  1796. if (val > 0)
  1797. SetPageCgroupFileMapped(pc);
  1798. else if (!page_mapped(page))
  1799. ClearPageCgroupFileMapped(pc);
  1800. idx = MEM_CGROUP_STAT_FILE_MAPPED;
  1801. break;
  1802. default:
  1803. BUG();
  1804. }
  1805. this_cpu_add(mem->stat->count[idx], val);
  1806. out:
  1807. if (unlikely(need_unlock))
  1808. move_unlock_page_cgroup(pc, &flags);
  1809. rcu_read_unlock();
  1810. return;
  1811. }
  1812. EXPORT_SYMBOL(mem_cgroup_update_page_stat);
  1813. /*
  1814. * size of first charge trial. "32" comes from vmscan.c's magic value.
  1815. * TODO: maybe necessary to use big numbers in big irons.
  1816. */
  1817. #define CHARGE_BATCH 32U
  1818. struct memcg_stock_pcp {
  1819. struct mem_cgroup *cached; /* this never be root cgroup */
  1820. unsigned int nr_pages;
  1821. struct work_struct work;
  1822. unsigned long flags;
  1823. #define FLUSHING_CACHED_CHARGE (0)
  1824. };
  1825. static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
  1826. static DEFINE_MUTEX(percpu_charge_mutex);
  1827. /*
  1828. * Try to consume stocked charge on this cpu. If success, one page is consumed
  1829. * from local stock and true is returned. If the stock is 0 or charges from a
  1830. * cgroup which is not current target, returns false. This stock will be
  1831. * refilled.
  1832. */
  1833. static bool consume_stock(struct mem_cgroup *mem)
  1834. {
  1835. struct memcg_stock_pcp *stock;
  1836. bool ret = true;
  1837. stock = &get_cpu_var(memcg_stock);
  1838. if (mem == stock->cached && stock->nr_pages)
  1839. stock->nr_pages--;
  1840. else /* need to call res_counter_charge */
  1841. ret = false;
  1842. put_cpu_var(memcg_stock);
  1843. return ret;
  1844. }
  1845. /*
  1846. * Returns stocks cached in percpu to res_counter and reset cached information.
  1847. */
  1848. static void drain_stock(struct memcg_stock_pcp *stock)
  1849. {
  1850. struct mem_cgroup *old = stock->cached;
  1851. if (stock->nr_pages) {
  1852. unsigned long bytes = stock->nr_pages * PAGE_SIZE;
  1853. res_counter_uncharge(&old->res, bytes);
  1854. if (do_swap_account)
  1855. res_counter_uncharge(&old->memsw, bytes);
  1856. stock->nr_pages = 0;
  1857. }
  1858. stock->cached = NULL;
  1859. }
  1860. /*
  1861. * This must be called under preempt disabled or must be called by
  1862. * a thread which is pinned to local cpu.
  1863. */
  1864. static void drain_local_stock(struct work_struct *dummy)
  1865. {
  1866. struct memcg_stock_pcp *stock = &__get_cpu_var(memcg_stock);
  1867. drain_stock(stock);
  1868. clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
  1869. }
  1870. /*
  1871. * Cache charges(val) which is from res_counter, to local per_cpu area.
  1872. * This will be consumed by consume_stock() function, later.
  1873. */
  1874. static void refill_stock(struct mem_cgroup *mem, unsigned int nr_pages)
  1875. {
  1876. struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock);
  1877. if (stock->cached != mem) { /* reset if necessary */
  1878. drain_stock(stock);
  1879. stock->cached = mem;
  1880. }
  1881. stock->nr_pages += nr_pages;
  1882. put_cpu_var(memcg_stock);
  1883. }
  1884. /*
  1885. * Drains all per-CPU charge caches for given root_mem resp. subtree
  1886. * of the hierarchy under it. sync flag says whether we should block
  1887. * until the work is done.
  1888. */
  1889. static void drain_all_stock(struct mem_cgroup *root_mem, bool sync)
  1890. {
  1891. int cpu, curcpu;
  1892. /* Notify other cpus that system-wide "drain" is running */
  1893. get_online_cpus();
  1894. /*
  1895. * Get a hint for avoiding draining charges on the current cpu,
  1896. * which must be exhausted by our charging. It is not required that
  1897. * this be a precise check, so we use raw_smp_processor_id() instead of
  1898. * getcpu()/putcpu().
  1899. */
  1900. curcpu = raw_smp_processor_id();
  1901. for_each_online_cpu(cpu) {
  1902. struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
  1903. struct mem_cgroup *mem;
  1904. mem = stock->cached;
  1905. if (!mem || !stock->nr_pages)
  1906. continue;
  1907. if (!mem_cgroup_same_or_subtree(root_mem, mem))
  1908. continue;
  1909. if (!test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
  1910. if (cpu == curcpu)
  1911. drain_local_stock(&stock->work);
  1912. else
  1913. schedule_work_on(cpu, &stock->work);
  1914. }
  1915. }
  1916. if (!sync)
  1917. goto out;
  1918. for_each_online_cpu(cpu) {
  1919. struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
  1920. if (test_bit(FLUSHING_CACHED_CHARGE, &stock->flags))
  1921. flush_work(&stock->work);
  1922. }
  1923. out:
  1924. put_online_cpus();
  1925. }
  1926. /*
  1927. * Tries to drain stocked charges in other cpus. This function is asynchronous
  1928. * and just put a work per cpu for draining localy on each cpu. Caller can
  1929. * expects some charges will be back to res_counter later but cannot wait for
  1930. * it.
  1931. */
  1932. static void drain_all_stock_async(struct mem_cgroup *root_mem)
  1933. {
  1934. /*
  1935. * If someone calls draining, avoid adding more kworker runs.
  1936. */
  1937. if (!mutex_trylock(&percpu_charge_mutex))
  1938. return;
  1939. drain_all_stock(root_mem, false);
  1940. mutex_unlock(&percpu_charge_mutex);
  1941. }
  1942. /* This is a synchronous drain interface. */
  1943. static void drain_all_stock_sync(struct mem_cgroup *root_mem)
  1944. {
  1945. /* called when force_empty is called */
  1946. mutex_lock(&percpu_charge_mutex);
  1947. drain_all_stock(root_mem, true);
  1948. mutex_unlock(&percpu_charge_mutex);
  1949. }
  1950. /*
  1951. * This function drains percpu counter value from DEAD cpu and
  1952. * move it to local cpu. Note that this function can be preempted.
  1953. */
  1954. static void mem_cgroup_drain_pcp_counter(struct mem_cgroup *mem, int cpu)
  1955. {
  1956. int i;
  1957. spin_lock(&mem->pcp_counter_lock);
  1958. for (i = 0; i < MEM_CGROUP_STAT_DATA; i++) {
  1959. long x = per_cpu(mem->stat->count[i], cpu);
  1960. per_cpu(mem->stat->count[i], cpu) = 0;
  1961. mem->nocpu_base.count[i] += x;
  1962. }
  1963. for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
  1964. unsigned long x = per_cpu(mem->stat->events[i], cpu);
  1965. per_cpu(mem->stat->events[i], cpu) = 0;
  1966. mem->nocpu_base.events[i] += x;
  1967. }
  1968. /* need to clear ON_MOVE value, works as a kind of lock. */
  1969. per_cpu(mem->stat->count[MEM_CGROUP_ON_MOVE], cpu) = 0;
  1970. spin_unlock(&mem->pcp_counter_lock);
  1971. }
  1972. static void synchronize_mem_cgroup_on_move(struct mem_cgroup *mem, int cpu)
  1973. {
  1974. int idx = MEM_CGROUP_ON_MOVE;
  1975. spin_lock(&mem->pcp_counter_lock);
  1976. per_cpu(mem->stat->count[idx], cpu) = mem->nocpu_base.count[idx];
  1977. spin_unlock(&mem->pcp_counter_lock);
  1978. }
  1979. static int __cpuinit memcg_cpu_hotplug_callback(struct notifier_block *nb,
  1980. unsigned long action,
  1981. void *hcpu)
  1982. {
  1983. int cpu = (unsigned long)hcpu;
  1984. struct memcg_stock_pcp *stock;
  1985. struct mem_cgroup *iter;
  1986. if ((action == CPU_ONLINE)) {
  1987. for_each_mem_cgroup_all(iter)
  1988. synchronize_mem_cgroup_on_move(iter, cpu);
  1989. return NOTIFY_OK;
  1990. }
  1991. if ((action != CPU_DEAD) || action != CPU_DEAD_FROZEN)
  1992. return NOTIFY_OK;
  1993. for_each_mem_cgroup_all(iter)
  1994. mem_cgroup_drain_pcp_counter(iter, cpu);
  1995. stock = &per_cpu(memcg_stock, cpu);
  1996. drain_stock(stock);
  1997. return NOTIFY_OK;
  1998. }
  1999. /* See __mem_cgroup_try_charge() for details */
  2000. enum {
  2001. CHARGE_OK, /* success */
  2002. CHARGE_RETRY, /* need to retry but retry is not bad */
  2003. CHARGE_NOMEM, /* we can't do more. return -ENOMEM */
  2004. CHARGE_WOULDBLOCK, /* GFP_WAIT wasn't set and no enough res. */
  2005. CHARGE_OOM_DIE, /* the current is killed because of OOM */
  2006. };
  2007. static int mem_cgroup_do_charge(struct mem_cgroup *mem, gfp_t gfp_mask,
  2008. unsigned int nr_pages, bool oom_check)
  2009. {
  2010. unsigned long csize = nr_pages * PAGE_SIZE;
  2011. struct mem_cgroup *mem_over_limit;
  2012. struct res_counter *fail_res;
  2013. unsigned long flags = 0;
  2014. int ret;
  2015. ret = res_counter_charge(&mem->res, csize, &fail_res);
  2016. if (likely(!ret)) {
  2017. if (!do_swap_account)
  2018. return CHARGE_OK;
  2019. ret = res_counter_charge(&mem->memsw, csize, &fail_res);
  2020. if (likely(!ret))
  2021. return CHARGE_OK;
  2022. res_counter_uncharge(&mem->res, csize);
  2023. mem_over_limit = mem_cgroup_from_res_counter(fail_res, memsw);
  2024. flags |= MEM_CGROUP_RECLAIM_NOSWAP;
  2025. } else
  2026. mem_over_limit = mem_cgroup_from_res_counter(fail_res, res);
  2027. /*
  2028. * nr_pages can be either a huge page (HPAGE_PMD_NR), a batch
  2029. * of regular pages (CHARGE_BATCH), or a single regular page (1).
  2030. *
  2031. * Never reclaim on behalf of optional batching, retry with a
  2032. * single page instead.
  2033. */
  2034. if (nr_pages == CHARGE_BATCH)
  2035. return CHARGE_RETRY;
  2036. if (!(gfp_mask & __GFP_WAIT))
  2037. return CHARGE_WOULDBLOCK;
  2038. ret = mem_cgroup_hierarchical_reclaim(mem_over_limit, NULL,
  2039. gfp_mask, flags, NULL);
  2040. if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
  2041. return CHARGE_RETRY;
  2042. /*
  2043. * Even though the limit is exceeded at this point, reclaim
  2044. * may have been able to free some pages. Retry the charge
  2045. * before killing the task.
  2046. *
  2047. * Only for regular pages, though: huge pages are rather
  2048. * unlikely to succeed so close to the limit, and we fall back
  2049. * to regular pages anyway in case of failure.
  2050. */
  2051. if (nr_pages == 1 && ret)
  2052. return CHARGE_RETRY;
  2053. /*
  2054. * At task move, charge accounts can be doubly counted. So, it's
  2055. * better to wait until the end of task_move if something is going on.
  2056. */
  2057. if (mem_cgroup_wait_acct_move(mem_over_limit))
  2058. return CHARGE_RETRY;
  2059. /* If we don't need to call oom-killer at el, return immediately */
  2060. if (!oom_check)
  2061. return CHARGE_NOMEM;
  2062. /* check OOM */
  2063. if (!mem_cgroup_handle_oom(mem_over_limit, gfp_mask))
  2064. return CHARGE_OOM_DIE;
  2065. return CHARGE_RETRY;
  2066. }
  2067. /*
  2068. * Unlike exported interface, "oom" parameter is added. if oom==true,
  2069. * oom-killer can be invoked.
  2070. */
  2071. static int __mem_cgroup_try_charge(struct mm_struct *mm,
  2072. gfp_t gfp_mask,
  2073. unsigned int nr_pages,
  2074. struct mem_cgroup **memcg,
  2075. bool oom)
  2076. {
  2077. unsigned int batch = max(CHARGE_BATCH, nr_pages);
  2078. int nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
  2079. struct mem_cgroup *mem = NULL;
  2080. int ret;
  2081. /*
  2082. * Unlike gloval-vm's OOM-kill, we're not in memory shortage
  2083. * in system level. So, allow to go ahead dying process in addition to
  2084. * MEMDIE process.
  2085. */
  2086. if (unlikely(test_thread_flag(TIF_MEMDIE)
  2087. || fatal_signal_pending(current)))
  2088. goto bypass;
  2089. /*
  2090. * We always charge the cgroup the mm_struct belongs to.
  2091. * The mm_struct's mem_cgroup changes on task migration if the
  2092. * thread group leader migrates. It's possible that mm is not
  2093. * set, if so charge the init_mm (happens for pagecache usage).
  2094. */
  2095. if (!*memcg && !mm)
  2096. goto bypass;
  2097. again:
  2098. if (*memcg) { /* css should be a valid one */
  2099. mem = *memcg;
  2100. VM_BUG_ON(css_is_removed(&mem->css));
  2101. if (mem_cgroup_is_root(mem))
  2102. goto done;
  2103. if (nr_pages == 1 && consume_stock(mem))
  2104. goto done;
  2105. css_get(&mem->css);
  2106. } else {
  2107. struct task_struct *p;
  2108. rcu_read_lock();
  2109. p = rcu_dereference(mm->owner);
  2110. /*
  2111. * Because we don't have task_lock(), "p" can exit.
  2112. * In that case, "mem" can point to root or p can be NULL with
  2113. * race with swapoff. Then, we have small risk of mis-accouning.
  2114. * But such kind of mis-account by race always happens because
  2115. * we don't have cgroup_mutex(). It's overkill and we allo that
  2116. * small race, here.
  2117. * (*) swapoff at el will charge against mm-struct not against
  2118. * task-struct. So, mm->owner can be NULL.
  2119. */
  2120. mem = mem_cgroup_from_task(p);
  2121. if (!mem || mem_cgroup_is_root(mem)) {
  2122. rcu_read_unlock();
  2123. goto done;
  2124. }
  2125. if (nr_pages == 1 && consume_stock(mem)) {
  2126. /*
  2127. * It seems dagerous to access memcg without css_get().
  2128. * But considering how consume_stok works, it's not
  2129. * necessary. If consume_stock success, some charges
  2130. * from this memcg are cached on this cpu. So, we
  2131. * don't need to call css_get()/css_tryget() before
  2132. * calling consume_stock().
  2133. */
  2134. rcu_read_unlock();
  2135. goto done;
  2136. }
  2137. /* after here, we may be blocked. we need to get refcnt */
  2138. if (!css_tryget(&mem->css)) {
  2139. rcu_read_unlock();
  2140. goto again;
  2141. }
  2142. rcu_read_unlock();
  2143. }
  2144. do {
  2145. bool oom_check;
  2146. /* If killed, bypass charge */
  2147. if (fatal_signal_pending(current)) {
  2148. css_put(&mem->css);
  2149. goto bypass;
  2150. }
  2151. oom_check = false;
  2152. if (oom && !nr_oom_retries) {
  2153. oom_check = true;
  2154. nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
  2155. }
  2156. ret = mem_cgroup_do_charge(mem, gfp_mask, batch, oom_check);
  2157. switch (ret) {
  2158. case CHARGE_OK:
  2159. break;
  2160. case CHARGE_RETRY: /* not in OOM situation but retry */
  2161. batch = nr_pages;
  2162. css_put(&mem->css);
  2163. mem = NULL;
  2164. goto again;
  2165. case CHARGE_WOULDBLOCK: /* !__GFP_WAIT */
  2166. css_put(&mem->css);
  2167. goto nomem;
  2168. case CHARGE_NOMEM: /* OOM routine works */
  2169. if (!oom) {
  2170. css_put(&mem->css);
  2171. goto nomem;
  2172. }
  2173. /* If oom, we never return -ENOMEM */
  2174. nr_oom_retries--;
  2175. break;
  2176. case CHARGE_OOM_DIE: /* Killed by OOM Killer */
  2177. css_put(&mem->css);
  2178. goto bypass;
  2179. }
  2180. } while (ret != CHARGE_OK);
  2181. if (batch > nr_pages)
  2182. refill_stock(mem, batch - nr_pages);
  2183. css_put(&mem->css);
  2184. done:
  2185. *memcg = mem;
  2186. return 0;
  2187. nomem:
  2188. *memcg = NULL;
  2189. return -ENOMEM;
  2190. bypass:
  2191. *memcg = NULL;
  2192. return 0;
  2193. }
  2194. /*
  2195. * Somemtimes we have to undo a charge we got by try_charge().
  2196. * This function is for that and do uncharge, put css's refcnt.
  2197. * gotten by try_charge().
  2198. */
  2199. static void __mem_cgroup_cancel_charge(struct mem_cgroup *mem,
  2200. unsigned int nr_pages)
  2201. {
  2202. if (!mem_cgroup_is_root(mem)) {
  2203. unsigned long bytes = nr_pages * PAGE_SIZE;
  2204. res_counter_uncharge(&mem->res, bytes);
  2205. if (do_swap_account)
  2206. res_counter_uncharge(&mem->memsw, bytes);
  2207. }
  2208. }
  2209. /*
  2210. * A helper function to get mem_cgroup from ID. must be called under
  2211. * rcu_read_lock(). The caller must check css_is_removed() or some if
  2212. * it's concern. (dropping refcnt from swap can be called against removed
  2213. * memcg.)
  2214. */
  2215. static struct mem_cgroup *mem_cgroup_lookup(unsigned short id)
  2216. {
  2217. struct cgroup_subsys_state *css;
  2218. /* ID 0 is unused ID */
  2219. if (!id)
  2220. return NULL;
  2221. css = css_lookup(&mem_cgroup_subsys, id);
  2222. if (!css)
  2223. return NULL;
  2224. return container_of(css, struct mem_cgroup, css);
  2225. }
  2226. struct mem_cgroup *try_get_mem_cgroup_from_page(struct page *page)
  2227. {
  2228. struct mem_cgroup *mem = NULL;
  2229. struct page_cgroup *pc;
  2230. unsigned short id;
  2231. swp_entry_t ent;
  2232. VM_BUG_ON(!PageLocked(page));
  2233. pc = lookup_page_cgroup(page);
  2234. lock_page_cgroup(pc);
  2235. if (PageCgroupUsed(pc)) {
  2236. mem = pc->mem_cgroup;
  2237. if (mem && !css_tryget(&mem->css))
  2238. mem = NULL;
  2239. } else if (PageSwapCache(page)) {
  2240. ent.val = page_private(page);
  2241. id = lookup_swap_cgroup(ent);
  2242. rcu_read_lock();
  2243. mem = mem_cgroup_lookup(id);
  2244. if (mem && !css_tryget(&mem->css))
  2245. mem = NULL;
  2246. rcu_read_unlock();
  2247. }
  2248. unlock_page_cgroup(pc);
  2249. return mem;
  2250. }
  2251. static void __mem_cgroup_commit_charge(struct mem_cgroup *mem,
  2252. struct page *page,
  2253. unsigned int nr_pages,
  2254. struct page_cgroup *pc,
  2255. enum charge_type ctype)
  2256. {
  2257. lock_page_cgroup(pc);
  2258. if (unlikely(PageCgroupUsed(pc))) {
  2259. unlock_page_cgroup(pc);
  2260. __mem_cgroup_cancel_charge(mem, nr_pages);
  2261. return;
  2262. }
  2263. /*
  2264. * we don't need page_cgroup_lock about tail pages, becase they are not
  2265. * accessed by any other context at this point.
  2266. */
  2267. pc->mem_cgroup = mem;
  2268. /*
  2269. * We access a page_cgroup asynchronously without lock_page_cgroup().
  2270. * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
  2271. * is accessed after testing USED bit. To make pc->mem_cgroup visible
  2272. * before USED bit, we need memory barrier here.
  2273. * See mem_cgroup_add_lru_list(), etc.
  2274. */
  2275. smp_wmb();
  2276. switch (ctype) {
  2277. case MEM_CGROUP_CHARGE_TYPE_CACHE:
  2278. case MEM_CGROUP_CHARGE_TYPE_SHMEM:
  2279. SetPageCgroupCache(pc);
  2280. SetPageCgroupUsed(pc);
  2281. break;
  2282. case MEM_CGROUP_CHARGE_TYPE_MAPPED:
  2283. ClearPageCgroupCache(pc);
  2284. SetPageCgroupUsed(pc);
  2285. break;
  2286. default:
  2287. break;
  2288. }
  2289. mem_cgroup_charge_statistics(mem, PageCgroupCache(pc), nr_pages);
  2290. unlock_page_cgroup(pc);
  2291. /*
  2292. * "charge_statistics" updated event counter. Then, check it.
  2293. * Insert ancestor (and ancestor's ancestors), to softlimit RB-tree.
  2294. * if they exceeds softlimit.
  2295. */
  2296. memcg_check_events(mem, page);
  2297. }
  2298. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  2299. #define PCGF_NOCOPY_AT_SPLIT ((1 << PCG_LOCK) | (1 << PCG_MOVE_LOCK) |\
  2300. (1 << PCG_ACCT_LRU) | (1 << PCG_MIGRATION))
  2301. /*
  2302. * Because tail pages are not marked as "used", set it. We're under
  2303. * zone->lru_lock, 'splitting on pmd' and compund_lock.
  2304. */
  2305. void mem_cgroup_split_huge_fixup(struct page *head, struct page *tail)
  2306. {
  2307. struct page_cgroup *head_pc = lookup_page_cgroup(head);
  2308. struct page_cgroup *tail_pc = lookup_page_cgroup(tail);
  2309. unsigned long flags;
  2310. if (mem_cgroup_disabled())
  2311. return;
  2312. /*
  2313. * We have no races with charge/uncharge but will have races with
  2314. * page state accounting.
  2315. */
  2316. move_lock_page_cgroup(head_pc, &flags);
  2317. tail_pc->mem_cgroup = head_pc->mem_cgroup;
  2318. smp_wmb(); /* see __commit_charge() */
  2319. if (PageCgroupAcctLRU(head_pc)) {
  2320. enum lru_list lru;
  2321. struct mem_cgroup_per_zone *mz;
  2322. /*
  2323. * LRU flags cannot be copied because we need to add tail
  2324. *.page to LRU by generic call and our hook will be called.
  2325. * We hold lru_lock, then, reduce counter directly.
  2326. */
  2327. lru = page_lru(head);
  2328. mz = page_cgroup_zoneinfo(head_pc->mem_cgroup, head);
  2329. MEM_CGROUP_ZSTAT(mz, lru) -= 1;
  2330. }
  2331. tail_pc->flags = head_pc->flags & ~PCGF_NOCOPY_AT_SPLIT;
  2332. move_unlock_page_cgroup(head_pc, &flags);
  2333. }
  2334. #endif
  2335. /**
  2336. * mem_cgroup_move_account - move account of the page
  2337. * @page: the page
  2338. * @nr_pages: number of regular pages (>1 for huge pages)
  2339. * @pc: page_cgroup of the page.
  2340. * @from: mem_cgroup which the page is moved from.
  2341. * @to: mem_cgroup which the page is moved to. @from != @to.
  2342. * @uncharge: whether we should call uncharge and css_put against @from.
  2343. *
  2344. * The caller must confirm following.
  2345. * - page is not on LRU (isolate_page() is useful.)
  2346. * - compound_lock is held when nr_pages > 1
  2347. *
  2348. * This function doesn't do "charge" nor css_get to new cgroup. It should be
  2349. * done by a caller(__mem_cgroup_try_charge would be useful). If @uncharge is
  2350. * true, this function does "uncharge" from old cgroup, but it doesn't if
  2351. * @uncharge is false, so a caller should do "uncharge".
  2352. */
  2353. static int mem_cgroup_move_account(struct page *page,
  2354. unsigned int nr_pages,
  2355. struct page_cgroup *pc,
  2356. struct mem_cgroup *from,
  2357. struct mem_cgroup *to,
  2358. bool uncharge)
  2359. {
  2360. unsigned long flags;
  2361. int ret;
  2362. VM_BUG_ON(from == to);
  2363. VM_BUG_ON(PageLRU(page));
  2364. /*
  2365. * The page is isolated from LRU. So, collapse function
  2366. * will not handle this page. But page splitting can happen.
  2367. * Do this check under compound_page_lock(). The caller should
  2368. * hold it.
  2369. */
  2370. ret = -EBUSY;
  2371. if (nr_pages > 1 && !PageTransHuge(page))
  2372. goto out;
  2373. lock_page_cgroup(pc);
  2374. ret = -EINVAL;
  2375. if (!PageCgroupUsed(pc) || pc->mem_cgroup != from)
  2376. goto unlock;
  2377. move_lock_page_cgroup(pc, &flags);
  2378. if (PageCgroupFileMapped(pc)) {
  2379. /* Update mapped_file data for mem_cgroup */
  2380. preempt_disable();
  2381. __this_cpu_dec(from->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
  2382. __this_cpu_inc(to->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
  2383. preempt_enable();
  2384. }
  2385. mem_cgroup_charge_statistics(from, PageCgroupCache(pc), -nr_pages);
  2386. if (uncharge)
  2387. /* This is not "cancel", but cancel_charge does all we need. */
  2388. __mem_cgroup_cancel_charge(from, nr_pages);
  2389. /* caller should have done css_get */
  2390. pc->mem_cgroup = to;
  2391. mem_cgroup_charge_statistics(to, PageCgroupCache(pc), nr_pages);
  2392. /*
  2393. * We charges against "to" which may not have any tasks. Then, "to"
  2394. * can be under rmdir(). But in current implementation, caller of
  2395. * this function is just force_empty() and move charge, so it's
  2396. * guaranteed that "to" is never removed. So, we don't check rmdir
  2397. * status here.
  2398. */
  2399. move_unlock_page_cgroup(pc, &flags);
  2400. ret = 0;
  2401. unlock:
  2402. unlock_page_cgroup(pc);
  2403. /*
  2404. * check events
  2405. */
  2406. memcg_check_events(to, page);
  2407. memcg_check_events(from, page);
  2408. out:
  2409. return ret;
  2410. }
  2411. /*
  2412. * move charges to its parent.
  2413. */
  2414. static int mem_cgroup_move_parent(struct page *page,
  2415. struct page_cgroup *pc,
  2416. struct mem_cgroup *child,
  2417. gfp_t gfp_mask)
  2418. {
  2419. struct cgroup *cg = child->css.cgroup;
  2420. struct cgroup *pcg = cg->parent;
  2421. struct mem_cgroup *parent;
  2422. unsigned int nr_pages;
  2423. unsigned long uninitialized_var(flags);
  2424. int ret;
  2425. /* Is ROOT ? */
  2426. if (!pcg)
  2427. return -EINVAL;
  2428. ret = -EBUSY;
  2429. if (!get_page_unless_zero(page))
  2430. goto out;
  2431. if (isolate_lru_page(page))
  2432. goto put;
  2433. nr_pages = hpage_nr_pages(page);
  2434. parent = mem_cgroup_from_cont(pcg);
  2435. ret = __mem_cgroup_try_charge(NULL, gfp_mask, nr_pages, &parent, false);
  2436. if (ret || !parent)
  2437. goto put_back;
  2438. if (nr_pages > 1)
  2439. flags = compound_lock_irqsave(page);
  2440. ret = mem_cgroup_move_account(page, nr_pages, pc, child, parent, true);
  2441. if (ret)
  2442. __mem_cgroup_cancel_charge(parent, nr_pages);
  2443. if (nr_pages > 1)
  2444. compound_unlock_irqrestore(page, flags);
  2445. put_back:
  2446. putback_lru_page(page);
  2447. put:
  2448. put_page(page);
  2449. out:
  2450. return ret;
  2451. }
  2452. /*
  2453. * Charge the memory controller for page usage.
  2454. * Return
  2455. * 0 if the charge was successful
  2456. * < 0 if the cgroup is over its limit
  2457. */
  2458. static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
  2459. gfp_t gfp_mask, enum charge_type ctype)
  2460. {
  2461. struct mem_cgroup *mem = NULL;
  2462. unsigned int nr_pages = 1;
  2463. struct page_cgroup *pc;
  2464. bool oom = true;
  2465. int ret;
  2466. if (PageTransHuge(page)) {
  2467. nr_pages <<= compound_order(page);
  2468. VM_BUG_ON(!PageTransHuge(page));
  2469. /*
  2470. * Never OOM-kill a process for a huge page. The
  2471. * fault handler will fall back to regular pages.
  2472. */
  2473. oom = false;
  2474. }
  2475. pc = lookup_page_cgroup(page);
  2476. BUG_ON(!pc); /* XXX: remove this and move pc lookup into commit */
  2477. ret = __mem_cgroup_try_charge(mm, gfp_mask, nr_pages, &mem, oom);
  2478. if (ret || !mem)
  2479. return ret;
  2480. __mem_cgroup_commit_charge(mem, page, nr_pages, pc, ctype);
  2481. return 0;
  2482. }
  2483. int mem_cgroup_newpage_charge(struct page *page,
  2484. struct mm_struct *mm, gfp_t gfp_mask)
  2485. {
  2486. if (mem_cgroup_disabled())
  2487. return 0;
  2488. /*
  2489. * If already mapped, we don't have to account.
  2490. * If page cache, page->mapping has address_space.
  2491. * But page->mapping may have out-of-use anon_vma pointer,
  2492. * detecit it by PageAnon() check. newly-mapped-anon's page->mapping
  2493. * is NULL.
  2494. */
  2495. if (page_mapped(page) || (page->mapping && !PageAnon(page)))
  2496. return 0;
  2497. if (unlikely(!mm))
  2498. mm = &init_mm;
  2499. return mem_cgroup_charge_common(page, mm, gfp_mask,
  2500. MEM_CGROUP_CHARGE_TYPE_MAPPED);
  2501. }
  2502. static void
  2503. __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
  2504. enum charge_type ctype);
  2505. static void
  2506. __mem_cgroup_commit_charge_lrucare(struct page *page, struct mem_cgroup *mem,
  2507. enum charge_type ctype)
  2508. {
  2509. struct page_cgroup *pc = lookup_page_cgroup(page);
  2510. /*
  2511. * In some case, SwapCache, FUSE(splice_buf->radixtree), the page
  2512. * is already on LRU. It means the page may on some other page_cgroup's
  2513. * LRU. Take care of it.
  2514. */
  2515. mem_cgroup_lru_del_before_commit(page);
  2516. __mem_cgroup_commit_charge(mem, page, 1, pc, ctype);
  2517. mem_cgroup_lru_add_after_commit(page);
  2518. return;
  2519. }
  2520. int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
  2521. gfp_t gfp_mask)
  2522. {
  2523. struct mem_cgroup *mem = NULL;
  2524. int ret;
  2525. if (mem_cgroup_disabled())
  2526. return 0;
  2527. if (PageCompound(page))
  2528. return 0;
  2529. if (unlikely(!mm))
  2530. mm = &init_mm;
  2531. if (page_is_file_cache(page)) {
  2532. ret = __mem_cgroup_try_charge(mm, gfp_mask, 1, &mem, true);
  2533. if (ret || !mem)
  2534. return ret;
  2535. /*
  2536. * FUSE reuses pages without going through the final
  2537. * put that would remove them from the LRU list, make
  2538. * sure that they get relinked properly.
  2539. */
  2540. __mem_cgroup_commit_charge_lrucare(page, mem,
  2541. MEM_CGROUP_CHARGE_TYPE_CACHE);
  2542. return ret;
  2543. }
  2544. /* shmem */
  2545. if (PageSwapCache(page)) {
  2546. ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &mem);
  2547. if (!ret)
  2548. __mem_cgroup_commit_charge_swapin(page, mem,
  2549. MEM_CGROUP_CHARGE_TYPE_SHMEM);
  2550. } else
  2551. ret = mem_cgroup_charge_common(page, mm, gfp_mask,
  2552. MEM_CGROUP_CHARGE_TYPE_SHMEM);
  2553. return ret;
  2554. }
  2555. /*
  2556. * While swap-in, try_charge -> commit or cancel, the page is locked.
  2557. * And when try_charge() successfully returns, one refcnt to memcg without
  2558. * struct page_cgroup is acquired. This refcnt will be consumed by
  2559. * "commit()" or removed by "cancel()"
  2560. */
  2561. int mem_cgroup_try_charge_swapin(struct mm_struct *mm,
  2562. struct page *page,
  2563. gfp_t mask, struct mem_cgroup **ptr)
  2564. {
  2565. struct mem_cgroup *mem;
  2566. int ret;
  2567. *ptr = NULL;
  2568. if (mem_cgroup_disabled())
  2569. return 0;
  2570. if (!do_swap_account)
  2571. goto charge_cur_mm;
  2572. /*
  2573. * A racing thread's fault, or swapoff, may have already updated
  2574. * the pte, and even removed page from swap cache: in those cases
  2575. * do_swap_page()'s pte_same() test will fail; but there's also a
  2576. * KSM case which does need to charge the page.
  2577. */
  2578. if (!PageSwapCache(page))
  2579. goto charge_cur_mm;
  2580. mem = try_get_mem_cgroup_from_page(page);
  2581. if (!mem)
  2582. goto charge_cur_mm;
  2583. *ptr = mem;
  2584. ret = __mem_cgroup_try_charge(NULL, mask, 1, ptr, true);
  2585. css_put(&mem->css);
  2586. return ret;
  2587. charge_cur_mm:
  2588. if (unlikely(!mm))
  2589. mm = &init_mm;
  2590. return __mem_cgroup_try_charge(mm, mask, 1, ptr, true);
  2591. }
  2592. static void
  2593. __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
  2594. enum charge_type ctype)
  2595. {
  2596. if (mem_cgroup_disabled())
  2597. return;
  2598. if (!ptr)
  2599. return;
  2600. cgroup_exclude_rmdir(&ptr->css);
  2601. __mem_cgroup_commit_charge_lrucare(page, ptr, ctype);
  2602. /*
  2603. * Now swap is on-memory. This means this page may be
  2604. * counted both as mem and swap....double count.
  2605. * Fix it by uncharging from memsw. Basically, this SwapCache is stable
  2606. * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
  2607. * may call delete_from_swap_cache() before reach here.
  2608. */
  2609. if (do_swap_account && PageSwapCache(page)) {
  2610. swp_entry_t ent = {.val = page_private(page)};
  2611. unsigned short id;
  2612. struct mem_cgroup *memcg;
  2613. id = swap_cgroup_record(ent, 0);
  2614. rcu_read_lock();
  2615. memcg = mem_cgroup_lookup(id);
  2616. if (memcg) {
  2617. /*
  2618. * This recorded memcg can be obsolete one. So, avoid
  2619. * calling css_tryget
  2620. */
  2621. if (!mem_cgroup_is_root(memcg))
  2622. res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
  2623. mem_cgroup_swap_statistics(memcg, false);
  2624. mem_cgroup_put(memcg);
  2625. }
  2626. rcu_read_unlock();
  2627. }
  2628. /*
  2629. * At swapin, we may charge account against cgroup which has no tasks.
  2630. * So, rmdir()->pre_destroy() can be called while we do this charge.
  2631. * In that case, we need to call pre_destroy() again. check it here.
  2632. */
  2633. cgroup_release_and_wakeup_rmdir(&ptr->css);
  2634. }
  2635. void mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr)
  2636. {
  2637. __mem_cgroup_commit_charge_swapin(page, ptr,
  2638. MEM_CGROUP_CHARGE_TYPE_MAPPED);
  2639. }
  2640. void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *mem)
  2641. {
  2642. if (mem_cgroup_disabled())
  2643. return;
  2644. if (!mem)
  2645. return;
  2646. __mem_cgroup_cancel_charge(mem, 1);
  2647. }
  2648. static void mem_cgroup_do_uncharge(struct mem_cgroup *mem,
  2649. unsigned int nr_pages,
  2650. const enum charge_type ctype)
  2651. {
  2652. struct memcg_batch_info *batch = NULL;
  2653. bool uncharge_memsw = true;
  2654. /* If swapout, usage of swap doesn't decrease */
  2655. if (!do_swap_account || ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
  2656. uncharge_memsw = false;
  2657. batch = &current->memcg_batch;
  2658. /*
  2659. * In usual, we do css_get() when we remember memcg pointer.
  2660. * But in this case, we keep res->usage until end of a series of
  2661. * uncharges. Then, it's ok to ignore memcg's refcnt.
  2662. */
  2663. if (!batch->memcg)
  2664. batch->memcg = mem;
  2665. /*
  2666. * do_batch > 0 when unmapping pages or inode invalidate/truncate.
  2667. * In those cases, all pages freed continuously can be expected to be in
  2668. * the same cgroup and we have chance to coalesce uncharges.
  2669. * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE)
  2670. * because we want to do uncharge as soon as possible.
  2671. */
  2672. if (!batch->do_batch || test_thread_flag(TIF_MEMDIE))
  2673. goto direct_uncharge;
  2674. if (nr_pages > 1)
  2675. goto direct_uncharge;
  2676. /*
  2677. * In typical case, batch->memcg == mem. This means we can
  2678. * merge a series of uncharges to an uncharge of res_counter.
  2679. * If not, we uncharge res_counter ony by one.
  2680. */
  2681. if (batch->memcg != mem)
  2682. goto direct_uncharge;
  2683. /* remember freed charge and uncharge it later */
  2684. batch->nr_pages++;
  2685. if (uncharge_memsw)
  2686. batch->memsw_nr_pages++;
  2687. return;
  2688. direct_uncharge:
  2689. res_counter_uncharge(&mem->res, nr_pages * PAGE_SIZE);
  2690. if (uncharge_memsw)
  2691. res_counter_uncharge(&mem->memsw, nr_pages * PAGE_SIZE);
  2692. if (unlikely(batch->memcg != mem))
  2693. memcg_oom_recover(mem);
  2694. return;
  2695. }
  2696. /*
  2697. * uncharge if !page_mapped(page)
  2698. */
  2699. static struct mem_cgroup *
  2700. __mem_cgroup_uncharge_common(struct page *page, enum charge_type ctype)
  2701. {
  2702. struct mem_cgroup *mem = NULL;
  2703. unsigned int nr_pages = 1;
  2704. struct page_cgroup *pc;
  2705. if (mem_cgroup_disabled())
  2706. return NULL;
  2707. if (PageSwapCache(page))
  2708. return NULL;
  2709. if (PageTransHuge(page)) {
  2710. nr_pages <<= compound_order(page);
  2711. VM_BUG_ON(!PageTransHuge(page));
  2712. }
  2713. /*
  2714. * Check if our page_cgroup is valid
  2715. */
  2716. pc = lookup_page_cgroup(page);
  2717. if (unlikely(!pc || !PageCgroupUsed(pc)))
  2718. return NULL;
  2719. lock_page_cgroup(pc);
  2720. mem = pc->mem_cgroup;
  2721. if (!PageCgroupUsed(pc))
  2722. goto unlock_out;
  2723. switch (ctype) {
  2724. case MEM_CGROUP_CHARGE_TYPE_MAPPED:
  2725. case MEM_CGROUP_CHARGE_TYPE_DROP:
  2726. /* See mem_cgroup_prepare_migration() */
  2727. if (page_mapped(page) || PageCgroupMigration(pc))
  2728. goto unlock_out;
  2729. break;
  2730. case MEM_CGROUP_CHARGE_TYPE_SWAPOUT:
  2731. if (!PageAnon(page)) { /* Shared memory */
  2732. if (page->mapping && !page_is_file_cache(page))
  2733. goto unlock_out;
  2734. } else if (page_mapped(page)) /* Anon */
  2735. goto unlock_out;
  2736. break;
  2737. default:
  2738. break;
  2739. }
  2740. mem_cgroup_charge_statistics(mem, PageCgroupCache(pc), -nr_pages);
  2741. ClearPageCgroupUsed(pc);
  2742. /*
  2743. * pc->mem_cgroup is not cleared here. It will be accessed when it's
  2744. * freed from LRU. This is safe because uncharged page is expected not
  2745. * to be reused (freed soon). Exception is SwapCache, it's handled by
  2746. * special functions.
  2747. */
  2748. unlock_page_cgroup(pc);
  2749. /*
  2750. * even after unlock, we have mem->res.usage here and this memcg
  2751. * will never be freed.
  2752. */
  2753. memcg_check_events(mem, page);
  2754. if (do_swap_account && ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT) {
  2755. mem_cgroup_swap_statistics(mem, true);
  2756. mem_cgroup_get(mem);
  2757. }
  2758. if (!mem_cgroup_is_root(mem))
  2759. mem_cgroup_do_uncharge(mem, nr_pages, ctype);
  2760. return mem;
  2761. unlock_out:
  2762. unlock_page_cgroup(pc);
  2763. return NULL;
  2764. }
  2765. void mem_cgroup_uncharge_page(struct page *page)
  2766. {
  2767. /* early check. */
  2768. if (page_mapped(page))
  2769. return;
  2770. if (page->mapping && !PageAnon(page))
  2771. return;
  2772. __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_MAPPED);
  2773. }
  2774. void mem_cgroup_uncharge_cache_page(struct page *page)
  2775. {
  2776. VM_BUG_ON(page_mapped(page));
  2777. VM_BUG_ON(page->mapping);
  2778. __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_CACHE);
  2779. }
  2780. /*
  2781. * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate.
  2782. * In that cases, pages are freed continuously and we can expect pages
  2783. * are in the same memcg. All these calls itself limits the number of
  2784. * pages freed at once, then uncharge_start/end() is called properly.
  2785. * This may be called prural(2) times in a context,
  2786. */
  2787. void mem_cgroup_uncharge_start(void)
  2788. {
  2789. current->memcg_batch.do_batch++;
  2790. /* We can do nest. */
  2791. if (current->memcg_batch.do_batch == 1) {
  2792. current->memcg_batch.memcg = NULL;
  2793. current->memcg_batch.nr_pages = 0;
  2794. current->memcg_batch.memsw_nr_pages = 0;
  2795. }
  2796. }
  2797. void mem_cgroup_uncharge_end(void)
  2798. {
  2799. struct memcg_batch_info *batch = &current->memcg_batch;
  2800. if (!batch->do_batch)
  2801. return;
  2802. batch->do_batch--;
  2803. if (batch->do_batch) /* If stacked, do nothing. */
  2804. return;
  2805. if (!batch->memcg)
  2806. return;
  2807. /*
  2808. * This "batch->memcg" is valid without any css_get/put etc...
  2809. * bacause we hide charges behind us.
  2810. */
  2811. if (batch->nr_pages)
  2812. res_counter_uncharge(&batch->memcg->res,
  2813. batch->nr_pages * PAGE_SIZE);
  2814. if (batch->memsw_nr_pages)
  2815. res_counter_uncharge(&batch->memcg->memsw,
  2816. batch->memsw_nr_pages * PAGE_SIZE);
  2817. memcg_oom_recover(batch->memcg);
  2818. /* forget this pointer (for sanity check) */
  2819. batch->memcg = NULL;
  2820. }
  2821. #ifdef CONFIG_SWAP
  2822. /*
  2823. * called after __delete_from_swap_cache() and drop "page" account.
  2824. * memcg information is recorded to swap_cgroup of "ent"
  2825. */
  2826. void
  2827. mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout)
  2828. {
  2829. struct mem_cgroup *memcg;
  2830. int ctype = MEM_CGROUP_CHARGE_TYPE_SWAPOUT;
  2831. if (!swapout) /* this was a swap cache but the swap is unused ! */
  2832. ctype = MEM_CGROUP_CHARGE_TYPE_DROP;
  2833. memcg = __mem_cgroup_uncharge_common(page, ctype);
  2834. /*
  2835. * record memcg information, if swapout && memcg != NULL,
  2836. * mem_cgroup_get() was called in uncharge().
  2837. */
  2838. if (do_swap_account && swapout && memcg)
  2839. swap_cgroup_record(ent, css_id(&memcg->css));
  2840. }
  2841. #endif
  2842. #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
  2843. /*
  2844. * called from swap_entry_free(). remove record in swap_cgroup and
  2845. * uncharge "memsw" account.
  2846. */
  2847. void mem_cgroup_uncharge_swap(swp_entry_t ent)
  2848. {
  2849. struct mem_cgroup *memcg;
  2850. unsigned short id;
  2851. if (!do_swap_account)
  2852. return;
  2853. id = swap_cgroup_record(ent, 0);
  2854. rcu_read_lock();
  2855. memcg = mem_cgroup_lookup(id);
  2856. if (memcg) {
  2857. /*
  2858. * We uncharge this because swap is freed.
  2859. * This memcg can be obsolete one. We avoid calling css_tryget
  2860. */
  2861. if (!mem_cgroup_is_root(memcg))
  2862. res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
  2863. mem_cgroup_swap_statistics(memcg, false);
  2864. mem_cgroup_put(memcg);
  2865. }
  2866. rcu_read_unlock();
  2867. }
  2868. /**
  2869. * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
  2870. * @entry: swap entry to be moved
  2871. * @from: mem_cgroup which the entry is moved from
  2872. * @to: mem_cgroup which the entry is moved to
  2873. * @need_fixup: whether we should fixup res_counters and refcounts.
  2874. *
  2875. * It succeeds only when the swap_cgroup's record for this entry is the same
  2876. * as the mem_cgroup's id of @from.
  2877. *
  2878. * Returns 0 on success, -EINVAL on failure.
  2879. *
  2880. * The caller must have charged to @to, IOW, called res_counter_charge() about
  2881. * both res and memsw, and called css_get().
  2882. */
  2883. static int mem_cgroup_move_swap_account(swp_entry_t entry,
  2884. struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
  2885. {
  2886. unsigned short old_id, new_id;
  2887. old_id = css_id(&from->css);
  2888. new_id = css_id(&to->css);
  2889. if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
  2890. mem_cgroup_swap_statistics(from, false);
  2891. mem_cgroup_swap_statistics(to, true);
  2892. /*
  2893. * This function is only called from task migration context now.
  2894. * It postpones res_counter and refcount handling till the end
  2895. * of task migration(mem_cgroup_clear_mc()) for performance
  2896. * improvement. But we cannot postpone mem_cgroup_get(to)
  2897. * because if the process that has been moved to @to does
  2898. * swap-in, the refcount of @to might be decreased to 0.
  2899. */
  2900. mem_cgroup_get(to);
  2901. if (need_fixup) {
  2902. if (!mem_cgroup_is_root(from))
  2903. res_counter_uncharge(&from->memsw, PAGE_SIZE);
  2904. mem_cgroup_put(from);
  2905. /*
  2906. * we charged both to->res and to->memsw, so we should
  2907. * uncharge to->res.
  2908. */
  2909. if (!mem_cgroup_is_root(to))
  2910. res_counter_uncharge(&to->res, PAGE_SIZE);
  2911. }
  2912. return 0;
  2913. }
  2914. return -EINVAL;
  2915. }
  2916. #else
  2917. static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
  2918. struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
  2919. {
  2920. return -EINVAL;
  2921. }
  2922. #endif
  2923. /*
  2924. * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
  2925. * page belongs to.
  2926. */
  2927. int mem_cgroup_prepare_migration(struct page *page,
  2928. struct page *newpage, struct mem_cgroup **ptr, gfp_t gfp_mask)
  2929. {
  2930. struct mem_cgroup *mem = NULL;
  2931. struct page_cgroup *pc;
  2932. enum charge_type ctype;
  2933. int ret = 0;
  2934. *ptr = NULL;
  2935. VM_BUG_ON(PageTransHuge(page));
  2936. if (mem_cgroup_disabled())
  2937. return 0;
  2938. pc = lookup_page_cgroup(page);
  2939. lock_page_cgroup(pc);
  2940. if (PageCgroupUsed(pc)) {
  2941. mem = pc->mem_cgroup;
  2942. css_get(&mem->css);
  2943. /*
  2944. * At migrating an anonymous page, its mapcount goes down
  2945. * to 0 and uncharge() will be called. But, even if it's fully
  2946. * unmapped, migration may fail and this page has to be
  2947. * charged again. We set MIGRATION flag here and delay uncharge
  2948. * until end_migration() is called
  2949. *
  2950. * Corner Case Thinking
  2951. * A)
  2952. * When the old page was mapped as Anon and it's unmap-and-freed
  2953. * while migration was ongoing.
  2954. * If unmap finds the old page, uncharge() of it will be delayed
  2955. * until end_migration(). If unmap finds a new page, it's
  2956. * uncharged when it make mapcount to be 1->0. If unmap code
  2957. * finds swap_migration_entry, the new page will not be mapped
  2958. * and end_migration() will find it(mapcount==0).
  2959. *
  2960. * B)
  2961. * When the old page was mapped but migraion fails, the kernel
  2962. * remaps it. A charge for it is kept by MIGRATION flag even
  2963. * if mapcount goes down to 0. We can do remap successfully
  2964. * without charging it again.
  2965. *
  2966. * C)
  2967. * The "old" page is under lock_page() until the end of
  2968. * migration, so, the old page itself will not be swapped-out.
  2969. * If the new page is swapped out before end_migraton, our
  2970. * hook to usual swap-out path will catch the event.
  2971. */
  2972. if (PageAnon(page))
  2973. SetPageCgroupMigration(pc);
  2974. }
  2975. unlock_page_cgroup(pc);
  2976. /*
  2977. * If the page is not charged at this point,
  2978. * we return here.
  2979. */
  2980. if (!mem)
  2981. return 0;
  2982. *ptr = mem;
  2983. ret = __mem_cgroup_try_charge(NULL, gfp_mask, 1, ptr, false);
  2984. css_put(&mem->css);/* drop extra refcnt */
  2985. if (ret || *ptr == NULL) {
  2986. if (PageAnon(page)) {
  2987. lock_page_cgroup(pc);
  2988. ClearPageCgroupMigration(pc);
  2989. unlock_page_cgroup(pc);
  2990. /*
  2991. * The old page may be fully unmapped while we kept it.
  2992. */
  2993. mem_cgroup_uncharge_page(page);
  2994. }
  2995. return -ENOMEM;
  2996. }
  2997. /*
  2998. * We charge new page before it's used/mapped. So, even if unlock_page()
  2999. * is called before end_migration, we can catch all events on this new
  3000. * page. In the case new page is migrated but not remapped, new page's
  3001. * mapcount will be finally 0 and we call uncharge in end_migration().
  3002. */
  3003. pc = lookup_page_cgroup(newpage);
  3004. if (PageAnon(page))
  3005. ctype = MEM_CGROUP_CHARGE_TYPE_MAPPED;
  3006. else if (page_is_file_cache(page))
  3007. ctype = MEM_CGROUP_CHARGE_TYPE_CACHE;
  3008. else
  3009. ctype = MEM_CGROUP_CHARGE_TYPE_SHMEM;
  3010. __mem_cgroup_commit_charge(mem, page, 1, pc, ctype);
  3011. return ret;
  3012. }
  3013. /* remove redundant charge if migration failed*/
  3014. void mem_cgroup_end_migration(struct mem_cgroup *mem,
  3015. struct page *oldpage, struct page *newpage, bool migration_ok)
  3016. {
  3017. struct page *used, *unused;
  3018. struct page_cgroup *pc;
  3019. if (!mem)
  3020. return;
  3021. /* blocks rmdir() */
  3022. cgroup_exclude_rmdir(&mem->css);
  3023. if (!migration_ok) {
  3024. used = oldpage;
  3025. unused = newpage;
  3026. } else {
  3027. used = newpage;
  3028. unused = oldpage;
  3029. }
  3030. /*
  3031. * We disallowed uncharge of pages under migration because mapcount
  3032. * of the page goes down to zero, temporarly.
  3033. * Clear the flag and check the page should be charged.
  3034. */
  3035. pc = lookup_page_cgroup(oldpage);
  3036. lock_page_cgroup(pc);
  3037. ClearPageCgroupMigration(pc);
  3038. unlock_page_cgroup(pc);
  3039. __mem_cgroup_uncharge_common(unused, MEM_CGROUP_CHARGE_TYPE_FORCE);
  3040. /*
  3041. * If a page is a file cache, radix-tree replacement is very atomic
  3042. * and we can skip this check. When it was an Anon page, its mapcount
  3043. * goes down to 0. But because we added MIGRATION flage, it's not
  3044. * uncharged yet. There are several case but page->mapcount check
  3045. * and USED bit check in mem_cgroup_uncharge_page() will do enough
  3046. * check. (see prepare_charge() also)
  3047. */
  3048. if (PageAnon(used))
  3049. mem_cgroup_uncharge_page(used);
  3050. /*
  3051. * At migration, we may charge account against cgroup which has no
  3052. * tasks.
  3053. * So, rmdir()->pre_destroy() can be called while we do this charge.
  3054. * In that case, we need to call pre_destroy() again. check it here.
  3055. */
  3056. cgroup_release_and_wakeup_rmdir(&mem->css);
  3057. }
  3058. #ifdef CONFIG_DEBUG_VM
  3059. static struct page_cgroup *lookup_page_cgroup_used(struct page *page)
  3060. {
  3061. struct page_cgroup *pc;
  3062. pc = lookup_page_cgroup(page);
  3063. if (likely(pc) && PageCgroupUsed(pc))
  3064. return pc;
  3065. return NULL;
  3066. }
  3067. bool mem_cgroup_bad_page_check(struct page *page)
  3068. {
  3069. if (mem_cgroup_disabled())
  3070. return false;
  3071. return lookup_page_cgroup_used(page) != NULL;
  3072. }
  3073. void mem_cgroup_print_bad_page(struct page *page)
  3074. {
  3075. struct page_cgroup *pc;
  3076. pc = lookup_page_cgroup_used(page);
  3077. if (pc) {
  3078. int ret = -1;
  3079. char *path;
  3080. printk(KERN_ALERT "pc:%p pc->flags:%lx pc->mem_cgroup:%p",
  3081. pc, pc->flags, pc->mem_cgroup);
  3082. path = kmalloc(PATH_MAX, GFP_KERNEL);
  3083. if (path) {
  3084. rcu_read_lock();
  3085. ret = cgroup_path(pc->mem_cgroup->css.cgroup,
  3086. path, PATH_MAX);
  3087. rcu_read_unlock();
  3088. }
  3089. printk(KERN_CONT "(%s)\n",
  3090. (ret < 0) ? "cannot get the path" : path);
  3091. kfree(path);
  3092. }
  3093. }
  3094. #endif
  3095. static DEFINE_MUTEX(set_limit_mutex);
  3096. static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
  3097. unsigned long long val)
  3098. {
  3099. int retry_count;
  3100. u64 memswlimit, memlimit;
  3101. int ret = 0;
  3102. int children = mem_cgroup_count_children(memcg);
  3103. u64 curusage, oldusage;
  3104. int enlarge;
  3105. /*
  3106. * For keeping hierarchical_reclaim simple, how long we should retry
  3107. * is depends on callers. We set our retry-count to be function
  3108. * of # of children which we should visit in this loop.
  3109. */
  3110. retry_count = MEM_CGROUP_RECLAIM_RETRIES * children;
  3111. oldusage = res_counter_read_u64(&memcg->res, RES_USAGE);
  3112. enlarge = 0;
  3113. while (retry_count) {
  3114. if (signal_pending(current)) {
  3115. ret = -EINTR;
  3116. break;
  3117. }
  3118. /*
  3119. * Rather than hide all in some function, I do this in
  3120. * open coded manner. You see what this really does.
  3121. * We have to guarantee mem->res.limit < mem->memsw.limit.
  3122. */
  3123. mutex_lock(&set_limit_mutex);
  3124. memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
  3125. if (memswlimit < val) {
  3126. ret = -EINVAL;
  3127. mutex_unlock(&set_limit_mutex);
  3128. break;
  3129. }
  3130. memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
  3131. if (memlimit < val)
  3132. enlarge = 1;
  3133. ret = res_counter_set_limit(&memcg->res, val);
  3134. if (!ret) {
  3135. if (memswlimit == val)
  3136. memcg->memsw_is_minimum = true;
  3137. else
  3138. memcg->memsw_is_minimum = false;
  3139. }
  3140. mutex_unlock(&set_limit_mutex);
  3141. if (!ret)
  3142. break;
  3143. mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
  3144. MEM_CGROUP_RECLAIM_SHRINK,
  3145. NULL);
  3146. curusage = res_counter_read_u64(&memcg->res, RES_USAGE);
  3147. /* Usage is reduced ? */
  3148. if (curusage >= oldusage)
  3149. retry_count--;
  3150. else
  3151. oldusage = curusage;
  3152. }
  3153. if (!ret && enlarge)
  3154. memcg_oom_recover(memcg);
  3155. return ret;
  3156. }
  3157. static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
  3158. unsigned long long val)
  3159. {
  3160. int retry_count;
  3161. u64 memlimit, memswlimit, oldusage, curusage;
  3162. int children = mem_cgroup_count_children(memcg);
  3163. int ret = -EBUSY;
  3164. int enlarge = 0;
  3165. /* see mem_cgroup_resize_res_limit */
  3166. retry_count = children * MEM_CGROUP_RECLAIM_RETRIES;
  3167. oldusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
  3168. while (retry_count) {
  3169. if (signal_pending(current)) {
  3170. ret = -EINTR;
  3171. break;
  3172. }
  3173. /*
  3174. * Rather than hide all in some function, I do this in
  3175. * open coded manner. You see what this really does.
  3176. * We have to guarantee mem->res.limit < mem->memsw.limit.
  3177. */
  3178. mutex_lock(&set_limit_mutex);
  3179. memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
  3180. if (memlimit > val) {
  3181. ret = -EINVAL;
  3182. mutex_unlock(&set_limit_mutex);
  3183. break;
  3184. }
  3185. memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
  3186. if (memswlimit < val)
  3187. enlarge = 1;
  3188. ret = res_counter_set_limit(&memcg->memsw, val);
  3189. if (!ret) {
  3190. if (memlimit == val)
  3191. memcg->memsw_is_minimum = true;
  3192. else
  3193. memcg->memsw_is_minimum = false;
  3194. }
  3195. mutex_unlock(&set_limit_mutex);
  3196. if (!ret)
  3197. break;
  3198. mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
  3199. MEM_CGROUP_RECLAIM_NOSWAP |
  3200. MEM_CGROUP_RECLAIM_SHRINK,
  3201. NULL);
  3202. curusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
  3203. /* Usage is reduced ? */
  3204. if (curusage >= oldusage)
  3205. retry_count--;
  3206. else
  3207. oldusage = curusage;
  3208. }
  3209. if (!ret && enlarge)
  3210. memcg_oom_recover(memcg);
  3211. return ret;
  3212. }
  3213. unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
  3214. gfp_t gfp_mask,
  3215. unsigned long *total_scanned)
  3216. {
  3217. unsigned long nr_reclaimed = 0;
  3218. struct mem_cgroup_per_zone *mz, *next_mz = NULL;
  3219. unsigned long reclaimed;
  3220. int loop = 0;
  3221. struct mem_cgroup_tree_per_zone *mctz;
  3222. unsigned long long excess;
  3223. unsigned long nr_scanned;
  3224. if (order > 0)
  3225. return 0;
  3226. mctz = soft_limit_tree_node_zone(zone_to_nid(zone), zone_idx(zone));
  3227. /*
  3228. * This loop can run a while, specially if mem_cgroup's continuously
  3229. * keep exceeding their soft limit and putting the system under
  3230. * pressure
  3231. */
  3232. do {
  3233. if (next_mz)
  3234. mz = next_mz;
  3235. else
  3236. mz = mem_cgroup_largest_soft_limit_node(mctz);
  3237. if (!mz)
  3238. break;
  3239. nr_scanned = 0;
  3240. reclaimed = mem_cgroup_hierarchical_reclaim(mz->mem, zone,
  3241. gfp_mask,
  3242. MEM_CGROUP_RECLAIM_SOFT,
  3243. &nr_scanned);
  3244. nr_reclaimed += reclaimed;
  3245. *total_scanned += nr_scanned;
  3246. spin_lock(&mctz->lock);
  3247. /*
  3248. * If we failed to reclaim anything from this memory cgroup
  3249. * it is time to move on to the next cgroup
  3250. */
  3251. next_mz = NULL;
  3252. if (!reclaimed) {
  3253. do {
  3254. /*
  3255. * Loop until we find yet another one.
  3256. *
  3257. * By the time we get the soft_limit lock
  3258. * again, someone might have aded the
  3259. * group back on the RB tree. Iterate to
  3260. * make sure we get a different mem.
  3261. * mem_cgroup_largest_soft_limit_node returns
  3262. * NULL if no other cgroup is present on
  3263. * the tree
  3264. */
  3265. next_mz =
  3266. __mem_cgroup_largest_soft_limit_node(mctz);
  3267. if (next_mz == mz)
  3268. css_put(&next_mz->mem->css);
  3269. else /* next_mz == NULL or other memcg */
  3270. break;
  3271. } while (1);
  3272. }
  3273. __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
  3274. excess = res_counter_soft_limit_excess(&mz->mem->res);
  3275. /*
  3276. * One school of thought says that we should not add
  3277. * back the node to the tree if reclaim returns 0.
  3278. * But our reclaim could return 0, simply because due
  3279. * to priority we are exposing a smaller subset of
  3280. * memory to reclaim from. Consider this as a longer
  3281. * term TODO.
  3282. */
  3283. /* If excess == 0, no tree ops */
  3284. __mem_cgroup_insert_exceeded(mz->mem, mz, mctz, excess);
  3285. spin_unlock(&mctz->lock);
  3286. css_put(&mz->mem->css);
  3287. loop++;
  3288. /*
  3289. * Could not reclaim anything and there are no more
  3290. * mem cgroups to try or we seem to be looping without
  3291. * reclaiming anything.
  3292. */
  3293. if (!nr_reclaimed &&
  3294. (next_mz == NULL ||
  3295. loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
  3296. break;
  3297. } while (!nr_reclaimed);
  3298. if (next_mz)
  3299. css_put(&next_mz->mem->css);
  3300. return nr_reclaimed;
  3301. }
  3302. /*
  3303. * This routine traverse page_cgroup in given list and drop them all.
  3304. * *And* this routine doesn't reclaim page itself, just removes page_cgroup.
  3305. */
  3306. static int mem_cgroup_force_empty_list(struct mem_cgroup *mem,
  3307. int node, int zid, enum lru_list lru)
  3308. {
  3309. struct zone *zone;
  3310. struct mem_cgroup_per_zone *mz;
  3311. struct page_cgroup *pc, *busy;
  3312. unsigned long flags, loop;
  3313. struct list_head *list;
  3314. int ret = 0;
  3315. zone = &NODE_DATA(node)->node_zones[zid];
  3316. mz = mem_cgroup_zoneinfo(mem, node, zid);
  3317. list = &mz->lists[lru];
  3318. loop = MEM_CGROUP_ZSTAT(mz, lru);
  3319. /* give some margin against EBUSY etc...*/
  3320. loop += 256;
  3321. busy = NULL;
  3322. while (loop--) {
  3323. struct page *page;
  3324. ret = 0;
  3325. spin_lock_irqsave(&zone->lru_lock, flags);
  3326. if (list_empty(list)) {
  3327. spin_unlock_irqrestore(&zone->lru_lock, flags);
  3328. break;
  3329. }
  3330. pc = list_entry(list->prev, struct page_cgroup, lru);
  3331. if (busy == pc) {
  3332. list_move(&pc->lru, list);
  3333. busy = NULL;
  3334. spin_unlock_irqrestore(&zone->lru_lock, flags);
  3335. continue;
  3336. }
  3337. spin_unlock_irqrestore(&zone->lru_lock, flags);
  3338. page = lookup_cgroup_page(pc);
  3339. ret = mem_cgroup_move_parent(page, pc, mem, GFP_KERNEL);
  3340. if (ret == -ENOMEM)
  3341. break;
  3342. if (ret == -EBUSY || ret == -EINVAL) {
  3343. /* found lock contention or "pc" is obsolete. */
  3344. busy = pc;
  3345. cond_resched();
  3346. } else
  3347. busy = NULL;
  3348. }
  3349. if (!ret && !list_empty(list))
  3350. return -EBUSY;
  3351. return ret;
  3352. }
  3353. /*
  3354. * make mem_cgroup's charge to be 0 if there is no task.
  3355. * This enables deleting this mem_cgroup.
  3356. */
  3357. static int mem_cgroup_force_empty(struct mem_cgroup *mem, bool free_all)
  3358. {
  3359. int ret;
  3360. int node, zid, shrink;
  3361. int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
  3362. struct cgroup *cgrp = mem->css.cgroup;
  3363. css_get(&mem->css);
  3364. shrink = 0;
  3365. /* should free all ? */
  3366. if (free_all)
  3367. goto try_to_free;
  3368. move_account:
  3369. do {
  3370. ret = -EBUSY;
  3371. if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children))
  3372. goto out;
  3373. ret = -EINTR;
  3374. if (signal_pending(current))
  3375. goto out;
  3376. /* This is for making all *used* pages to be on LRU. */
  3377. lru_add_drain_all();
  3378. drain_all_stock_sync(mem);
  3379. ret = 0;
  3380. mem_cgroup_start_move(mem);
  3381. for_each_node_state(node, N_HIGH_MEMORY) {
  3382. for (zid = 0; !ret && zid < MAX_NR_ZONES; zid++) {
  3383. enum lru_list l;
  3384. for_each_lru(l) {
  3385. ret = mem_cgroup_force_empty_list(mem,
  3386. node, zid, l);
  3387. if (ret)
  3388. break;
  3389. }
  3390. }
  3391. if (ret)
  3392. break;
  3393. }
  3394. mem_cgroup_end_move(mem);
  3395. memcg_oom_recover(mem);
  3396. /* it seems parent cgroup doesn't have enough mem */
  3397. if (ret == -ENOMEM)
  3398. goto try_to_free;
  3399. cond_resched();
  3400. /* "ret" should also be checked to ensure all lists are empty. */
  3401. } while (mem->res.usage > 0 || ret);
  3402. out:
  3403. css_put(&mem->css);
  3404. return ret;
  3405. try_to_free:
  3406. /* returns EBUSY if there is a task or if we come here twice. */
  3407. if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children) || shrink) {
  3408. ret = -EBUSY;
  3409. goto out;
  3410. }
  3411. /* we call try-to-free pages for make this cgroup empty */
  3412. lru_add_drain_all();
  3413. /* try to free all pages in this cgroup */
  3414. shrink = 1;
  3415. while (nr_retries && mem->res.usage > 0) {
  3416. struct memcg_scanrecord rec;
  3417. int progress;
  3418. if (signal_pending(current)) {
  3419. ret = -EINTR;
  3420. goto out;
  3421. }
  3422. rec.context = SCAN_BY_SHRINK;
  3423. rec.mem = mem;
  3424. rec.root = mem;
  3425. progress = try_to_free_mem_cgroup_pages(mem, GFP_KERNEL,
  3426. false, &rec);
  3427. if (!progress) {
  3428. nr_retries--;
  3429. /* maybe some writeback is necessary */
  3430. congestion_wait(BLK_RW_ASYNC, HZ/10);
  3431. }
  3432. }
  3433. lru_add_drain();
  3434. /* try move_account...there may be some *locked* pages. */
  3435. goto move_account;
  3436. }
  3437. int mem_cgroup_force_empty_write(struct cgroup *cont, unsigned int event)
  3438. {
  3439. return mem_cgroup_force_empty(mem_cgroup_from_cont(cont), true);
  3440. }
  3441. static u64 mem_cgroup_hierarchy_read(struct cgroup *cont, struct cftype *cft)
  3442. {
  3443. return mem_cgroup_from_cont(cont)->use_hierarchy;
  3444. }
  3445. static int mem_cgroup_hierarchy_write(struct cgroup *cont, struct cftype *cft,
  3446. u64 val)
  3447. {
  3448. int retval = 0;
  3449. struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
  3450. struct cgroup *parent = cont->parent;
  3451. struct mem_cgroup *parent_mem = NULL;
  3452. if (parent)
  3453. parent_mem = mem_cgroup_from_cont(parent);
  3454. cgroup_lock();
  3455. /*
  3456. * If parent's use_hierarchy is set, we can't make any modifications
  3457. * in the child subtrees. If it is unset, then the change can
  3458. * occur, provided the current cgroup has no children.
  3459. *
  3460. * For the root cgroup, parent_mem is NULL, we allow value to be
  3461. * set if there are no children.
  3462. */
  3463. if ((!parent_mem || !parent_mem->use_hierarchy) &&
  3464. (val == 1 || val == 0)) {
  3465. if (list_empty(&cont->children))
  3466. mem->use_hierarchy = val;
  3467. else
  3468. retval = -EBUSY;
  3469. } else
  3470. retval = -EINVAL;
  3471. cgroup_unlock();
  3472. return retval;
  3473. }
  3474. static unsigned long mem_cgroup_recursive_stat(struct mem_cgroup *mem,
  3475. enum mem_cgroup_stat_index idx)
  3476. {
  3477. struct mem_cgroup *iter;
  3478. long val = 0;
  3479. /* Per-cpu values can be negative, use a signed accumulator */
  3480. for_each_mem_cgroup_tree(iter, mem)
  3481. val += mem_cgroup_read_stat(iter, idx);
  3482. if (val < 0) /* race ? */
  3483. val = 0;
  3484. return val;
  3485. }
  3486. static inline u64 mem_cgroup_usage(struct mem_cgroup *mem, bool swap)
  3487. {
  3488. u64 val;
  3489. if (!mem_cgroup_is_root(mem)) {
  3490. if (!swap)
  3491. return res_counter_read_u64(&mem->res, RES_USAGE);
  3492. else
  3493. return res_counter_read_u64(&mem->memsw, RES_USAGE);
  3494. }
  3495. val = mem_cgroup_recursive_stat(mem, MEM_CGROUP_STAT_CACHE);
  3496. val += mem_cgroup_recursive_stat(mem, MEM_CGROUP_STAT_RSS);
  3497. if (swap)
  3498. val += mem_cgroup_recursive_stat(mem, MEM_CGROUP_STAT_SWAPOUT);
  3499. return val << PAGE_SHIFT;
  3500. }
  3501. static u64 mem_cgroup_read(struct cgroup *cont, struct cftype *cft)
  3502. {
  3503. struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
  3504. u64 val;
  3505. int type, name;
  3506. type = MEMFILE_TYPE(cft->private);
  3507. name = MEMFILE_ATTR(cft->private);
  3508. switch (type) {
  3509. case _MEM:
  3510. if (name == RES_USAGE)
  3511. val = mem_cgroup_usage(mem, false);
  3512. else
  3513. val = res_counter_read_u64(&mem->res, name);
  3514. break;
  3515. case _MEMSWAP:
  3516. if (name == RES_USAGE)
  3517. val = mem_cgroup_usage(mem, true);
  3518. else
  3519. val = res_counter_read_u64(&mem->memsw, name);
  3520. break;
  3521. default:
  3522. BUG();
  3523. break;
  3524. }
  3525. return val;
  3526. }
  3527. /*
  3528. * The user of this function is...
  3529. * RES_LIMIT.
  3530. */
  3531. static int mem_cgroup_write(struct cgroup *cont, struct cftype *cft,
  3532. const char *buffer)
  3533. {
  3534. struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
  3535. int type, name;
  3536. unsigned long long val;
  3537. int ret;
  3538. type = MEMFILE_TYPE(cft->private);
  3539. name = MEMFILE_ATTR(cft->private);
  3540. switch (name) {
  3541. case RES_LIMIT:
  3542. if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
  3543. ret = -EINVAL;
  3544. break;
  3545. }
  3546. /* This function does all necessary parse...reuse it */
  3547. ret = res_counter_memparse_write_strategy(buffer, &val);
  3548. if (ret)
  3549. break;
  3550. if (type == _MEM)
  3551. ret = mem_cgroup_resize_limit(memcg, val);
  3552. else
  3553. ret = mem_cgroup_resize_memsw_limit(memcg, val);
  3554. break;
  3555. case RES_SOFT_LIMIT:
  3556. ret = res_counter_memparse_write_strategy(buffer, &val);
  3557. if (ret)
  3558. break;
  3559. /*
  3560. * For memsw, soft limits are hard to implement in terms
  3561. * of semantics, for now, we support soft limits for
  3562. * control without swap
  3563. */
  3564. if (type == _MEM)
  3565. ret = res_counter_set_soft_limit(&memcg->res, val);
  3566. else
  3567. ret = -EINVAL;
  3568. break;
  3569. default:
  3570. ret = -EINVAL; /* should be BUG() ? */
  3571. break;
  3572. }
  3573. return ret;
  3574. }
  3575. static void memcg_get_hierarchical_limit(struct mem_cgroup *memcg,
  3576. unsigned long long *mem_limit, unsigned long long *memsw_limit)
  3577. {
  3578. struct cgroup *cgroup;
  3579. unsigned long long min_limit, min_memsw_limit, tmp;
  3580. min_limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
  3581. min_memsw_limit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
  3582. cgroup = memcg->css.cgroup;
  3583. if (!memcg->use_hierarchy)
  3584. goto out;
  3585. while (cgroup->parent) {
  3586. cgroup = cgroup->parent;
  3587. memcg = mem_cgroup_from_cont(cgroup);
  3588. if (!memcg->use_hierarchy)
  3589. break;
  3590. tmp = res_counter_read_u64(&memcg->res, RES_LIMIT);
  3591. min_limit = min(min_limit, tmp);
  3592. tmp = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
  3593. min_memsw_limit = min(min_memsw_limit, tmp);
  3594. }
  3595. out:
  3596. *mem_limit = min_limit;
  3597. *memsw_limit = min_memsw_limit;
  3598. return;
  3599. }
  3600. static int mem_cgroup_reset(struct cgroup *cont, unsigned int event)
  3601. {
  3602. struct mem_cgroup *mem;
  3603. int type, name;
  3604. mem = mem_cgroup_from_cont(cont);
  3605. type = MEMFILE_TYPE(event);
  3606. name = MEMFILE_ATTR(event);
  3607. switch (name) {
  3608. case RES_MAX_USAGE:
  3609. if (type == _MEM)
  3610. res_counter_reset_max(&mem->res);
  3611. else
  3612. res_counter_reset_max(&mem->memsw);
  3613. break;
  3614. case RES_FAILCNT:
  3615. if (type == _MEM)
  3616. res_counter_reset_failcnt(&mem->res);
  3617. else
  3618. res_counter_reset_failcnt(&mem->memsw);
  3619. break;
  3620. }
  3621. return 0;
  3622. }
  3623. static u64 mem_cgroup_move_charge_read(struct cgroup *cgrp,
  3624. struct cftype *cft)
  3625. {
  3626. return mem_cgroup_from_cont(cgrp)->move_charge_at_immigrate;
  3627. }
  3628. #ifdef CONFIG_MMU
  3629. static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
  3630. struct cftype *cft, u64 val)
  3631. {
  3632. struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
  3633. if (val >= (1 << NR_MOVE_TYPE))
  3634. return -EINVAL;
  3635. /*
  3636. * We check this value several times in both in can_attach() and
  3637. * attach(), so we need cgroup lock to prevent this value from being
  3638. * inconsistent.
  3639. */
  3640. cgroup_lock();
  3641. mem->move_charge_at_immigrate = val;
  3642. cgroup_unlock();
  3643. return 0;
  3644. }
  3645. #else
  3646. static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
  3647. struct cftype *cft, u64 val)
  3648. {
  3649. return -ENOSYS;
  3650. }
  3651. #endif
  3652. /* For read statistics */
  3653. enum {
  3654. MCS_CACHE,
  3655. MCS_RSS,
  3656. MCS_FILE_MAPPED,
  3657. MCS_PGPGIN,
  3658. MCS_PGPGOUT,
  3659. MCS_SWAP,
  3660. MCS_PGFAULT,
  3661. MCS_PGMAJFAULT,
  3662. MCS_INACTIVE_ANON,
  3663. MCS_ACTIVE_ANON,
  3664. MCS_INACTIVE_FILE,
  3665. MCS_ACTIVE_FILE,
  3666. MCS_UNEVICTABLE,
  3667. NR_MCS_STAT,
  3668. };
  3669. struct mcs_total_stat {
  3670. s64 stat[NR_MCS_STAT];
  3671. };
  3672. struct {
  3673. char *local_name;
  3674. char *total_name;
  3675. } memcg_stat_strings[NR_MCS_STAT] = {
  3676. {"cache", "total_cache"},
  3677. {"rss", "total_rss"},
  3678. {"mapped_file", "total_mapped_file"},
  3679. {"pgpgin", "total_pgpgin"},
  3680. {"pgpgout", "total_pgpgout"},
  3681. {"swap", "total_swap"},
  3682. {"pgfault", "total_pgfault"},
  3683. {"pgmajfault", "total_pgmajfault"},
  3684. {"inactive_anon", "total_inactive_anon"},
  3685. {"active_anon", "total_active_anon"},
  3686. {"inactive_file", "total_inactive_file"},
  3687. {"active_file", "total_active_file"},
  3688. {"unevictable", "total_unevictable"}
  3689. };
  3690. static void
  3691. mem_cgroup_get_local_stat(struct mem_cgroup *mem, struct mcs_total_stat *s)
  3692. {
  3693. s64 val;
  3694. /* per cpu stat */
  3695. val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_CACHE);
  3696. s->stat[MCS_CACHE] += val * PAGE_SIZE;
  3697. val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_RSS);
  3698. s->stat[MCS_RSS] += val * PAGE_SIZE;
  3699. val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_FILE_MAPPED);
  3700. s->stat[MCS_FILE_MAPPED] += val * PAGE_SIZE;
  3701. val = mem_cgroup_read_events(mem, MEM_CGROUP_EVENTS_PGPGIN);
  3702. s->stat[MCS_PGPGIN] += val;
  3703. val = mem_cgroup_read_events(mem, MEM_CGROUP_EVENTS_PGPGOUT);
  3704. s->stat[MCS_PGPGOUT] += val;
  3705. if (do_swap_account) {
  3706. val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_SWAPOUT);
  3707. s->stat[MCS_SWAP] += val * PAGE_SIZE;
  3708. }
  3709. val = mem_cgroup_read_events(mem, MEM_CGROUP_EVENTS_PGFAULT);
  3710. s->stat[MCS_PGFAULT] += val;
  3711. val = mem_cgroup_read_events(mem, MEM_CGROUP_EVENTS_PGMAJFAULT);
  3712. s->stat[MCS_PGMAJFAULT] += val;
  3713. /* per zone stat */
  3714. val = mem_cgroup_nr_lru_pages(mem, BIT(LRU_INACTIVE_ANON));
  3715. s->stat[MCS_INACTIVE_ANON] += val * PAGE_SIZE;
  3716. val = mem_cgroup_nr_lru_pages(mem, BIT(LRU_ACTIVE_ANON));
  3717. s->stat[MCS_ACTIVE_ANON] += val * PAGE_SIZE;
  3718. val = mem_cgroup_nr_lru_pages(mem, BIT(LRU_INACTIVE_FILE));
  3719. s->stat[MCS_INACTIVE_FILE] += val * PAGE_SIZE;
  3720. val = mem_cgroup_nr_lru_pages(mem, BIT(LRU_ACTIVE_FILE));
  3721. s->stat[MCS_ACTIVE_FILE] += val * PAGE_SIZE;
  3722. val = mem_cgroup_nr_lru_pages(mem, BIT(LRU_UNEVICTABLE));
  3723. s->stat[MCS_UNEVICTABLE] += val * PAGE_SIZE;
  3724. }
  3725. static void
  3726. mem_cgroup_get_total_stat(struct mem_cgroup *mem, struct mcs_total_stat *s)
  3727. {
  3728. struct mem_cgroup *iter;
  3729. for_each_mem_cgroup_tree(iter, mem)
  3730. mem_cgroup_get_local_stat(iter, s);
  3731. }
  3732. #ifdef CONFIG_NUMA
  3733. static int mem_control_numa_stat_show(struct seq_file *m, void *arg)
  3734. {
  3735. int nid;
  3736. unsigned long total_nr, file_nr, anon_nr, unevictable_nr;
  3737. unsigned long node_nr;
  3738. struct cgroup *cont = m->private;
  3739. struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
  3740. total_nr = mem_cgroup_nr_lru_pages(mem_cont, LRU_ALL);
  3741. seq_printf(m, "total=%lu", total_nr);
  3742. for_each_node_state(nid, N_HIGH_MEMORY) {
  3743. node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid, LRU_ALL);
  3744. seq_printf(m, " N%d=%lu", nid, node_nr);
  3745. }
  3746. seq_putc(m, '\n');
  3747. file_nr = mem_cgroup_nr_lru_pages(mem_cont, LRU_ALL_FILE);
  3748. seq_printf(m, "file=%lu", file_nr);
  3749. for_each_node_state(nid, N_HIGH_MEMORY) {
  3750. node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid,
  3751. LRU_ALL_FILE);
  3752. seq_printf(m, " N%d=%lu", nid, node_nr);
  3753. }
  3754. seq_putc(m, '\n');
  3755. anon_nr = mem_cgroup_nr_lru_pages(mem_cont, LRU_ALL_ANON);
  3756. seq_printf(m, "anon=%lu", anon_nr);
  3757. for_each_node_state(nid, N_HIGH_MEMORY) {
  3758. node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid,
  3759. LRU_ALL_ANON);
  3760. seq_printf(m, " N%d=%lu", nid, node_nr);
  3761. }
  3762. seq_putc(m, '\n');
  3763. unevictable_nr = mem_cgroup_nr_lru_pages(mem_cont, BIT(LRU_UNEVICTABLE));
  3764. seq_printf(m, "unevictable=%lu", unevictable_nr);
  3765. for_each_node_state(nid, N_HIGH_MEMORY) {
  3766. node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid,
  3767. BIT(LRU_UNEVICTABLE));
  3768. seq_printf(m, " N%d=%lu", nid, node_nr);
  3769. }
  3770. seq_putc(m, '\n');
  3771. return 0;
  3772. }
  3773. #endif /* CONFIG_NUMA */
  3774. static int mem_control_stat_show(struct cgroup *cont, struct cftype *cft,
  3775. struct cgroup_map_cb *cb)
  3776. {
  3777. struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
  3778. struct mcs_total_stat mystat;
  3779. int i;
  3780. memset(&mystat, 0, sizeof(mystat));
  3781. mem_cgroup_get_local_stat(mem_cont, &mystat);
  3782. for (i = 0; i < NR_MCS_STAT; i++) {
  3783. if (i == MCS_SWAP && !do_swap_account)
  3784. continue;
  3785. cb->fill(cb, memcg_stat_strings[i].local_name, mystat.stat[i]);
  3786. }
  3787. /* Hierarchical information */
  3788. {
  3789. unsigned long long limit, memsw_limit;
  3790. memcg_get_hierarchical_limit(mem_cont, &limit, &memsw_limit);
  3791. cb->fill(cb, "hierarchical_memory_limit", limit);
  3792. if (do_swap_account)
  3793. cb->fill(cb, "hierarchical_memsw_limit", memsw_limit);
  3794. }
  3795. memset(&mystat, 0, sizeof(mystat));
  3796. mem_cgroup_get_total_stat(mem_cont, &mystat);
  3797. for (i = 0; i < NR_MCS_STAT; i++) {
  3798. if (i == MCS_SWAP && !do_swap_account)
  3799. continue;
  3800. cb->fill(cb, memcg_stat_strings[i].total_name, mystat.stat[i]);
  3801. }
  3802. #ifdef CONFIG_DEBUG_VM
  3803. cb->fill(cb, "inactive_ratio", calc_inactive_ratio(mem_cont, NULL));
  3804. {
  3805. int nid, zid;
  3806. struct mem_cgroup_per_zone *mz;
  3807. unsigned long recent_rotated[2] = {0, 0};
  3808. unsigned long recent_scanned[2] = {0, 0};
  3809. for_each_online_node(nid)
  3810. for (zid = 0; zid < MAX_NR_ZONES; zid++) {
  3811. mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
  3812. recent_rotated[0] +=
  3813. mz->reclaim_stat.recent_rotated[0];
  3814. recent_rotated[1] +=
  3815. mz->reclaim_stat.recent_rotated[1];
  3816. recent_scanned[0] +=
  3817. mz->reclaim_stat.recent_scanned[0];
  3818. recent_scanned[1] +=
  3819. mz->reclaim_stat.recent_scanned[1];
  3820. }
  3821. cb->fill(cb, "recent_rotated_anon", recent_rotated[0]);
  3822. cb->fill(cb, "recent_rotated_file", recent_rotated[1]);
  3823. cb->fill(cb, "recent_scanned_anon", recent_scanned[0]);
  3824. cb->fill(cb, "recent_scanned_file", recent_scanned[1]);
  3825. }
  3826. #endif
  3827. return 0;
  3828. }
  3829. static u64 mem_cgroup_swappiness_read(struct cgroup *cgrp, struct cftype *cft)
  3830. {
  3831. struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
  3832. return mem_cgroup_swappiness(memcg);
  3833. }
  3834. static int mem_cgroup_swappiness_write(struct cgroup *cgrp, struct cftype *cft,
  3835. u64 val)
  3836. {
  3837. struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
  3838. struct mem_cgroup *parent;
  3839. if (val > 100)
  3840. return -EINVAL;
  3841. if (cgrp->parent == NULL)
  3842. return -EINVAL;
  3843. parent = mem_cgroup_from_cont(cgrp->parent);
  3844. cgroup_lock();
  3845. /* If under hierarchy, only empty-root can set this value */
  3846. if ((parent->use_hierarchy) ||
  3847. (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
  3848. cgroup_unlock();
  3849. return -EINVAL;
  3850. }
  3851. memcg->swappiness = val;
  3852. cgroup_unlock();
  3853. return 0;
  3854. }
  3855. static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
  3856. {
  3857. struct mem_cgroup_threshold_ary *t;
  3858. u64 usage;
  3859. int i;
  3860. rcu_read_lock();
  3861. if (!swap)
  3862. t = rcu_dereference(memcg->thresholds.primary);
  3863. else
  3864. t = rcu_dereference(memcg->memsw_thresholds.primary);
  3865. if (!t)
  3866. goto unlock;
  3867. usage = mem_cgroup_usage(memcg, swap);
  3868. /*
  3869. * current_threshold points to threshold just below usage.
  3870. * If it's not true, a threshold was crossed after last
  3871. * call of __mem_cgroup_threshold().
  3872. */
  3873. i = t->current_threshold;
  3874. /*
  3875. * Iterate backward over array of thresholds starting from
  3876. * current_threshold and check if a threshold is crossed.
  3877. * If none of thresholds below usage is crossed, we read
  3878. * only one element of the array here.
  3879. */
  3880. for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
  3881. eventfd_signal(t->entries[i].eventfd, 1);
  3882. /* i = current_threshold + 1 */
  3883. i++;
  3884. /*
  3885. * Iterate forward over array of thresholds starting from
  3886. * current_threshold+1 and check if a threshold is crossed.
  3887. * If none of thresholds above usage is crossed, we read
  3888. * only one element of the array here.
  3889. */
  3890. for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
  3891. eventfd_signal(t->entries[i].eventfd, 1);
  3892. /* Update current_threshold */
  3893. t->current_threshold = i - 1;
  3894. unlock:
  3895. rcu_read_unlock();
  3896. }
  3897. static void mem_cgroup_threshold(struct mem_cgroup *memcg)
  3898. {
  3899. while (memcg) {
  3900. __mem_cgroup_threshold(memcg, false);
  3901. if (do_swap_account)
  3902. __mem_cgroup_threshold(memcg, true);
  3903. memcg = parent_mem_cgroup(memcg);
  3904. }
  3905. }
  3906. static int compare_thresholds(const void *a, const void *b)
  3907. {
  3908. const struct mem_cgroup_threshold *_a = a;
  3909. const struct mem_cgroup_threshold *_b = b;
  3910. return _a->threshold - _b->threshold;
  3911. }
  3912. static int mem_cgroup_oom_notify_cb(struct mem_cgroup *mem)
  3913. {
  3914. struct mem_cgroup_eventfd_list *ev;
  3915. list_for_each_entry(ev, &mem->oom_notify, list)
  3916. eventfd_signal(ev->eventfd, 1);
  3917. return 0;
  3918. }
  3919. static void mem_cgroup_oom_notify(struct mem_cgroup *mem)
  3920. {
  3921. struct mem_cgroup *iter;
  3922. for_each_mem_cgroup_tree(iter, mem)
  3923. mem_cgroup_oom_notify_cb(iter);
  3924. }
  3925. static int mem_cgroup_usage_register_event(struct cgroup *cgrp,
  3926. struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
  3927. {
  3928. struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
  3929. struct mem_cgroup_thresholds *thresholds;
  3930. struct mem_cgroup_threshold_ary *new;
  3931. int type = MEMFILE_TYPE(cft->private);
  3932. u64 threshold, usage;
  3933. int i, size, ret;
  3934. ret = res_counter_memparse_write_strategy(args, &threshold);
  3935. if (ret)
  3936. return ret;
  3937. mutex_lock(&memcg->thresholds_lock);
  3938. if (type == _MEM)
  3939. thresholds = &memcg->thresholds;
  3940. else if (type == _MEMSWAP)
  3941. thresholds = &memcg->memsw_thresholds;
  3942. else
  3943. BUG();
  3944. usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
  3945. /* Check if a threshold crossed before adding a new one */
  3946. if (thresholds->primary)
  3947. __mem_cgroup_threshold(memcg, type == _MEMSWAP);
  3948. size = thresholds->primary ? thresholds->primary->size + 1 : 1;
  3949. /* Allocate memory for new array of thresholds */
  3950. new = kmalloc(sizeof(*new) + size * sizeof(struct mem_cgroup_threshold),
  3951. GFP_KERNEL);
  3952. if (!new) {
  3953. ret = -ENOMEM;
  3954. goto unlock;
  3955. }
  3956. new->size = size;
  3957. /* Copy thresholds (if any) to new array */
  3958. if (thresholds->primary) {
  3959. memcpy(new->entries, thresholds->primary->entries, (size - 1) *
  3960. sizeof(struct mem_cgroup_threshold));
  3961. }
  3962. /* Add new threshold */
  3963. new->entries[size - 1].eventfd = eventfd;
  3964. new->entries[size - 1].threshold = threshold;
  3965. /* Sort thresholds. Registering of new threshold isn't time-critical */
  3966. sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
  3967. compare_thresholds, NULL);
  3968. /* Find current threshold */
  3969. new->current_threshold = -1;
  3970. for (i = 0; i < size; i++) {
  3971. if (new->entries[i].threshold < usage) {
  3972. /*
  3973. * new->current_threshold will not be used until
  3974. * rcu_assign_pointer(), so it's safe to increment
  3975. * it here.
  3976. */
  3977. ++new->current_threshold;
  3978. }
  3979. }
  3980. /* Free old spare buffer and save old primary buffer as spare */
  3981. kfree(thresholds->spare);
  3982. thresholds->spare = thresholds->primary;
  3983. rcu_assign_pointer(thresholds->primary, new);
  3984. /* To be sure that nobody uses thresholds */
  3985. synchronize_rcu();
  3986. unlock:
  3987. mutex_unlock(&memcg->thresholds_lock);
  3988. return ret;
  3989. }
  3990. static void mem_cgroup_usage_unregister_event(struct cgroup *cgrp,
  3991. struct cftype *cft, struct eventfd_ctx *eventfd)
  3992. {
  3993. struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
  3994. struct mem_cgroup_thresholds *thresholds;
  3995. struct mem_cgroup_threshold_ary *new;
  3996. int type = MEMFILE_TYPE(cft->private);
  3997. u64 usage;
  3998. int i, j, size;
  3999. mutex_lock(&memcg->thresholds_lock);
  4000. if (type == _MEM)
  4001. thresholds = &memcg->thresholds;
  4002. else if (type == _MEMSWAP)
  4003. thresholds = &memcg->memsw_thresholds;
  4004. else
  4005. BUG();
  4006. /*
  4007. * Something went wrong if we trying to unregister a threshold
  4008. * if we don't have thresholds
  4009. */
  4010. BUG_ON(!thresholds);
  4011. usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
  4012. /* Check if a threshold crossed before removing */
  4013. __mem_cgroup_threshold(memcg, type == _MEMSWAP);
  4014. /* Calculate new number of threshold */
  4015. size = 0;
  4016. for (i = 0; i < thresholds->primary->size; i++) {
  4017. if (thresholds->primary->entries[i].eventfd != eventfd)
  4018. size++;
  4019. }
  4020. new = thresholds->spare;
  4021. /* Set thresholds array to NULL if we don't have thresholds */
  4022. if (!size) {
  4023. kfree(new);
  4024. new = NULL;
  4025. goto swap_buffers;
  4026. }
  4027. new->size = size;
  4028. /* Copy thresholds and find current threshold */
  4029. new->current_threshold = -1;
  4030. for (i = 0, j = 0; i < thresholds->primary->size; i++) {
  4031. if (thresholds->primary->entries[i].eventfd == eventfd)
  4032. continue;
  4033. new->entries[j] = thresholds->primary->entries[i];
  4034. if (new->entries[j].threshold < usage) {
  4035. /*
  4036. * new->current_threshold will not be used
  4037. * until rcu_assign_pointer(), so it's safe to increment
  4038. * it here.
  4039. */
  4040. ++new->current_threshold;
  4041. }
  4042. j++;
  4043. }
  4044. swap_buffers:
  4045. /* Swap primary and spare array */
  4046. thresholds->spare = thresholds->primary;
  4047. rcu_assign_pointer(thresholds->primary, new);
  4048. /* To be sure that nobody uses thresholds */
  4049. synchronize_rcu();
  4050. mutex_unlock(&memcg->thresholds_lock);
  4051. }
  4052. static int mem_cgroup_oom_register_event(struct cgroup *cgrp,
  4053. struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
  4054. {
  4055. struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
  4056. struct mem_cgroup_eventfd_list *event;
  4057. int type = MEMFILE_TYPE(cft->private);
  4058. BUG_ON(type != _OOM_TYPE);
  4059. event = kmalloc(sizeof(*event), GFP_KERNEL);
  4060. if (!event)
  4061. return -ENOMEM;
  4062. spin_lock(&memcg_oom_lock);
  4063. event->eventfd = eventfd;
  4064. list_add(&event->list, &memcg->oom_notify);
  4065. /* already in OOM ? */
  4066. if (atomic_read(&memcg->under_oom))
  4067. eventfd_signal(eventfd, 1);
  4068. spin_unlock(&memcg_oom_lock);
  4069. return 0;
  4070. }
  4071. static void mem_cgroup_oom_unregister_event(struct cgroup *cgrp,
  4072. struct cftype *cft, struct eventfd_ctx *eventfd)
  4073. {
  4074. struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
  4075. struct mem_cgroup_eventfd_list *ev, *tmp;
  4076. int type = MEMFILE_TYPE(cft->private);
  4077. BUG_ON(type != _OOM_TYPE);
  4078. spin_lock(&memcg_oom_lock);
  4079. list_for_each_entry_safe(ev, tmp, &mem->oom_notify, list) {
  4080. if (ev->eventfd == eventfd) {
  4081. list_del(&ev->list);
  4082. kfree(ev);
  4083. }
  4084. }
  4085. spin_unlock(&memcg_oom_lock);
  4086. }
  4087. static int mem_cgroup_oom_control_read(struct cgroup *cgrp,
  4088. struct cftype *cft, struct cgroup_map_cb *cb)
  4089. {
  4090. struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
  4091. cb->fill(cb, "oom_kill_disable", mem->oom_kill_disable);
  4092. if (atomic_read(&mem->under_oom))
  4093. cb->fill(cb, "under_oom", 1);
  4094. else
  4095. cb->fill(cb, "under_oom", 0);
  4096. return 0;
  4097. }
  4098. static int mem_cgroup_oom_control_write(struct cgroup *cgrp,
  4099. struct cftype *cft, u64 val)
  4100. {
  4101. struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
  4102. struct mem_cgroup *parent;
  4103. /* cannot set to root cgroup and only 0 and 1 are allowed */
  4104. if (!cgrp->parent || !((val == 0) || (val == 1)))
  4105. return -EINVAL;
  4106. parent = mem_cgroup_from_cont(cgrp->parent);
  4107. cgroup_lock();
  4108. /* oom-kill-disable is a flag for subhierarchy. */
  4109. if ((parent->use_hierarchy) ||
  4110. (mem->use_hierarchy && !list_empty(&cgrp->children))) {
  4111. cgroup_unlock();
  4112. return -EINVAL;
  4113. }
  4114. mem->oom_kill_disable = val;
  4115. if (!val)
  4116. memcg_oom_recover(mem);
  4117. cgroup_unlock();
  4118. return 0;
  4119. }
  4120. #ifdef CONFIG_NUMA
  4121. static const struct file_operations mem_control_numa_stat_file_operations = {
  4122. .read = seq_read,
  4123. .llseek = seq_lseek,
  4124. .release = single_release,
  4125. };
  4126. static int mem_control_numa_stat_open(struct inode *unused, struct file *file)
  4127. {
  4128. struct cgroup *cont = file->f_dentry->d_parent->d_fsdata;
  4129. file->f_op = &mem_control_numa_stat_file_operations;
  4130. return single_open(file, mem_control_numa_stat_show, cont);
  4131. }
  4132. #endif /* CONFIG_NUMA */
  4133. static int mem_cgroup_vmscan_stat_read(struct cgroup *cgrp,
  4134. struct cftype *cft,
  4135. struct cgroup_map_cb *cb)
  4136. {
  4137. struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
  4138. char string[64];
  4139. int i;
  4140. for (i = 0; i < NR_SCANSTATS; i++) {
  4141. strcpy(string, scanstat_string[i]);
  4142. strcat(string, SCANSTAT_WORD_LIMIT);
  4143. cb->fill(cb, string, mem->scanstat.stats[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. cb->fill(cb, string, mem->scanstat.stats[SCAN_BY_SYSTEM][i]);
  4149. }
  4150. for (i = 0; i < NR_SCANSTATS; i++) {
  4151. strcpy(string, scanstat_string[i]);
  4152. strcat(string, SCANSTAT_WORD_LIMIT);
  4153. strcat(string, SCANSTAT_WORD_HIERARCHY);
  4154. cb->fill(cb, string, mem->scanstat.rootstats[SCAN_BY_LIMIT][i]);
  4155. }
  4156. for (i = 0; i < NR_SCANSTATS; i++) {
  4157. strcpy(string, scanstat_string[i]);
  4158. strcat(string, SCANSTAT_WORD_SYSTEM);
  4159. strcat(string, SCANSTAT_WORD_HIERARCHY);
  4160. cb->fill(cb, string, mem->scanstat.rootstats[SCAN_BY_SYSTEM][i]);
  4161. }
  4162. return 0;
  4163. }
  4164. static int mem_cgroup_reset_vmscan_stat(struct cgroup *cgrp,
  4165. unsigned int event)
  4166. {
  4167. struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
  4168. spin_lock(&mem->scanstat.lock);
  4169. memset(&mem->scanstat.stats, 0, sizeof(mem->scanstat.stats));
  4170. memset(&mem->scanstat.rootstats, 0, sizeof(mem->scanstat.rootstats));
  4171. spin_unlock(&mem->scanstat.lock);
  4172. return 0;
  4173. }
  4174. static struct cftype mem_cgroup_files[] = {
  4175. {
  4176. .name = "usage_in_bytes",
  4177. .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
  4178. .read_u64 = mem_cgroup_read,
  4179. .register_event = mem_cgroup_usage_register_event,
  4180. .unregister_event = mem_cgroup_usage_unregister_event,
  4181. },
  4182. {
  4183. .name = "max_usage_in_bytes",
  4184. .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
  4185. .trigger = mem_cgroup_reset,
  4186. .read_u64 = mem_cgroup_read,
  4187. },
  4188. {
  4189. .name = "limit_in_bytes",
  4190. .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
  4191. .write_string = mem_cgroup_write,
  4192. .read_u64 = mem_cgroup_read,
  4193. },
  4194. {
  4195. .name = "soft_limit_in_bytes",
  4196. .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
  4197. .write_string = mem_cgroup_write,
  4198. .read_u64 = mem_cgroup_read,
  4199. },
  4200. {
  4201. .name = "failcnt",
  4202. .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
  4203. .trigger = mem_cgroup_reset,
  4204. .read_u64 = mem_cgroup_read,
  4205. },
  4206. {
  4207. .name = "stat",
  4208. .read_map = mem_control_stat_show,
  4209. },
  4210. {
  4211. .name = "force_empty",
  4212. .trigger = mem_cgroup_force_empty_write,
  4213. },
  4214. {
  4215. .name = "use_hierarchy",
  4216. .write_u64 = mem_cgroup_hierarchy_write,
  4217. .read_u64 = mem_cgroup_hierarchy_read,
  4218. },
  4219. {
  4220. .name = "swappiness",
  4221. .read_u64 = mem_cgroup_swappiness_read,
  4222. .write_u64 = mem_cgroup_swappiness_write,
  4223. },
  4224. {
  4225. .name = "move_charge_at_immigrate",
  4226. .read_u64 = mem_cgroup_move_charge_read,
  4227. .write_u64 = mem_cgroup_move_charge_write,
  4228. },
  4229. {
  4230. .name = "oom_control",
  4231. .read_map = mem_cgroup_oom_control_read,
  4232. .write_u64 = mem_cgroup_oom_control_write,
  4233. .register_event = mem_cgroup_oom_register_event,
  4234. .unregister_event = mem_cgroup_oom_unregister_event,
  4235. .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
  4236. },
  4237. #ifdef CONFIG_NUMA
  4238. {
  4239. .name = "numa_stat",
  4240. .open = mem_control_numa_stat_open,
  4241. .mode = S_IRUGO,
  4242. },
  4243. #endif
  4244. {
  4245. .name = "vmscan_stat",
  4246. .read_map = mem_cgroup_vmscan_stat_read,
  4247. .trigger = mem_cgroup_reset_vmscan_stat,
  4248. },
  4249. };
  4250. #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
  4251. static struct cftype memsw_cgroup_files[] = {
  4252. {
  4253. .name = "memsw.usage_in_bytes",
  4254. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
  4255. .read_u64 = mem_cgroup_read,
  4256. .register_event = mem_cgroup_usage_register_event,
  4257. .unregister_event = mem_cgroup_usage_unregister_event,
  4258. },
  4259. {
  4260. .name = "memsw.max_usage_in_bytes",
  4261. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
  4262. .trigger = mem_cgroup_reset,
  4263. .read_u64 = mem_cgroup_read,
  4264. },
  4265. {
  4266. .name = "memsw.limit_in_bytes",
  4267. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
  4268. .write_string = mem_cgroup_write,
  4269. .read_u64 = mem_cgroup_read,
  4270. },
  4271. {
  4272. .name = "memsw.failcnt",
  4273. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
  4274. .trigger = mem_cgroup_reset,
  4275. .read_u64 = mem_cgroup_read,
  4276. },
  4277. };
  4278. static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
  4279. {
  4280. if (!do_swap_account)
  4281. return 0;
  4282. return cgroup_add_files(cont, ss, memsw_cgroup_files,
  4283. ARRAY_SIZE(memsw_cgroup_files));
  4284. };
  4285. #else
  4286. static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
  4287. {
  4288. return 0;
  4289. }
  4290. #endif
  4291. static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
  4292. {
  4293. struct mem_cgroup_per_node *pn;
  4294. struct mem_cgroup_per_zone *mz;
  4295. enum lru_list l;
  4296. int zone, tmp = node;
  4297. /*
  4298. * This routine is called against possible nodes.
  4299. * But it's BUG to call kmalloc() against offline node.
  4300. *
  4301. * TODO: this routine can waste much memory for nodes which will
  4302. * never be onlined. It's better to use memory hotplug callback
  4303. * function.
  4304. */
  4305. if (!node_state(node, N_NORMAL_MEMORY))
  4306. tmp = -1;
  4307. pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
  4308. if (!pn)
  4309. return 1;
  4310. mem->info.nodeinfo[node] = pn;
  4311. for (zone = 0; zone < MAX_NR_ZONES; zone++) {
  4312. mz = &pn->zoneinfo[zone];
  4313. for_each_lru(l)
  4314. INIT_LIST_HEAD(&mz->lists[l]);
  4315. mz->usage_in_excess = 0;
  4316. mz->on_tree = false;
  4317. mz->mem = mem;
  4318. }
  4319. return 0;
  4320. }
  4321. static void free_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
  4322. {
  4323. kfree(mem->info.nodeinfo[node]);
  4324. }
  4325. static struct mem_cgroup *mem_cgroup_alloc(void)
  4326. {
  4327. struct mem_cgroup *mem;
  4328. int size = sizeof(struct mem_cgroup);
  4329. /* Can be very big if MAX_NUMNODES is very big */
  4330. if (size < PAGE_SIZE)
  4331. mem = kzalloc(size, GFP_KERNEL);
  4332. else
  4333. mem = vzalloc(size);
  4334. if (!mem)
  4335. return NULL;
  4336. mem->stat = alloc_percpu(struct mem_cgroup_stat_cpu);
  4337. if (!mem->stat)
  4338. goto out_free;
  4339. spin_lock_init(&mem->pcp_counter_lock);
  4340. return mem;
  4341. out_free:
  4342. if (size < PAGE_SIZE)
  4343. kfree(mem);
  4344. else
  4345. vfree(mem);
  4346. return NULL;
  4347. }
  4348. /*
  4349. * At destroying mem_cgroup, references from swap_cgroup can remain.
  4350. * (scanning all at force_empty is too costly...)
  4351. *
  4352. * Instead of clearing all references at force_empty, we remember
  4353. * the number of reference from swap_cgroup and free mem_cgroup when
  4354. * it goes down to 0.
  4355. *
  4356. * Removal of cgroup itself succeeds regardless of refs from swap.
  4357. */
  4358. static void __mem_cgroup_free(struct mem_cgroup *mem)
  4359. {
  4360. int node;
  4361. mem_cgroup_remove_from_trees(mem);
  4362. free_css_id(&mem_cgroup_subsys, &mem->css);
  4363. for_each_node_state(node, N_POSSIBLE)
  4364. free_mem_cgroup_per_zone_info(mem, node);
  4365. free_percpu(mem->stat);
  4366. if (sizeof(struct mem_cgroup) < PAGE_SIZE)
  4367. kfree(mem);
  4368. else
  4369. vfree(mem);
  4370. }
  4371. static void mem_cgroup_get(struct mem_cgroup *mem)
  4372. {
  4373. atomic_inc(&mem->refcnt);
  4374. }
  4375. static void __mem_cgroup_put(struct mem_cgroup *mem, int count)
  4376. {
  4377. if (atomic_sub_and_test(count, &mem->refcnt)) {
  4378. struct mem_cgroup *parent = parent_mem_cgroup(mem);
  4379. __mem_cgroup_free(mem);
  4380. if (parent)
  4381. mem_cgroup_put(parent);
  4382. }
  4383. }
  4384. static void mem_cgroup_put(struct mem_cgroup *mem)
  4385. {
  4386. __mem_cgroup_put(mem, 1);
  4387. }
  4388. /*
  4389. * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
  4390. */
  4391. static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *mem)
  4392. {
  4393. if (!mem->res.parent)
  4394. return NULL;
  4395. return mem_cgroup_from_res_counter(mem->res.parent, res);
  4396. }
  4397. #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
  4398. static void __init enable_swap_cgroup(void)
  4399. {
  4400. if (!mem_cgroup_disabled() && really_do_swap_account)
  4401. do_swap_account = 1;
  4402. }
  4403. #else
  4404. static void __init enable_swap_cgroup(void)
  4405. {
  4406. }
  4407. #endif
  4408. static int mem_cgroup_soft_limit_tree_init(void)
  4409. {
  4410. struct mem_cgroup_tree_per_node *rtpn;
  4411. struct mem_cgroup_tree_per_zone *rtpz;
  4412. int tmp, node, zone;
  4413. for_each_node_state(node, N_POSSIBLE) {
  4414. tmp = node;
  4415. if (!node_state(node, N_NORMAL_MEMORY))
  4416. tmp = -1;
  4417. rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, tmp);
  4418. if (!rtpn)
  4419. return 1;
  4420. soft_limit_tree.rb_tree_per_node[node] = rtpn;
  4421. for (zone = 0; zone < MAX_NR_ZONES; zone++) {
  4422. rtpz = &rtpn->rb_tree_per_zone[zone];
  4423. rtpz->rb_root = RB_ROOT;
  4424. spin_lock_init(&rtpz->lock);
  4425. }
  4426. }
  4427. return 0;
  4428. }
  4429. static struct cgroup_subsys_state * __ref
  4430. mem_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cont)
  4431. {
  4432. struct mem_cgroup *mem, *parent;
  4433. long error = -ENOMEM;
  4434. int node;
  4435. mem = mem_cgroup_alloc();
  4436. if (!mem)
  4437. return ERR_PTR(error);
  4438. for_each_node_state(node, N_POSSIBLE)
  4439. if (alloc_mem_cgroup_per_zone_info(mem, node))
  4440. goto free_out;
  4441. /* root ? */
  4442. if (cont->parent == NULL) {
  4443. int cpu;
  4444. enable_swap_cgroup();
  4445. parent = NULL;
  4446. root_mem_cgroup = mem;
  4447. if (mem_cgroup_soft_limit_tree_init())
  4448. goto free_out;
  4449. for_each_possible_cpu(cpu) {
  4450. struct memcg_stock_pcp *stock =
  4451. &per_cpu(memcg_stock, cpu);
  4452. INIT_WORK(&stock->work, drain_local_stock);
  4453. }
  4454. hotcpu_notifier(memcg_cpu_hotplug_callback, 0);
  4455. } else {
  4456. parent = mem_cgroup_from_cont(cont->parent);
  4457. mem->use_hierarchy = parent->use_hierarchy;
  4458. mem->oom_kill_disable = parent->oom_kill_disable;
  4459. }
  4460. if (parent && parent->use_hierarchy) {
  4461. res_counter_init(&mem->res, &parent->res);
  4462. res_counter_init(&mem->memsw, &parent->memsw);
  4463. /*
  4464. * We increment refcnt of the parent to ensure that we can
  4465. * safely access it on res_counter_charge/uncharge.
  4466. * This refcnt will be decremented when freeing this
  4467. * mem_cgroup(see mem_cgroup_put).
  4468. */
  4469. mem_cgroup_get(parent);
  4470. } else {
  4471. res_counter_init(&mem->res, NULL);
  4472. res_counter_init(&mem->memsw, NULL);
  4473. }
  4474. mem->last_scanned_child = 0;
  4475. mem->last_scanned_node = MAX_NUMNODES;
  4476. INIT_LIST_HEAD(&mem->oom_notify);
  4477. if (parent)
  4478. mem->swappiness = mem_cgroup_swappiness(parent);
  4479. atomic_set(&mem->refcnt, 1);
  4480. mem->move_charge_at_immigrate = 0;
  4481. mutex_init(&mem->thresholds_lock);
  4482. spin_lock_init(&mem->scanstat.lock);
  4483. return &mem->css;
  4484. free_out:
  4485. __mem_cgroup_free(mem);
  4486. root_mem_cgroup = NULL;
  4487. return ERR_PTR(error);
  4488. }
  4489. static int mem_cgroup_pre_destroy(struct cgroup_subsys *ss,
  4490. struct cgroup *cont)
  4491. {
  4492. struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
  4493. return mem_cgroup_force_empty(mem, false);
  4494. }
  4495. static void mem_cgroup_destroy(struct cgroup_subsys *ss,
  4496. struct cgroup *cont)
  4497. {
  4498. struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
  4499. mem_cgroup_put(mem);
  4500. }
  4501. static int mem_cgroup_populate(struct cgroup_subsys *ss,
  4502. struct cgroup *cont)
  4503. {
  4504. int ret;
  4505. ret = cgroup_add_files(cont, ss, mem_cgroup_files,
  4506. ARRAY_SIZE(mem_cgroup_files));
  4507. if (!ret)
  4508. ret = register_memsw_files(cont, ss);
  4509. return ret;
  4510. }
  4511. #ifdef CONFIG_MMU
  4512. /* Handlers for move charge at task migration. */
  4513. #define PRECHARGE_COUNT_AT_ONCE 256
  4514. static int mem_cgroup_do_precharge(unsigned long count)
  4515. {
  4516. int ret = 0;
  4517. int batch_count = PRECHARGE_COUNT_AT_ONCE;
  4518. struct mem_cgroup *mem = mc.to;
  4519. if (mem_cgroup_is_root(mem)) {
  4520. mc.precharge += count;
  4521. /* we don't need css_get for root */
  4522. return ret;
  4523. }
  4524. /* try to charge at once */
  4525. if (count > 1) {
  4526. struct res_counter *dummy;
  4527. /*
  4528. * "mem" cannot be under rmdir() because we've already checked
  4529. * by cgroup_lock_live_cgroup() that it is not removed and we
  4530. * are still under the same cgroup_mutex. So we can postpone
  4531. * css_get().
  4532. */
  4533. if (res_counter_charge(&mem->res, PAGE_SIZE * count, &dummy))
  4534. goto one_by_one;
  4535. if (do_swap_account && res_counter_charge(&mem->memsw,
  4536. PAGE_SIZE * count, &dummy)) {
  4537. res_counter_uncharge(&mem->res, PAGE_SIZE * count);
  4538. goto one_by_one;
  4539. }
  4540. mc.precharge += count;
  4541. return ret;
  4542. }
  4543. one_by_one:
  4544. /* fall back to one by one charge */
  4545. while (count--) {
  4546. if (signal_pending(current)) {
  4547. ret = -EINTR;
  4548. break;
  4549. }
  4550. if (!batch_count--) {
  4551. batch_count = PRECHARGE_COUNT_AT_ONCE;
  4552. cond_resched();
  4553. }
  4554. ret = __mem_cgroup_try_charge(NULL, GFP_KERNEL, 1, &mem, false);
  4555. if (ret || !mem)
  4556. /* mem_cgroup_clear_mc() will do uncharge later */
  4557. return -ENOMEM;
  4558. mc.precharge++;
  4559. }
  4560. return ret;
  4561. }
  4562. /**
  4563. * is_target_pte_for_mc - check a pte whether it is valid for move charge
  4564. * @vma: the vma the pte to be checked belongs
  4565. * @addr: the address corresponding to the pte to be checked
  4566. * @ptent: the pte to be checked
  4567. * @target: the pointer the target page or swap ent will be stored(can be NULL)
  4568. *
  4569. * Returns
  4570. * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
  4571. * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
  4572. * move charge. if @target is not NULL, the page is stored in target->page
  4573. * with extra refcnt got(Callers should handle it).
  4574. * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
  4575. * target for charge migration. if @target is not NULL, the entry is stored
  4576. * in target->ent.
  4577. *
  4578. * Called with pte lock held.
  4579. */
  4580. union mc_target {
  4581. struct page *page;
  4582. swp_entry_t ent;
  4583. };
  4584. enum mc_target_type {
  4585. MC_TARGET_NONE, /* not used */
  4586. MC_TARGET_PAGE,
  4587. MC_TARGET_SWAP,
  4588. };
  4589. static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
  4590. unsigned long addr, pte_t ptent)
  4591. {
  4592. struct page *page = vm_normal_page(vma, addr, ptent);
  4593. if (!page || !page_mapped(page))
  4594. return NULL;
  4595. if (PageAnon(page)) {
  4596. /* we don't move shared anon */
  4597. if (!move_anon() || page_mapcount(page) > 2)
  4598. return NULL;
  4599. } else if (!move_file())
  4600. /* we ignore mapcount for file pages */
  4601. return NULL;
  4602. if (!get_page_unless_zero(page))
  4603. return NULL;
  4604. return page;
  4605. }
  4606. static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
  4607. unsigned long addr, pte_t ptent, swp_entry_t *entry)
  4608. {
  4609. int usage_count;
  4610. struct page *page = NULL;
  4611. swp_entry_t ent = pte_to_swp_entry(ptent);
  4612. if (!move_anon() || non_swap_entry(ent))
  4613. return NULL;
  4614. usage_count = mem_cgroup_count_swap_user(ent, &page);
  4615. if (usage_count > 1) { /* we don't move shared anon */
  4616. if (page)
  4617. put_page(page);
  4618. return NULL;
  4619. }
  4620. if (do_swap_account)
  4621. entry->val = ent.val;
  4622. return page;
  4623. }
  4624. static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
  4625. unsigned long addr, pte_t ptent, swp_entry_t *entry)
  4626. {
  4627. struct page *page = NULL;
  4628. struct inode *inode;
  4629. struct address_space *mapping;
  4630. pgoff_t pgoff;
  4631. if (!vma->vm_file) /* anonymous vma */
  4632. return NULL;
  4633. if (!move_file())
  4634. return NULL;
  4635. inode = vma->vm_file->f_path.dentry->d_inode;
  4636. mapping = vma->vm_file->f_mapping;
  4637. if (pte_none(ptent))
  4638. pgoff = linear_page_index(vma, addr);
  4639. else /* pte_file(ptent) is true */
  4640. pgoff = pte_to_pgoff(ptent);
  4641. /* page is moved even if it's not RSS of this task(page-faulted). */
  4642. page = find_get_page(mapping, pgoff);
  4643. #ifdef CONFIG_SWAP
  4644. /* shmem/tmpfs may report page out on swap: account for that too. */
  4645. if (radix_tree_exceptional_entry(page)) {
  4646. swp_entry_t swap = radix_to_swp_entry(page);
  4647. if (do_swap_account)
  4648. *entry = swap;
  4649. page = find_get_page(&swapper_space, swap.val);
  4650. }
  4651. #endif
  4652. return page;
  4653. }
  4654. static int is_target_pte_for_mc(struct vm_area_struct *vma,
  4655. unsigned long addr, pte_t ptent, union mc_target *target)
  4656. {
  4657. struct page *page = NULL;
  4658. struct page_cgroup *pc;
  4659. int ret = 0;
  4660. swp_entry_t ent = { .val = 0 };
  4661. if (pte_present(ptent))
  4662. page = mc_handle_present_pte(vma, addr, ptent);
  4663. else if (is_swap_pte(ptent))
  4664. page = mc_handle_swap_pte(vma, addr, ptent, &ent);
  4665. else if (pte_none(ptent) || pte_file(ptent))
  4666. page = mc_handle_file_pte(vma, addr, ptent, &ent);
  4667. if (!page && !ent.val)
  4668. return 0;
  4669. if (page) {
  4670. pc = lookup_page_cgroup(page);
  4671. /*
  4672. * Do only loose check w/o page_cgroup lock.
  4673. * mem_cgroup_move_account() checks the pc is valid or not under
  4674. * the lock.
  4675. */
  4676. if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
  4677. ret = MC_TARGET_PAGE;
  4678. if (target)
  4679. target->page = page;
  4680. }
  4681. if (!ret || !target)
  4682. put_page(page);
  4683. }
  4684. /* There is a swap entry and a page doesn't exist or isn't charged */
  4685. if (ent.val && !ret &&
  4686. css_id(&mc.from->css) == lookup_swap_cgroup(ent)) {
  4687. ret = MC_TARGET_SWAP;
  4688. if (target)
  4689. target->ent = ent;
  4690. }
  4691. return ret;
  4692. }
  4693. static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
  4694. unsigned long addr, unsigned long end,
  4695. struct mm_walk *walk)
  4696. {
  4697. struct vm_area_struct *vma = walk->private;
  4698. pte_t *pte;
  4699. spinlock_t *ptl;
  4700. split_huge_page_pmd(walk->mm, pmd);
  4701. pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
  4702. for (; addr != end; pte++, addr += PAGE_SIZE)
  4703. if (is_target_pte_for_mc(vma, addr, *pte, NULL))
  4704. mc.precharge++; /* increment precharge temporarily */
  4705. pte_unmap_unlock(pte - 1, ptl);
  4706. cond_resched();
  4707. return 0;
  4708. }
  4709. static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
  4710. {
  4711. unsigned long precharge;
  4712. struct vm_area_struct *vma;
  4713. down_read(&mm->mmap_sem);
  4714. for (vma = mm->mmap; vma; vma = vma->vm_next) {
  4715. struct mm_walk mem_cgroup_count_precharge_walk = {
  4716. .pmd_entry = mem_cgroup_count_precharge_pte_range,
  4717. .mm = mm,
  4718. .private = vma,
  4719. };
  4720. if (is_vm_hugetlb_page(vma))
  4721. continue;
  4722. walk_page_range(vma->vm_start, vma->vm_end,
  4723. &mem_cgroup_count_precharge_walk);
  4724. }
  4725. up_read(&mm->mmap_sem);
  4726. precharge = mc.precharge;
  4727. mc.precharge = 0;
  4728. return precharge;
  4729. }
  4730. static int mem_cgroup_precharge_mc(struct mm_struct *mm)
  4731. {
  4732. unsigned long precharge = mem_cgroup_count_precharge(mm);
  4733. VM_BUG_ON(mc.moving_task);
  4734. mc.moving_task = current;
  4735. return mem_cgroup_do_precharge(precharge);
  4736. }
  4737. /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
  4738. static void __mem_cgroup_clear_mc(void)
  4739. {
  4740. struct mem_cgroup *from = mc.from;
  4741. struct mem_cgroup *to = mc.to;
  4742. /* we must uncharge all the leftover precharges from mc.to */
  4743. if (mc.precharge) {
  4744. __mem_cgroup_cancel_charge(mc.to, mc.precharge);
  4745. mc.precharge = 0;
  4746. }
  4747. /*
  4748. * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
  4749. * we must uncharge here.
  4750. */
  4751. if (mc.moved_charge) {
  4752. __mem_cgroup_cancel_charge(mc.from, mc.moved_charge);
  4753. mc.moved_charge = 0;
  4754. }
  4755. /* we must fixup refcnts and charges */
  4756. if (mc.moved_swap) {
  4757. /* uncharge swap account from the old cgroup */
  4758. if (!mem_cgroup_is_root(mc.from))
  4759. res_counter_uncharge(&mc.from->memsw,
  4760. PAGE_SIZE * mc.moved_swap);
  4761. __mem_cgroup_put(mc.from, mc.moved_swap);
  4762. if (!mem_cgroup_is_root(mc.to)) {
  4763. /*
  4764. * we charged both to->res and to->memsw, so we should
  4765. * uncharge to->res.
  4766. */
  4767. res_counter_uncharge(&mc.to->res,
  4768. PAGE_SIZE * mc.moved_swap);
  4769. }
  4770. /* we've already done mem_cgroup_get(mc.to) */
  4771. mc.moved_swap = 0;
  4772. }
  4773. memcg_oom_recover(from);
  4774. memcg_oom_recover(to);
  4775. wake_up_all(&mc.waitq);
  4776. }
  4777. static void mem_cgroup_clear_mc(void)
  4778. {
  4779. struct mem_cgroup *from = mc.from;
  4780. /*
  4781. * we must clear moving_task before waking up waiters at the end of
  4782. * task migration.
  4783. */
  4784. mc.moving_task = NULL;
  4785. __mem_cgroup_clear_mc();
  4786. spin_lock(&mc.lock);
  4787. mc.from = NULL;
  4788. mc.to = NULL;
  4789. spin_unlock(&mc.lock);
  4790. mem_cgroup_end_move(from);
  4791. }
  4792. static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
  4793. struct cgroup *cgroup,
  4794. struct task_struct *p)
  4795. {
  4796. int ret = 0;
  4797. struct mem_cgroup *mem = mem_cgroup_from_cont(cgroup);
  4798. if (mem->move_charge_at_immigrate) {
  4799. struct mm_struct *mm;
  4800. struct mem_cgroup *from = mem_cgroup_from_task(p);
  4801. VM_BUG_ON(from == mem);
  4802. mm = get_task_mm(p);
  4803. if (!mm)
  4804. return 0;
  4805. /* We move charges only when we move a owner of the mm */
  4806. if (mm->owner == p) {
  4807. VM_BUG_ON(mc.from);
  4808. VM_BUG_ON(mc.to);
  4809. VM_BUG_ON(mc.precharge);
  4810. VM_BUG_ON(mc.moved_charge);
  4811. VM_BUG_ON(mc.moved_swap);
  4812. mem_cgroup_start_move(from);
  4813. spin_lock(&mc.lock);
  4814. mc.from = from;
  4815. mc.to = mem;
  4816. spin_unlock(&mc.lock);
  4817. /* We set mc.moving_task later */
  4818. ret = mem_cgroup_precharge_mc(mm);
  4819. if (ret)
  4820. mem_cgroup_clear_mc();
  4821. }
  4822. mmput(mm);
  4823. }
  4824. return ret;
  4825. }
  4826. static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
  4827. struct cgroup *cgroup,
  4828. struct task_struct *p)
  4829. {
  4830. mem_cgroup_clear_mc();
  4831. }
  4832. static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
  4833. unsigned long addr, unsigned long end,
  4834. struct mm_walk *walk)
  4835. {
  4836. int ret = 0;
  4837. struct vm_area_struct *vma = walk->private;
  4838. pte_t *pte;
  4839. spinlock_t *ptl;
  4840. split_huge_page_pmd(walk->mm, pmd);
  4841. retry:
  4842. pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
  4843. for (; addr != end; addr += PAGE_SIZE) {
  4844. pte_t ptent = *(pte++);
  4845. union mc_target target;
  4846. int type;
  4847. struct page *page;
  4848. struct page_cgroup *pc;
  4849. swp_entry_t ent;
  4850. if (!mc.precharge)
  4851. break;
  4852. type = is_target_pte_for_mc(vma, addr, ptent, &target);
  4853. switch (type) {
  4854. case MC_TARGET_PAGE:
  4855. page = target.page;
  4856. if (isolate_lru_page(page))
  4857. goto put;
  4858. pc = lookup_page_cgroup(page);
  4859. if (!mem_cgroup_move_account(page, 1, pc,
  4860. mc.from, mc.to, false)) {
  4861. mc.precharge--;
  4862. /* we uncharge from mc.from later. */
  4863. mc.moved_charge++;
  4864. }
  4865. putback_lru_page(page);
  4866. put: /* is_target_pte_for_mc() gets the page */
  4867. put_page(page);
  4868. break;
  4869. case MC_TARGET_SWAP:
  4870. ent = target.ent;
  4871. if (!mem_cgroup_move_swap_account(ent,
  4872. mc.from, mc.to, false)) {
  4873. mc.precharge--;
  4874. /* we fixup refcnts and charges later. */
  4875. mc.moved_swap++;
  4876. }
  4877. break;
  4878. default:
  4879. break;
  4880. }
  4881. }
  4882. pte_unmap_unlock(pte - 1, ptl);
  4883. cond_resched();
  4884. if (addr != end) {
  4885. /*
  4886. * We have consumed all precharges we got in can_attach().
  4887. * We try charge one by one, but don't do any additional
  4888. * charges to mc.to if we have failed in charge once in attach()
  4889. * phase.
  4890. */
  4891. ret = mem_cgroup_do_precharge(1);
  4892. if (!ret)
  4893. goto retry;
  4894. }
  4895. return ret;
  4896. }
  4897. static void mem_cgroup_move_charge(struct mm_struct *mm)
  4898. {
  4899. struct vm_area_struct *vma;
  4900. lru_add_drain_all();
  4901. retry:
  4902. if (unlikely(!down_read_trylock(&mm->mmap_sem))) {
  4903. /*
  4904. * Someone who are holding the mmap_sem might be waiting in
  4905. * waitq. So we cancel all extra charges, wake up all waiters,
  4906. * and retry. Because we cancel precharges, we might not be able
  4907. * to move enough charges, but moving charge is a best-effort
  4908. * feature anyway, so it wouldn't be a big problem.
  4909. */
  4910. __mem_cgroup_clear_mc();
  4911. cond_resched();
  4912. goto retry;
  4913. }
  4914. for (vma = mm->mmap; vma; vma = vma->vm_next) {
  4915. int ret;
  4916. struct mm_walk mem_cgroup_move_charge_walk = {
  4917. .pmd_entry = mem_cgroup_move_charge_pte_range,
  4918. .mm = mm,
  4919. .private = vma,
  4920. };
  4921. if (is_vm_hugetlb_page(vma))
  4922. continue;
  4923. ret = walk_page_range(vma->vm_start, vma->vm_end,
  4924. &mem_cgroup_move_charge_walk);
  4925. if (ret)
  4926. /*
  4927. * means we have consumed all precharges and failed in
  4928. * doing additional charge. Just abandon here.
  4929. */
  4930. break;
  4931. }
  4932. up_read(&mm->mmap_sem);
  4933. }
  4934. static void mem_cgroup_move_task(struct cgroup_subsys *ss,
  4935. struct cgroup *cont,
  4936. struct cgroup *old_cont,
  4937. struct task_struct *p)
  4938. {
  4939. struct mm_struct *mm = get_task_mm(p);
  4940. if (mm) {
  4941. if (mc.to)
  4942. mem_cgroup_move_charge(mm);
  4943. put_swap_token(mm);
  4944. mmput(mm);
  4945. }
  4946. if (mc.to)
  4947. mem_cgroup_clear_mc();
  4948. }
  4949. #else /* !CONFIG_MMU */
  4950. static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
  4951. struct cgroup *cgroup,
  4952. struct task_struct *p)
  4953. {
  4954. return 0;
  4955. }
  4956. static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
  4957. struct cgroup *cgroup,
  4958. struct task_struct *p)
  4959. {
  4960. }
  4961. static void mem_cgroup_move_task(struct cgroup_subsys *ss,
  4962. struct cgroup *cont,
  4963. struct cgroup *old_cont,
  4964. struct task_struct *p)
  4965. {
  4966. }
  4967. #endif
  4968. struct cgroup_subsys mem_cgroup_subsys = {
  4969. .name = "memory",
  4970. .subsys_id = mem_cgroup_subsys_id,
  4971. .create = mem_cgroup_create,
  4972. .pre_destroy = mem_cgroup_pre_destroy,
  4973. .destroy = mem_cgroup_destroy,
  4974. .populate = mem_cgroup_populate,
  4975. .can_attach = mem_cgroup_can_attach,
  4976. .cancel_attach = mem_cgroup_cancel_attach,
  4977. .attach = mem_cgroup_move_task,
  4978. .early_init = 0,
  4979. .use_id = 1,
  4980. };
  4981. #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
  4982. static int __init enable_swap_account(char *s)
  4983. {
  4984. /* consider enabled if no parameter or 1 is given */
  4985. if (!strcmp(s, "1"))
  4986. really_do_swap_account = 1;
  4987. else if (!strcmp(s, "0"))
  4988. really_do_swap_account = 0;
  4989. return 1;
  4990. }
  4991. __setup("swapaccount=", enable_swap_account);
  4992. #endif