memcontrol.c 146 KB

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