memcontrol.c 146 KB

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