memcontrol.c 131 KB

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