memcontrol.c 147 KB

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