memcontrol.c 134 KB

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