memcontrol.c 133 KB

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