memcontrol.c 145 KB

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