memcontrol.c 146 KB

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