memcontrol.c 131 KB

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