memcontrol.c 146 KB

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