memcontrol.c 143 KB

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