memcontrol.c 143 KB

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