memcontrol.c 142 KB

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