memcontrol.c 145 KB

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