memcontrol.c 130 KB

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