memcontrol.c 142 KB

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