memcontrol.c 130 KB

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