memcontrol.c 146 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679
  1. // SPDX-License-Identifier: GPL-2.0-or-later
  2. /* memcontrol.c - Memory Controller
  3. *
  4. * Copyright IBM Corporation, 2007
  5. * Author Balbir Singh <balbir@linux.vnet.ibm.com>
  6. *
  7. * Copyright 2007 OpenVZ SWsoft Inc
  8. * Author: Pavel Emelianov <xemul@openvz.org>
  9. *
  10. * Memory thresholds
  11. * Copyright (C) 2009 Nokia Corporation
  12. * Author: Kirill A. Shutemov
  13. *
  14. * Kernel Memory Controller
  15. * Copyright (C) 2012 Parallels Inc. and Google Inc.
  16. * Authors: Glauber Costa and Suleiman Souhlal
  17. *
  18. * Native page reclaim
  19. * Charge lifetime sanitation
  20. * Lockless page tracking & accounting
  21. * Unified hierarchy configuration model
  22. * Copyright (C) 2015 Red Hat, Inc., Johannes Weiner
  23. *
  24. * Per memcg lru locking
  25. * Copyright (C) 2020 Alibaba, Inc, Alex Shi
  26. */
  27. #include <linux/cgroup-defs.h>
  28. #include <linux/page_counter.h>
  29. #include <linux/memcontrol.h>
  30. #include <linux/cgroup.h>
  31. #include <linux/cpuset.h>
  32. #include <linux/sched/mm.h>
  33. #include <linux/shmem_fs.h>
  34. #include <linux/hugetlb.h>
  35. #include <linux/pagemap.h>
  36. #include <linux/pagevec.h>
  37. #include <linux/vm_event_item.h>
  38. #include <linux/smp.h>
  39. #include <linux/page-flags.h>
  40. #include <linux/backing-dev.h>
  41. #include <linux/bit_spinlock.h>
  42. #include <linux/rcupdate.h>
  43. #include <linux/limits.h>
  44. #include <linux/export.h>
  45. #include <linux/list.h>
  46. #include <linux/mutex.h>
  47. #include <linux/rbtree.h>
  48. #include <linux/slab.h>
  49. #include <linux/swapops.h>
  50. #include <linux/spinlock.h>
  51. #include <linux/fs.h>
  52. #include <linux/seq_file.h>
  53. #include <linux/vmpressure.h>
  54. #include <linux/memremap.h>
  55. #include <linux/mm_inline.h>
  56. #include <linux/swap_cgroup.h>
  57. #include <linux/cpu.h>
  58. #include <linux/oom.h>
  59. #include <linux/lockdep.h>
  60. #include <linux/resume_user_mode.h>
  61. #include <linux/psi.h>
  62. #include <linux/seq_buf.h>
  63. #include <linux/sched/isolation.h>
  64. #include <linux/kmemleak.h>
  65. #include "internal.h"
  66. #include <net/sock.h>
  67. #include <net/ip.h>
  68. #include "slab.h"
  69. #include "memcontrol-v1.h"
  70. #include <linux/uaccess.h>
  71. #define CREATE_TRACE_POINTS
  72. #include <trace/events/memcg.h>
  73. #undef CREATE_TRACE_POINTS
  74. #include <trace/events/vmscan.h>
  75. struct cgroup_subsys memory_cgrp_subsys __read_mostly;
  76. EXPORT_SYMBOL(memory_cgrp_subsys);
  77. struct mem_cgroup *root_mem_cgroup __read_mostly;
  78. EXPORT_SYMBOL(root_mem_cgroup);
  79. /* Active memory cgroup to use from an interrupt context */
  80. DEFINE_PER_CPU(struct mem_cgroup *, int_active_memcg);
  81. EXPORT_PER_CPU_SYMBOL_GPL(int_active_memcg);
  82. /* Socket memory accounting disabled? */
  83. static bool cgroup_memory_nosocket __ro_after_init;
  84. /* Kernel memory accounting disabled? */
  85. static bool cgroup_memory_nokmem __ro_after_init;
  86. /* BPF memory accounting disabled? */
  87. static bool cgroup_memory_nobpf __ro_after_init;
  88. static struct workqueue_struct *memcg_wq __ro_after_init;
  89. static struct kmem_cache *memcg_cachep;
  90. static struct kmem_cache *memcg_pn_cachep;
  91. #ifdef CONFIG_CGROUP_WRITEBACK
  92. static DECLARE_WAIT_QUEUE_HEAD(memcg_cgwb_frn_waitq);
  93. #endif
  94. static inline bool task_is_dying(void)
  95. {
  96. return tsk_is_oom_victim(current) || fatal_signal_pending(current) ||
  97. (current->flags & PF_EXITING);
  98. }
  99. /* Some nice accessors for the vmpressure. */
  100. struct vmpressure *memcg_to_vmpressure(struct mem_cgroup *memcg)
  101. {
  102. if (!memcg)
  103. memcg = root_mem_cgroup;
  104. return &memcg->vmpressure;
  105. }
  106. struct mem_cgroup *vmpressure_to_memcg(struct vmpressure *vmpr)
  107. {
  108. return container_of(vmpr, struct mem_cgroup, vmpressure);
  109. }
  110. #define SEQ_BUF_SIZE SZ_4K
  111. #define CURRENT_OBJCG_UPDATE_BIT 0
  112. #define CURRENT_OBJCG_UPDATE_FLAG (1UL << CURRENT_OBJCG_UPDATE_BIT)
  113. static DEFINE_SPINLOCK(objcg_lock);
  114. bool mem_cgroup_kmem_disabled(void)
  115. {
  116. return cgroup_memory_nokmem;
  117. }
  118. static void memcg_uncharge(struct mem_cgroup *memcg, unsigned int nr_pages);
  119. static void obj_cgroup_release(struct percpu_ref *ref)
  120. {
  121. struct obj_cgroup *objcg = container_of(ref, struct obj_cgroup, refcnt);
  122. unsigned int nr_bytes;
  123. unsigned int nr_pages;
  124. unsigned long flags;
  125. /*
  126. * At this point all allocated objects are freed, and
  127. * objcg->nr_charged_bytes can't have an arbitrary byte value.
  128. * However, it can be PAGE_SIZE or (x * PAGE_SIZE).
  129. *
  130. * The following sequence can lead to it:
  131. * 1) CPU0: objcg == stock->cached_objcg
  132. * 2) CPU1: we do a small allocation (e.g. 92 bytes),
  133. * PAGE_SIZE bytes are charged
  134. * 3) CPU1: a process from another memcg is allocating something,
  135. * the stock if flushed,
  136. * objcg->nr_charged_bytes = PAGE_SIZE - 92
  137. * 5) CPU0: we do release this object,
  138. * 92 bytes are added to stock->nr_bytes
  139. * 6) CPU0: stock is flushed,
  140. * 92 bytes are added to objcg->nr_charged_bytes
  141. *
  142. * In the result, nr_charged_bytes == PAGE_SIZE.
  143. * This page will be uncharged in obj_cgroup_release().
  144. */
  145. nr_bytes = atomic_read(&objcg->nr_charged_bytes);
  146. WARN_ON_ONCE(nr_bytes & (PAGE_SIZE - 1));
  147. nr_pages = nr_bytes >> PAGE_SHIFT;
  148. if (nr_pages) {
  149. struct mem_cgroup *memcg;
  150. memcg = get_mem_cgroup_from_objcg(objcg);
  151. mod_memcg_state(memcg, MEMCG_KMEM, -nr_pages);
  152. memcg1_account_kmem(memcg, -nr_pages);
  153. if (!mem_cgroup_is_root(memcg))
  154. memcg_uncharge(memcg, nr_pages);
  155. mem_cgroup_put(memcg);
  156. }
  157. spin_lock_irqsave(&objcg_lock, flags);
  158. list_del(&objcg->list);
  159. spin_unlock_irqrestore(&objcg_lock, flags);
  160. percpu_ref_exit(ref);
  161. kfree_rcu(objcg, rcu);
  162. }
  163. static struct obj_cgroup *obj_cgroup_alloc(void)
  164. {
  165. struct obj_cgroup *objcg;
  166. int ret;
  167. objcg = kzalloc_obj(struct obj_cgroup);
  168. if (!objcg)
  169. return NULL;
  170. ret = percpu_ref_init(&objcg->refcnt, obj_cgroup_release, 0,
  171. GFP_KERNEL);
  172. if (ret) {
  173. kfree(objcg);
  174. return NULL;
  175. }
  176. INIT_LIST_HEAD(&objcg->list);
  177. return objcg;
  178. }
  179. static void memcg_reparent_objcgs(struct mem_cgroup *memcg,
  180. struct mem_cgroup *parent)
  181. {
  182. struct obj_cgroup *objcg, *iter;
  183. objcg = rcu_replace_pointer(memcg->objcg, NULL, true);
  184. spin_lock_irq(&objcg_lock);
  185. /* 1) Ready to reparent active objcg. */
  186. list_add(&objcg->list, &memcg->objcg_list);
  187. /* 2) Reparent active objcg and already reparented objcgs to parent. */
  188. list_for_each_entry(iter, &memcg->objcg_list, list)
  189. WRITE_ONCE(iter->memcg, parent);
  190. /* 3) Move already reparented objcgs to the parent's list */
  191. list_splice(&memcg->objcg_list, &parent->objcg_list);
  192. spin_unlock_irq(&objcg_lock);
  193. percpu_ref_kill(&objcg->refcnt);
  194. }
  195. /*
  196. * A lot of the calls to the cache allocation functions are expected to be
  197. * inlined by the compiler. Since the calls to memcg_slab_post_alloc_hook() are
  198. * conditional to this static branch, we'll have to allow modules that does
  199. * kmem_cache_alloc and the such to see this symbol as well
  200. */
  201. DEFINE_STATIC_KEY_FALSE(memcg_kmem_online_key);
  202. EXPORT_SYMBOL(memcg_kmem_online_key);
  203. DEFINE_STATIC_KEY_FALSE(memcg_bpf_enabled_key);
  204. EXPORT_SYMBOL(memcg_bpf_enabled_key);
  205. /**
  206. * mem_cgroup_css_from_folio - css of the memcg associated with a folio
  207. * @folio: folio of interest
  208. *
  209. * If memcg is bound to the default hierarchy, css of the memcg associated
  210. * with @folio is returned. The returned css remains associated with @folio
  211. * until it is released.
  212. *
  213. * If memcg is bound to a traditional hierarchy, the css of root_mem_cgroup
  214. * is returned.
  215. */
  216. struct cgroup_subsys_state *mem_cgroup_css_from_folio(struct folio *folio)
  217. {
  218. struct mem_cgroup *memcg = folio_memcg(folio);
  219. if (!memcg || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
  220. memcg = root_mem_cgroup;
  221. return &memcg->css;
  222. }
  223. /**
  224. * page_cgroup_ino - return inode number of the memcg a page is charged to
  225. * @page: the page
  226. *
  227. * Look up the closest online ancestor of the memory cgroup @page is charged to
  228. * and return its inode number or 0 if @page is not charged to any cgroup. It
  229. * is safe to call this function without holding a reference to @page.
  230. *
  231. * Note, this function is inherently racy, because there is nothing to prevent
  232. * the cgroup inode from getting torn down and potentially reallocated a moment
  233. * after page_cgroup_ino() returns, so it only should be used by callers that
  234. * do not care (such as procfs interfaces).
  235. */
  236. ino_t page_cgroup_ino(struct page *page)
  237. {
  238. struct mem_cgroup *memcg;
  239. unsigned long ino = 0;
  240. rcu_read_lock();
  241. /* page_folio() is racy here, but the entire function is racy anyway */
  242. memcg = folio_memcg_check(page_folio(page));
  243. while (memcg && !css_is_online(&memcg->css))
  244. memcg = parent_mem_cgroup(memcg);
  245. if (memcg)
  246. ino = cgroup_ino(memcg->css.cgroup);
  247. rcu_read_unlock();
  248. return ino;
  249. }
  250. EXPORT_SYMBOL_GPL(page_cgroup_ino);
  251. /* Subset of node_stat_item for memcg stats */
  252. static const unsigned int memcg_node_stat_items[] = {
  253. NR_INACTIVE_ANON,
  254. NR_ACTIVE_ANON,
  255. NR_INACTIVE_FILE,
  256. NR_ACTIVE_FILE,
  257. NR_UNEVICTABLE,
  258. NR_SLAB_RECLAIMABLE_B,
  259. NR_SLAB_UNRECLAIMABLE_B,
  260. WORKINGSET_REFAULT_ANON,
  261. WORKINGSET_REFAULT_FILE,
  262. WORKINGSET_ACTIVATE_ANON,
  263. WORKINGSET_ACTIVATE_FILE,
  264. WORKINGSET_RESTORE_ANON,
  265. WORKINGSET_RESTORE_FILE,
  266. WORKINGSET_NODERECLAIM,
  267. NR_ANON_MAPPED,
  268. NR_FILE_MAPPED,
  269. NR_FILE_PAGES,
  270. NR_FILE_DIRTY,
  271. NR_WRITEBACK,
  272. NR_SHMEM,
  273. NR_SHMEM_THPS,
  274. NR_FILE_THPS,
  275. NR_ANON_THPS,
  276. NR_KERNEL_STACK_KB,
  277. NR_PAGETABLE,
  278. NR_SECONDARY_PAGETABLE,
  279. #ifdef CONFIG_SWAP
  280. NR_SWAPCACHE,
  281. #endif
  282. #ifdef CONFIG_NUMA_BALANCING
  283. PGPROMOTE_SUCCESS,
  284. #endif
  285. PGDEMOTE_KSWAPD,
  286. PGDEMOTE_DIRECT,
  287. PGDEMOTE_KHUGEPAGED,
  288. PGDEMOTE_PROACTIVE,
  289. #ifdef CONFIG_HUGETLB_PAGE
  290. NR_HUGETLB,
  291. #endif
  292. };
  293. static const unsigned int memcg_stat_items[] = {
  294. MEMCG_SWAP,
  295. MEMCG_SOCK,
  296. MEMCG_PERCPU_B,
  297. MEMCG_VMALLOC,
  298. MEMCG_KMEM,
  299. MEMCG_ZSWAP_B,
  300. MEMCG_ZSWAPPED,
  301. };
  302. #define NR_MEMCG_NODE_STAT_ITEMS ARRAY_SIZE(memcg_node_stat_items)
  303. #define MEMCG_VMSTAT_SIZE (NR_MEMCG_NODE_STAT_ITEMS + \
  304. ARRAY_SIZE(memcg_stat_items))
  305. #define BAD_STAT_IDX(index) ((u32)(index) >= U8_MAX)
  306. static u8 mem_cgroup_stats_index[MEMCG_NR_STAT] __read_mostly;
  307. static void init_memcg_stats(void)
  308. {
  309. u8 i, j = 0;
  310. BUILD_BUG_ON(MEMCG_NR_STAT >= U8_MAX);
  311. memset(mem_cgroup_stats_index, U8_MAX, sizeof(mem_cgroup_stats_index));
  312. for (i = 0; i < NR_MEMCG_NODE_STAT_ITEMS; ++i, ++j)
  313. mem_cgroup_stats_index[memcg_node_stat_items[i]] = j;
  314. for (i = 0; i < ARRAY_SIZE(memcg_stat_items); ++i, ++j)
  315. mem_cgroup_stats_index[memcg_stat_items[i]] = j;
  316. }
  317. static inline int memcg_stats_index(int idx)
  318. {
  319. return mem_cgroup_stats_index[idx];
  320. }
  321. struct lruvec_stats_percpu {
  322. /* Local (CPU and cgroup) state */
  323. long state[NR_MEMCG_NODE_STAT_ITEMS];
  324. /* Delta calculation for lockless upward propagation */
  325. long state_prev[NR_MEMCG_NODE_STAT_ITEMS];
  326. };
  327. struct lruvec_stats {
  328. /* Aggregated (CPU and subtree) state */
  329. long state[NR_MEMCG_NODE_STAT_ITEMS];
  330. /* Non-hierarchical (CPU aggregated) state */
  331. long state_local[NR_MEMCG_NODE_STAT_ITEMS];
  332. /* Pending child counts during tree propagation */
  333. long state_pending[NR_MEMCG_NODE_STAT_ITEMS];
  334. };
  335. unsigned long lruvec_page_state(struct lruvec *lruvec, enum node_stat_item idx)
  336. {
  337. struct mem_cgroup_per_node *pn;
  338. long x;
  339. int i;
  340. if (mem_cgroup_disabled())
  341. return node_page_state(lruvec_pgdat(lruvec), idx);
  342. i = memcg_stats_index(idx);
  343. if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, idx))
  344. return 0;
  345. pn = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
  346. x = READ_ONCE(pn->lruvec_stats->state[i]);
  347. #ifdef CONFIG_SMP
  348. if (x < 0)
  349. x = 0;
  350. #endif
  351. return x;
  352. }
  353. unsigned long lruvec_page_state_local(struct lruvec *lruvec,
  354. enum node_stat_item idx)
  355. {
  356. struct mem_cgroup_per_node *pn;
  357. long x;
  358. int i;
  359. if (mem_cgroup_disabled())
  360. return node_page_state(lruvec_pgdat(lruvec), idx);
  361. i = memcg_stats_index(idx);
  362. if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, idx))
  363. return 0;
  364. pn = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
  365. x = READ_ONCE(pn->lruvec_stats->state_local[i]);
  366. #ifdef CONFIG_SMP
  367. if (x < 0)
  368. x = 0;
  369. #endif
  370. return x;
  371. }
  372. /* Subset of vm_event_item to report for memcg event stats */
  373. static const unsigned int memcg_vm_event_stat[] = {
  374. #ifdef CONFIG_MEMCG_V1
  375. PGPGIN,
  376. PGPGOUT,
  377. #endif
  378. PSWPIN,
  379. PSWPOUT,
  380. PGSCAN_KSWAPD,
  381. PGSCAN_DIRECT,
  382. PGSCAN_KHUGEPAGED,
  383. PGSCAN_PROACTIVE,
  384. PGSTEAL_KSWAPD,
  385. PGSTEAL_DIRECT,
  386. PGSTEAL_KHUGEPAGED,
  387. PGSTEAL_PROACTIVE,
  388. PGFAULT,
  389. PGMAJFAULT,
  390. PGREFILL,
  391. PGACTIVATE,
  392. PGDEACTIVATE,
  393. PGLAZYFREE,
  394. PGLAZYFREED,
  395. #ifdef CONFIG_SWAP
  396. SWPIN_ZERO,
  397. SWPOUT_ZERO,
  398. #endif
  399. #ifdef CONFIG_ZSWAP
  400. ZSWPIN,
  401. ZSWPOUT,
  402. ZSWPWB,
  403. #endif
  404. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  405. THP_FAULT_ALLOC,
  406. THP_COLLAPSE_ALLOC,
  407. THP_SWPOUT,
  408. THP_SWPOUT_FALLBACK,
  409. #endif
  410. #ifdef CONFIG_NUMA_BALANCING
  411. NUMA_PAGE_MIGRATE,
  412. NUMA_PTE_UPDATES,
  413. NUMA_HINT_FAULTS,
  414. #endif
  415. };
  416. #define NR_MEMCG_EVENTS ARRAY_SIZE(memcg_vm_event_stat)
  417. static u8 mem_cgroup_events_index[NR_VM_EVENT_ITEMS] __read_mostly;
  418. static void init_memcg_events(void)
  419. {
  420. u8 i;
  421. BUILD_BUG_ON(NR_VM_EVENT_ITEMS >= U8_MAX);
  422. memset(mem_cgroup_events_index, U8_MAX,
  423. sizeof(mem_cgroup_events_index));
  424. for (i = 0; i < NR_MEMCG_EVENTS; ++i)
  425. mem_cgroup_events_index[memcg_vm_event_stat[i]] = i;
  426. }
  427. static inline int memcg_events_index(enum vm_event_item idx)
  428. {
  429. return mem_cgroup_events_index[idx];
  430. }
  431. struct memcg_vmstats_percpu {
  432. /* Stats updates since the last flush */
  433. unsigned int stats_updates;
  434. /* Cached pointers for fast iteration in memcg_rstat_updated() */
  435. struct memcg_vmstats_percpu __percpu *parent_pcpu;
  436. struct memcg_vmstats *vmstats;
  437. /* The above should fit a single cacheline for memcg_rstat_updated() */
  438. /* Local (CPU and cgroup) page state & events */
  439. long state[MEMCG_VMSTAT_SIZE];
  440. unsigned long events[NR_MEMCG_EVENTS];
  441. /* Delta calculation for lockless upward propagation */
  442. long state_prev[MEMCG_VMSTAT_SIZE];
  443. unsigned long events_prev[NR_MEMCG_EVENTS];
  444. } ____cacheline_aligned;
  445. struct memcg_vmstats {
  446. /* Aggregated (CPU and subtree) page state & events */
  447. long state[MEMCG_VMSTAT_SIZE];
  448. unsigned long events[NR_MEMCG_EVENTS];
  449. /* Non-hierarchical (CPU aggregated) page state & events */
  450. long state_local[MEMCG_VMSTAT_SIZE];
  451. unsigned long events_local[NR_MEMCG_EVENTS];
  452. /* Pending child counts during tree propagation */
  453. long state_pending[MEMCG_VMSTAT_SIZE];
  454. unsigned long events_pending[NR_MEMCG_EVENTS];
  455. /* Stats updates since the last flush */
  456. atomic_t stats_updates;
  457. };
  458. /*
  459. * memcg and lruvec stats flushing
  460. *
  461. * Many codepaths leading to stats update or read are performance sensitive and
  462. * adding stats flushing in such codepaths is not desirable. So, to optimize the
  463. * flushing the kernel does:
  464. *
  465. * 1) Periodically and asynchronously flush the stats every 2 seconds to not let
  466. * rstat update tree grow unbounded.
  467. *
  468. * 2) Flush the stats synchronously on reader side only when there are more than
  469. * (MEMCG_CHARGE_BATCH * nr_cpus) update events. Though this optimization
  470. * will let stats be out of sync by atmost (MEMCG_CHARGE_BATCH * nr_cpus) but
  471. * only for 2 seconds due to (1).
  472. */
  473. static void flush_memcg_stats_dwork(struct work_struct *w);
  474. static DECLARE_DEFERRABLE_WORK(stats_flush_dwork, flush_memcg_stats_dwork);
  475. static u64 flush_last_time;
  476. #define FLUSH_TIME (2UL*HZ)
  477. static bool memcg_vmstats_needs_flush(struct memcg_vmstats *vmstats)
  478. {
  479. return atomic_read(&vmstats->stats_updates) >
  480. MEMCG_CHARGE_BATCH * num_online_cpus();
  481. }
  482. static inline void memcg_rstat_updated(struct mem_cgroup *memcg, int val,
  483. int cpu)
  484. {
  485. struct memcg_vmstats_percpu __percpu *statc_pcpu;
  486. struct memcg_vmstats_percpu *statc;
  487. unsigned int stats_updates;
  488. if (!val)
  489. return;
  490. css_rstat_updated(&memcg->css, cpu);
  491. statc_pcpu = memcg->vmstats_percpu;
  492. for (; statc_pcpu; statc_pcpu = statc->parent_pcpu) {
  493. statc = this_cpu_ptr(statc_pcpu);
  494. /*
  495. * If @memcg is already flushable then all its ancestors are
  496. * flushable as well and also there is no need to increase
  497. * stats_updates.
  498. */
  499. if (memcg_vmstats_needs_flush(statc->vmstats))
  500. break;
  501. stats_updates = this_cpu_add_return(statc_pcpu->stats_updates,
  502. abs(val));
  503. if (stats_updates < MEMCG_CHARGE_BATCH)
  504. continue;
  505. stats_updates = this_cpu_xchg(statc_pcpu->stats_updates, 0);
  506. atomic_add(stats_updates, &statc->vmstats->stats_updates);
  507. }
  508. }
  509. static void __mem_cgroup_flush_stats(struct mem_cgroup *memcg, bool force)
  510. {
  511. bool needs_flush = memcg_vmstats_needs_flush(memcg->vmstats);
  512. trace_memcg_flush_stats(memcg, atomic_read(&memcg->vmstats->stats_updates),
  513. force, needs_flush);
  514. if (!force && !needs_flush)
  515. return;
  516. if (mem_cgroup_is_root(memcg))
  517. WRITE_ONCE(flush_last_time, jiffies_64);
  518. css_rstat_flush(&memcg->css);
  519. }
  520. /*
  521. * mem_cgroup_flush_stats - flush the stats of a memory cgroup subtree
  522. * @memcg: root of the subtree to flush
  523. *
  524. * Flushing is serialized by the underlying global rstat lock. There is also a
  525. * minimum amount of work to be done even if there are no stat updates to flush.
  526. * Hence, we only flush the stats if the updates delta exceeds a threshold. This
  527. * avoids unnecessary work and contention on the underlying lock.
  528. */
  529. void mem_cgroup_flush_stats(struct mem_cgroup *memcg)
  530. {
  531. if (mem_cgroup_disabled())
  532. return;
  533. if (!memcg)
  534. memcg = root_mem_cgroup;
  535. __mem_cgroup_flush_stats(memcg, false);
  536. }
  537. void mem_cgroup_flush_stats_ratelimited(struct mem_cgroup *memcg)
  538. {
  539. /* Only flush if the periodic flusher is one full cycle late */
  540. if (time_after64(jiffies_64, READ_ONCE(flush_last_time) + 2*FLUSH_TIME))
  541. mem_cgroup_flush_stats(memcg);
  542. }
  543. static void flush_memcg_stats_dwork(struct work_struct *w)
  544. {
  545. /*
  546. * Deliberately ignore memcg_vmstats_needs_flush() here so that flushing
  547. * in latency-sensitive paths is as cheap as possible.
  548. */
  549. __mem_cgroup_flush_stats(root_mem_cgroup, true);
  550. queue_delayed_work(system_dfl_wq, &stats_flush_dwork, FLUSH_TIME);
  551. }
  552. unsigned long memcg_page_state(struct mem_cgroup *memcg, int idx)
  553. {
  554. long x;
  555. int i = memcg_stats_index(idx);
  556. if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, idx))
  557. return 0;
  558. x = READ_ONCE(memcg->vmstats->state[i]);
  559. #ifdef CONFIG_SMP
  560. if (x < 0)
  561. x = 0;
  562. #endif
  563. return x;
  564. }
  565. bool memcg_stat_item_valid(int idx)
  566. {
  567. if ((u32)idx >= MEMCG_NR_STAT)
  568. return false;
  569. return !BAD_STAT_IDX(memcg_stats_index(idx));
  570. }
  571. static int memcg_page_state_unit(int item);
  572. /*
  573. * Normalize the value passed into memcg_rstat_updated() to be in pages. Round
  574. * up non-zero sub-page updates to 1 page as zero page updates are ignored.
  575. */
  576. static int memcg_state_val_in_pages(int idx, int val)
  577. {
  578. int unit = memcg_page_state_unit(idx);
  579. if (!val || unit == PAGE_SIZE)
  580. return val;
  581. else
  582. return max(val * unit / PAGE_SIZE, 1UL);
  583. }
  584. /**
  585. * mod_memcg_state - update cgroup memory statistics
  586. * @memcg: the memory cgroup
  587. * @idx: the stat item - can be enum memcg_stat_item or enum node_stat_item
  588. * @val: delta to add to the counter, can be negative
  589. */
  590. void mod_memcg_state(struct mem_cgroup *memcg, enum memcg_stat_item idx,
  591. int val)
  592. {
  593. int i = memcg_stats_index(idx);
  594. int cpu;
  595. if (mem_cgroup_disabled())
  596. return;
  597. if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, idx))
  598. return;
  599. cpu = get_cpu();
  600. this_cpu_add(memcg->vmstats_percpu->state[i], val);
  601. val = memcg_state_val_in_pages(idx, val);
  602. memcg_rstat_updated(memcg, val, cpu);
  603. trace_mod_memcg_state(memcg, idx, val);
  604. put_cpu();
  605. }
  606. #ifdef CONFIG_MEMCG_V1
  607. /* idx can be of type enum memcg_stat_item or node_stat_item. */
  608. unsigned long memcg_page_state_local(struct mem_cgroup *memcg, int idx)
  609. {
  610. long x;
  611. int i = memcg_stats_index(idx);
  612. if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, idx))
  613. return 0;
  614. x = READ_ONCE(memcg->vmstats->state_local[i]);
  615. #ifdef CONFIG_SMP
  616. if (x < 0)
  617. x = 0;
  618. #endif
  619. return x;
  620. }
  621. #endif
  622. static void mod_memcg_lruvec_state(struct lruvec *lruvec,
  623. enum node_stat_item idx,
  624. int val)
  625. {
  626. struct mem_cgroup_per_node *pn;
  627. struct mem_cgroup *memcg;
  628. int i = memcg_stats_index(idx);
  629. int cpu;
  630. if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, idx))
  631. return;
  632. pn = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
  633. memcg = pn->memcg;
  634. cpu = get_cpu();
  635. /* Update memcg */
  636. this_cpu_add(memcg->vmstats_percpu->state[i], val);
  637. /* Update lruvec */
  638. this_cpu_add(pn->lruvec_stats_percpu->state[i], val);
  639. val = memcg_state_val_in_pages(idx, val);
  640. memcg_rstat_updated(memcg, val, cpu);
  641. trace_mod_memcg_lruvec_state(memcg, idx, val);
  642. put_cpu();
  643. }
  644. /**
  645. * mod_lruvec_state - update lruvec memory statistics
  646. * @lruvec: the lruvec
  647. * @idx: the stat item
  648. * @val: delta to add to the counter, can be negative
  649. *
  650. * The lruvec is the intersection of the NUMA node and a cgroup. This
  651. * function updates the all three counters that are affected by a
  652. * change of state at this level: per-node, per-cgroup, per-lruvec.
  653. */
  654. void mod_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
  655. int val)
  656. {
  657. /* Update node */
  658. mod_node_page_state(lruvec_pgdat(lruvec), idx, val);
  659. /* Update memcg and lruvec */
  660. if (!mem_cgroup_disabled())
  661. mod_memcg_lruvec_state(lruvec, idx, val);
  662. }
  663. void lruvec_stat_mod_folio(struct folio *folio, enum node_stat_item idx,
  664. int val)
  665. {
  666. struct mem_cgroup *memcg;
  667. pg_data_t *pgdat = folio_pgdat(folio);
  668. struct lruvec *lruvec;
  669. rcu_read_lock();
  670. memcg = folio_memcg(folio);
  671. /* Untracked pages have no memcg, no lruvec. Update only the node */
  672. if (!memcg) {
  673. rcu_read_unlock();
  674. mod_node_page_state(pgdat, idx, val);
  675. return;
  676. }
  677. lruvec = mem_cgroup_lruvec(memcg, pgdat);
  678. mod_lruvec_state(lruvec, idx, val);
  679. rcu_read_unlock();
  680. }
  681. EXPORT_SYMBOL(lruvec_stat_mod_folio);
  682. void mod_lruvec_kmem_state(void *p, enum node_stat_item idx, int val)
  683. {
  684. pg_data_t *pgdat = page_pgdat(virt_to_page(p));
  685. struct mem_cgroup *memcg;
  686. struct lruvec *lruvec;
  687. rcu_read_lock();
  688. memcg = mem_cgroup_from_virt(p);
  689. /*
  690. * Untracked pages have no memcg, no lruvec. Update only the
  691. * node. If we reparent the slab objects to the root memcg,
  692. * when we free the slab object, we need to update the per-memcg
  693. * vmstats to keep it correct for the root memcg.
  694. */
  695. if (!memcg) {
  696. mod_node_page_state(pgdat, idx, val);
  697. } else {
  698. lruvec = mem_cgroup_lruvec(memcg, pgdat);
  699. mod_lruvec_state(lruvec, idx, val);
  700. }
  701. rcu_read_unlock();
  702. }
  703. /**
  704. * count_memcg_events - account VM events in a cgroup
  705. * @memcg: the memory cgroup
  706. * @idx: the event item
  707. * @count: the number of events that occurred
  708. */
  709. void count_memcg_events(struct mem_cgroup *memcg, enum vm_event_item idx,
  710. unsigned long count)
  711. {
  712. int i = memcg_events_index(idx);
  713. int cpu;
  714. if (mem_cgroup_disabled())
  715. return;
  716. if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, idx))
  717. return;
  718. cpu = get_cpu();
  719. this_cpu_add(memcg->vmstats_percpu->events[i], count);
  720. memcg_rstat_updated(memcg, count, cpu);
  721. trace_count_memcg_events(memcg, idx, count);
  722. put_cpu();
  723. }
  724. unsigned long memcg_events(struct mem_cgroup *memcg, int event)
  725. {
  726. int i = memcg_events_index(event);
  727. if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, event))
  728. return 0;
  729. return READ_ONCE(memcg->vmstats->events[i]);
  730. }
  731. bool memcg_vm_event_item_valid(enum vm_event_item idx)
  732. {
  733. if (idx >= NR_VM_EVENT_ITEMS)
  734. return false;
  735. return !BAD_STAT_IDX(memcg_events_index(idx));
  736. }
  737. #ifdef CONFIG_MEMCG_V1
  738. unsigned long memcg_events_local(struct mem_cgroup *memcg, int event)
  739. {
  740. int i = memcg_events_index(event);
  741. if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, event))
  742. return 0;
  743. return READ_ONCE(memcg->vmstats->events_local[i]);
  744. }
  745. #endif
  746. struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
  747. {
  748. /*
  749. * mm_update_next_owner() may clear mm->owner to NULL
  750. * if it races with swapoff, page migration, etc.
  751. * So this can be called with p == NULL.
  752. */
  753. if (unlikely(!p))
  754. return NULL;
  755. return mem_cgroup_from_css(task_css(p, memory_cgrp_id));
  756. }
  757. EXPORT_SYMBOL(mem_cgroup_from_task);
  758. static __always_inline struct mem_cgroup *active_memcg(void)
  759. {
  760. if (!in_task())
  761. return this_cpu_read(int_active_memcg);
  762. else
  763. return current->active_memcg;
  764. }
  765. /**
  766. * get_mem_cgroup_from_mm: Obtain a reference on given mm_struct's memcg.
  767. * @mm: mm from which memcg should be extracted. It can be NULL.
  768. *
  769. * Obtain a reference on mm->memcg and returns it if successful. If mm
  770. * is NULL, then the memcg is chosen as follows:
  771. * 1) The active memcg, if set.
  772. * 2) current->mm->memcg, if available
  773. * 3) root memcg
  774. * If mem_cgroup is disabled, NULL is returned.
  775. */
  776. struct mem_cgroup *get_mem_cgroup_from_mm(struct mm_struct *mm)
  777. {
  778. struct mem_cgroup *memcg;
  779. if (mem_cgroup_disabled())
  780. return NULL;
  781. /*
  782. * Page cache insertions can happen without an
  783. * actual mm context, e.g. during disk probing
  784. * on boot, loopback IO, acct() writes etc.
  785. *
  786. * No need to css_get on root memcg as the reference
  787. * counting is disabled on the root level in the
  788. * cgroup core. See CSS_NO_REF.
  789. */
  790. if (unlikely(!mm)) {
  791. memcg = active_memcg();
  792. if (unlikely(memcg)) {
  793. /* remote memcg must hold a ref */
  794. css_get(&memcg->css);
  795. return memcg;
  796. }
  797. mm = current->mm;
  798. if (unlikely(!mm))
  799. return root_mem_cgroup;
  800. }
  801. rcu_read_lock();
  802. do {
  803. memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
  804. if (unlikely(!memcg))
  805. memcg = root_mem_cgroup;
  806. } while (!css_tryget(&memcg->css));
  807. rcu_read_unlock();
  808. return memcg;
  809. }
  810. EXPORT_SYMBOL(get_mem_cgroup_from_mm);
  811. /**
  812. * get_mem_cgroup_from_current - Obtain a reference on current task's memcg.
  813. */
  814. struct mem_cgroup *get_mem_cgroup_from_current(void)
  815. {
  816. struct mem_cgroup *memcg;
  817. if (mem_cgroup_disabled())
  818. return NULL;
  819. again:
  820. rcu_read_lock();
  821. memcg = mem_cgroup_from_task(current);
  822. if (!css_tryget(&memcg->css)) {
  823. rcu_read_unlock();
  824. goto again;
  825. }
  826. rcu_read_unlock();
  827. return memcg;
  828. }
  829. /**
  830. * get_mem_cgroup_from_folio - Obtain a reference on a given folio's memcg.
  831. * @folio: folio from which memcg should be extracted.
  832. */
  833. struct mem_cgroup *get_mem_cgroup_from_folio(struct folio *folio)
  834. {
  835. struct mem_cgroup *memcg = folio_memcg(folio);
  836. if (mem_cgroup_disabled())
  837. return NULL;
  838. rcu_read_lock();
  839. if (!memcg || WARN_ON_ONCE(!css_tryget(&memcg->css)))
  840. memcg = root_mem_cgroup;
  841. rcu_read_unlock();
  842. return memcg;
  843. }
  844. /**
  845. * mem_cgroup_iter - iterate over memory cgroup hierarchy
  846. * @root: hierarchy root
  847. * @prev: previously returned memcg, NULL on first invocation
  848. * @reclaim: cookie for shared reclaim walks, NULL for full walks
  849. *
  850. * Returns references to children of the hierarchy below @root, or
  851. * @root itself, or %NULL after a full round-trip.
  852. *
  853. * Caller must pass the return value in @prev on subsequent
  854. * invocations for reference counting, or use mem_cgroup_iter_break()
  855. * to cancel a hierarchy walk before the round-trip is complete.
  856. *
  857. * Reclaimers can specify a node in @reclaim to divide up the memcgs
  858. * in the hierarchy among all concurrent reclaimers operating on the
  859. * same node.
  860. */
  861. struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
  862. struct mem_cgroup *prev,
  863. struct mem_cgroup_reclaim_cookie *reclaim)
  864. {
  865. struct mem_cgroup_reclaim_iter *iter;
  866. struct cgroup_subsys_state *css;
  867. struct mem_cgroup *pos;
  868. struct mem_cgroup *next;
  869. if (mem_cgroup_disabled())
  870. return NULL;
  871. if (!root)
  872. root = root_mem_cgroup;
  873. rcu_read_lock();
  874. restart:
  875. next = NULL;
  876. if (reclaim) {
  877. int gen;
  878. int nid = reclaim->pgdat->node_id;
  879. iter = &root->nodeinfo[nid]->iter;
  880. gen = atomic_read(&iter->generation);
  881. /*
  882. * On start, join the current reclaim iteration cycle.
  883. * Exit when a concurrent walker completes it.
  884. */
  885. if (!prev)
  886. reclaim->generation = gen;
  887. else if (reclaim->generation != gen)
  888. goto out_unlock;
  889. pos = READ_ONCE(iter->position);
  890. } else
  891. pos = prev;
  892. css = pos ? &pos->css : NULL;
  893. while ((css = css_next_descendant_pre(css, &root->css))) {
  894. /*
  895. * Verify the css and acquire a reference. The root
  896. * is provided by the caller, so we know it's alive
  897. * and kicking, and don't take an extra reference.
  898. */
  899. if (css == &root->css || css_tryget(css))
  900. break;
  901. }
  902. next = mem_cgroup_from_css(css);
  903. if (reclaim) {
  904. /*
  905. * The position could have already been updated by a competing
  906. * thread, so check that the value hasn't changed since we read
  907. * it to avoid reclaiming from the same cgroup twice.
  908. */
  909. if (cmpxchg(&iter->position, pos, next) != pos) {
  910. if (css && css != &root->css)
  911. css_put(css);
  912. goto restart;
  913. }
  914. if (!next) {
  915. atomic_inc(&iter->generation);
  916. /*
  917. * Reclaimers share the hierarchy walk, and a
  918. * new one might jump in right at the end of
  919. * the hierarchy - make sure they see at least
  920. * one group and restart from the beginning.
  921. */
  922. if (!prev)
  923. goto restart;
  924. }
  925. }
  926. out_unlock:
  927. rcu_read_unlock();
  928. if (prev && prev != root)
  929. css_put(&prev->css);
  930. return next;
  931. }
  932. /**
  933. * mem_cgroup_iter_break - abort a hierarchy walk prematurely
  934. * @root: hierarchy root
  935. * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
  936. */
  937. void mem_cgroup_iter_break(struct mem_cgroup *root,
  938. struct mem_cgroup *prev)
  939. {
  940. if (!root)
  941. root = root_mem_cgroup;
  942. if (prev && prev != root)
  943. css_put(&prev->css);
  944. }
  945. static void __invalidate_reclaim_iterators(struct mem_cgroup *from,
  946. struct mem_cgroup *dead_memcg)
  947. {
  948. struct mem_cgroup_reclaim_iter *iter;
  949. struct mem_cgroup_per_node *mz;
  950. int nid;
  951. for_each_node(nid) {
  952. mz = from->nodeinfo[nid];
  953. iter = &mz->iter;
  954. cmpxchg(&iter->position, dead_memcg, NULL);
  955. }
  956. }
  957. static void invalidate_reclaim_iterators(struct mem_cgroup *dead_memcg)
  958. {
  959. struct mem_cgroup *memcg = dead_memcg;
  960. struct mem_cgroup *last;
  961. do {
  962. __invalidate_reclaim_iterators(memcg, dead_memcg);
  963. last = memcg;
  964. } while ((memcg = parent_mem_cgroup(memcg)));
  965. /*
  966. * When cgroup1 non-hierarchy mode is used,
  967. * parent_mem_cgroup() does not walk all the way up to the
  968. * cgroup root (root_mem_cgroup). So we have to handle
  969. * dead_memcg from cgroup root separately.
  970. */
  971. if (!mem_cgroup_is_root(last))
  972. __invalidate_reclaim_iterators(root_mem_cgroup,
  973. dead_memcg);
  974. }
  975. /**
  976. * mem_cgroup_scan_tasks - iterate over tasks of a memory cgroup hierarchy
  977. * @memcg: hierarchy root
  978. * @fn: function to call for each task
  979. * @arg: argument passed to @fn
  980. *
  981. * This function iterates over tasks attached to @memcg or to any of its
  982. * descendants and calls @fn for each task. If @fn returns a non-zero
  983. * value, the function breaks the iteration loop. Otherwise, it will iterate
  984. * over all tasks and return 0.
  985. *
  986. * This function must not be called for the root memory cgroup.
  987. */
  988. void mem_cgroup_scan_tasks(struct mem_cgroup *memcg,
  989. int (*fn)(struct task_struct *, void *), void *arg)
  990. {
  991. struct mem_cgroup *iter;
  992. int ret = 0;
  993. BUG_ON(mem_cgroup_is_root(memcg));
  994. for_each_mem_cgroup_tree(iter, memcg) {
  995. struct css_task_iter it;
  996. struct task_struct *task;
  997. css_task_iter_start(&iter->css, CSS_TASK_ITER_PROCS, &it);
  998. while (!ret && (task = css_task_iter_next(&it))) {
  999. ret = fn(task, arg);
  1000. /* Avoid potential softlockup warning */
  1001. cond_resched();
  1002. }
  1003. css_task_iter_end(&it);
  1004. if (ret) {
  1005. mem_cgroup_iter_break(memcg, iter);
  1006. break;
  1007. }
  1008. }
  1009. }
  1010. #ifdef CONFIG_DEBUG_VM
  1011. void lruvec_memcg_debug(struct lruvec *lruvec, struct folio *folio)
  1012. {
  1013. struct mem_cgroup *memcg;
  1014. if (mem_cgroup_disabled())
  1015. return;
  1016. memcg = folio_memcg(folio);
  1017. if (!memcg)
  1018. VM_BUG_ON_FOLIO(!mem_cgroup_is_root(lruvec_memcg(lruvec)), folio);
  1019. else
  1020. VM_BUG_ON_FOLIO(lruvec_memcg(lruvec) != memcg, folio);
  1021. }
  1022. #endif
  1023. /**
  1024. * folio_lruvec_lock - Lock the lruvec for a folio.
  1025. * @folio: Pointer to the folio.
  1026. *
  1027. * These functions are safe to use under any of the following conditions:
  1028. * - folio locked
  1029. * - folio_test_lru false
  1030. * - folio frozen (refcount of 0)
  1031. *
  1032. * Return: The lruvec this folio is on with its lock held.
  1033. */
  1034. struct lruvec *folio_lruvec_lock(struct folio *folio)
  1035. {
  1036. struct lruvec *lruvec = folio_lruvec(folio);
  1037. spin_lock(&lruvec->lru_lock);
  1038. lruvec_memcg_debug(lruvec, folio);
  1039. return lruvec;
  1040. }
  1041. /**
  1042. * folio_lruvec_lock_irq - Lock the lruvec for a folio.
  1043. * @folio: Pointer to the folio.
  1044. *
  1045. * These functions are safe to use under any of the following conditions:
  1046. * - folio locked
  1047. * - folio_test_lru false
  1048. * - folio frozen (refcount of 0)
  1049. *
  1050. * Return: The lruvec this folio is on with its lock held and interrupts
  1051. * disabled.
  1052. */
  1053. struct lruvec *folio_lruvec_lock_irq(struct folio *folio)
  1054. {
  1055. struct lruvec *lruvec = folio_lruvec(folio);
  1056. spin_lock_irq(&lruvec->lru_lock);
  1057. lruvec_memcg_debug(lruvec, folio);
  1058. return lruvec;
  1059. }
  1060. /**
  1061. * folio_lruvec_lock_irqsave - Lock the lruvec for a folio.
  1062. * @folio: Pointer to the folio.
  1063. * @flags: Pointer to irqsave flags.
  1064. *
  1065. * These functions are safe to use under any of the following conditions:
  1066. * - folio locked
  1067. * - folio_test_lru false
  1068. * - folio frozen (refcount of 0)
  1069. *
  1070. * Return: The lruvec this folio is on with its lock held and interrupts
  1071. * disabled.
  1072. */
  1073. struct lruvec *folio_lruvec_lock_irqsave(struct folio *folio,
  1074. unsigned long *flags)
  1075. {
  1076. struct lruvec *lruvec = folio_lruvec(folio);
  1077. spin_lock_irqsave(&lruvec->lru_lock, *flags);
  1078. lruvec_memcg_debug(lruvec, folio);
  1079. return lruvec;
  1080. }
  1081. /**
  1082. * mem_cgroup_update_lru_size - account for adding or removing an lru page
  1083. * @lruvec: mem_cgroup per zone lru vector
  1084. * @lru: index of lru list the page is sitting on
  1085. * @zid: zone id of the accounted pages
  1086. * @nr_pages: positive when adding or negative when removing
  1087. *
  1088. * This function must be called under lru_lock, just before a page is added
  1089. * to or just after a page is removed from an lru list.
  1090. */
  1091. void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
  1092. int zid, int nr_pages)
  1093. {
  1094. struct mem_cgroup_per_node *mz;
  1095. unsigned long *lru_size;
  1096. long size;
  1097. if (mem_cgroup_disabled())
  1098. return;
  1099. mz = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
  1100. lru_size = &mz->lru_zone_size[zid][lru];
  1101. if (nr_pages < 0)
  1102. *lru_size += nr_pages;
  1103. size = *lru_size;
  1104. if (WARN_ONCE(size < 0,
  1105. "%s(%p, %d, %d): lru_size %ld\n",
  1106. __func__, lruvec, lru, nr_pages, size)) {
  1107. VM_BUG_ON(1);
  1108. *lru_size = 0;
  1109. }
  1110. if (nr_pages > 0)
  1111. *lru_size += nr_pages;
  1112. }
  1113. /**
  1114. * mem_cgroup_margin - calculate chargeable space of a memory cgroup
  1115. * @memcg: the memory cgroup
  1116. *
  1117. * Returns the maximum amount of memory @mem can be charged with, in
  1118. * pages.
  1119. */
  1120. static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
  1121. {
  1122. unsigned long margin = 0;
  1123. unsigned long count;
  1124. unsigned long limit;
  1125. count = page_counter_read(&memcg->memory);
  1126. limit = READ_ONCE(memcg->memory.max);
  1127. if (count < limit)
  1128. margin = limit - count;
  1129. if (do_memsw_account()) {
  1130. count = page_counter_read(&memcg->memsw);
  1131. limit = READ_ONCE(memcg->memsw.max);
  1132. if (count < limit)
  1133. margin = min(margin, limit - count);
  1134. else
  1135. margin = 0;
  1136. }
  1137. return margin;
  1138. }
  1139. struct memory_stat {
  1140. const char *name;
  1141. unsigned int idx;
  1142. };
  1143. static const struct memory_stat memory_stats[] = {
  1144. { "anon", NR_ANON_MAPPED },
  1145. { "file", NR_FILE_PAGES },
  1146. { "kernel", MEMCG_KMEM },
  1147. { "kernel_stack", NR_KERNEL_STACK_KB },
  1148. { "pagetables", NR_PAGETABLE },
  1149. { "sec_pagetables", NR_SECONDARY_PAGETABLE },
  1150. { "percpu", MEMCG_PERCPU_B },
  1151. { "sock", MEMCG_SOCK },
  1152. { "vmalloc", MEMCG_VMALLOC },
  1153. { "shmem", NR_SHMEM },
  1154. #ifdef CONFIG_ZSWAP
  1155. { "zswap", MEMCG_ZSWAP_B },
  1156. { "zswapped", MEMCG_ZSWAPPED },
  1157. #endif
  1158. { "file_mapped", NR_FILE_MAPPED },
  1159. { "file_dirty", NR_FILE_DIRTY },
  1160. { "file_writeback", NR_WRITEBACK },
  1161. #ifdef CONFIG_SWAP
  1162. { "swapcached", NR_SWAPCACHE },
  1163. #endif
  1164. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  1165. { "anon_thp", NR_ANON_THPS },
  1166. { "file_thp", NR_FILE_THPS },
  1167. { "shmem_thp", NR_SHMEM_THPS },
  1168. #endif
  1169. { "inactive_anon", NR_INACTIVE_ANON },
  1170. { "active_anon", NR_ACTIVE_ANON },
  1171. { "inactive_file", NR_INACTIVE_FILE },
  1172. { "active_file", NR_ACTIVE_FILE },
  1173. { "unevictable", NR_UNEVICTABLE },
  1174. { "slab_reclaimable", NR_SLAB_RECLAIMABLE_B },
  1175. { "slab_unreclaimable", NR_SLAB_UNRECLAIMABLE_B },
  1176. #ifdef CONFIG_HUGETLB_PAGE
  1177. { "hugetlb", NR_HUGETLB },
  1178. #endif
  1179. /* The memory events */
  1180. { "workingset_refault_anon", WORKINGSET_REFAULT_ANON },
  1181. { "workingset_refault_file", WORKINGSET_REFAULT_FILE },
  1182. { "workingset_activate_anon", WORKINGSET_ACTIVATE_ANON },
  1183. { "workingset_activate_file", WORKINGSET_ACTIVATE_FILE },
  1184. { "workingset_restore_anon", WORKINGSET_RESTORE_ANON },
  1185. { "workingset_restore_file", WORKINGSET_RESTORE_FILE },
  1186. { "workingset_nodereclaim", WORKINGSET_NODERECLAIM },
  1187. { "pgdemote_kswapd", PGDEMOTE_KSWAPD },
  1188. { "pgdemote_direct", PGDEMOTE_DIRECT },
  1189. { "pgdemote_khugepaged", PGDEMOTE_KHUGEPAGED },
  1190. { "pgdemote_proactive", PGDEMOTE_PROACTIVE },
  1191. #ifdef CONFIG_NUMA_BALANCING
  1192. { "pgpromote_success", PGPROMOTE_SUCCESS },
  1193. #endif
  1194. };
  1195. /* The actual unit of the state item, not the same as the output unit */
  1196. static int memcg_page_state_unit(int item)
  1197. {
  1198. switch (item) {
  1199. case MEMCG_PERCPU_B:
  1200. case MEMCG_ZSWAP_B:
  1201. case NR_SLAB_RECLAIMABLE_B:
  1202. case NR_SLAB_UNRECLAIMABLE_B:
  1203. return 1;
  1204. case NR_KERNEL_STACK_KB:
  1205. return SZ_1K;
  1206. default:
  1207. return PAGE_SIZE;
  1208. }
  1209. }
  1210. /* Translate stat items to the correct unit for memory.stat output */
  1211. static int memcg_page_state_output_unit(int item)
  1212. {
  1213. /*
  1214. * Workingset state is actually in pages, but we export it to userspace
  1215. * as a scalar count of events, so special case it here.
  1216. *
  1217. * Demotion and promotion activities are exported in pages, consistent
  1218. * with their global counterparts.
  1219. */
  1220. switch (item) {
  1221. case WORKINGSET_REFAULT_ANON:
  1222. case WORKINGSET_REFAULT_FILE:
  1223. case WORKINGSET_ACTIVATE_ANON:
  1224. case WORKINGSET_ACTIVATE_FILE:
  1225. case WORKINGSET_RESTORE_ANON:
  1226. case WORKINGSET_RESTORE_FILE:
  1227. case WORKINGSET_NODERECLAIM:
  1228. case PGDEMOTE_KSWAPD:
  1229. case PGDEMOTE_DIRECT:
  1230. case PGDEMOTE_KHUGEPAGED:
  1231. case PGDEMOTE_PROACTIVE:
  1232. #ifdef CONFIG_NUMA_BALANCING
  1233. case PGPROMOTE_SUCCESS:
  1234. #endif
  1235. return 1;
  1236. default:
  1237. return memcg_page_state_unit(item);
  1238. }
  1239. }
  1240. unsigned long memcg_page_state_output(struct mem_cgroup *memcg, int item)
  1241. {
  1242. return memcg_page_state(memcg, item) *
  1243. memcg_page_state_output_unit(item);
  1244. }
  1245. #ifdef CONFIG_MEMCG_V1
  1246. unsigned long memcg_page_state_local_output(struct mem_cgroup *memcg, int item)
  1247. {
  1248. return memcg_page_state_local(memcg, item) *
  1249. memcg_page_state_output_unit(item);
  1250. }
  1251. #endif
  1252. #ifdef CONFIG_HUGETLB_PAGE
  1253. static bool memcg_accounts_hugetlb(void)
  1254. {
  1255. return cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_HUGETLB_ACCOUNTING;
  1256. }
  1257. #else /* CONFIG_HUGETLB_PAGE */
  1258. static bool memcg_accounts_hugetlb(void)
  1259. {
  1260. return false;
  1261. }
  1262. #endif /* CONFIG_HUGETLB_PAGE */
  1263. static void memcg_stat_format(struct mem_cgroup *memcg, struct seq_buf *s)
  1264. {
  1265. int i;
  1266. /*
  1267. * Provide statistics on the state of the memory subsystem as
  1268. * well as cumulative event counters that show past behavior.
  1269. *
  1270. * This list is ordered following a combination of these gradients:
  1271. * 1) generic big picture -> specifics and details
  1272. * 2) reflecting userspace activity -> reflecting kernel heuristics
  1273. *
  1274. * Current memory state:
  1275. */
  1276. mem_cgroup_flush_stats(memcg);
  1277. for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
  1278. u64 size;
  1279. #ifdef CONFIG_HUGETLB_PAGE
  1280. if (unlikely(memory_stats[i].idx == NR_HUGETLB) &&
  1281. !memcg_accounts_hugetlb())
  1282. continue;
  1283. #endif
  1284. size = memcg_page_state_output(memcg, memory_stats[i].idx);
  1285. seq_buf_printf(s, "%s %llu\n", memory_stats[i].name, size);
  1286. if (unlikely(memory_stats[i].idx == NR_SLAB_UNRECLAIMABLE_B)) {
  1287. size += memcg_page_state_output(memcg,
  1288. NR_SLAB_RECLAIMABLE_B);
  1289. seq_buf_printf(s, "slab %llu\n", size);
  1290. }
  1291. }
  1292. /* Accumulated memory events */
  1293. seq_buf_printf(s, "pgscan %lu\n",
  1294. memcg_events(memcg, PGSCAN_KSWAPD) +
  1295. memcg_events(memcg, PGSCAN_DIRECT) +
  1296. memcg_events(memcg, PGSCAN_PROACTIVE) +
  1297. memcg_events(memcg, PGSCAN_KHUGEPAGED));
  1298. seq_buf_printf(s, "pgsteal %lu\n",
  1299. memcg_events(memcg, PGSTEAL_KSWAPD) +
  1300. memcg_events(memcg, PGSTEAL_DIRECT) +
  1301. memcg_events(memcg, PGSTEAL_PROACTIVE) +
  1302. memcg_events(memcg, PGSTEAL_KHUGEPAGED));
  1303. for (i = 0; i < ARRAY_SIZE(memcg_vm_event_stat); i++) {
  1304. #ifdef CONFIG_MEMCG_V1
  1305. if (memcg_vm_event_stat[i] == PGPGIN ||
  1306. memcg_vm_event_stat[i] == PGPGOUT)
  1307. continue;
  1308. #endif
  1309. seq_buf_printf(s, "%s %lu\n",
  1310. vm_event_name(memcg_vm_event_stat[i]),
  1311. memcg_events(memcg, memcg_vm_event_stat[i]));
  1312. }
  1313. }
  1314. static void memory_stat_format(struct mem_cgroup *memcg, struct seq_buf *s)
  1315. {
  1316. if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
  1317. memcg_stat_format(memcg, s);
  1318. else
  1319. memcg1_stat_format(memcg, s);
  1320. if (seq_buf_has_overflowed(s))
  1321. pr_warn("%s: Warning, stat buffer overflow, please report\n", __func__);
  1322. }
  1323. /**
  1324. * mem_cgroup_print_oom_context: Print OOM information relevant to
  1325. * memory controller.
  1326. * @memcg: The memory cgroup that went over limit
  1327. * @p: Task that is going to be killed
  1328. *
  1329. * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
  1330. * enabled
  1331. */
  1332. void mem_cgroup_print_oom_context(struct mem_cgroup *memcg, struct task_struct *p)
  1333. {
  1334. rcu_read_lock();
  1335. if (memcg) {
  1336. pr_cont(",oom_memcg=");
  1337. pr_cont_cgroup_path(memcg->css.cgroup);
  1338. } else
  1339. pr_cont(",global_oom");
  1340. if (p) {
  1341. pr_cont(",task_memcg=");
  1342. pr_cont_cgroup_path(task_cgroup(p, memory_cgrp_id));
  1343. }
  1344. rcu_read_unlock();
  1345. }
  1346. /**
  1347. * mem_cgroup_print_oom_meminfo: Print OOM memory information relevant to
  1348. * memory controller.
  1349. * @memcg: The memory cgroup that went over limit
  1350. */
  1351. void mem_cgroup_print_oom_meminfo(struct mem_cgroup *memcg)
  1352. {
  1353. /* Use static buffer, for the caller is holding oom_lock. */
  1354. static char buf[SEQ_BUF_SIZE];
  1355. struct seq_buf s;
  1356. unsigned long memory_failcnt;
  1357. lockdep_assert_held(&oom_lock);
  1358. if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
  1359. memory_failcnt = atomic_long_read(&memcg->memory_events[MEMCG_MAX]);
  1360. else
  1361. memory_failcnt = memcg->memory.failcnt;
  1362. pr_info("memory: usage %llukB, limit %llukB, failcnt %lu\n",
  1363. K((u64)page_counter_read(&memcg->memory)),
  1364. K((u64)READ_ONCE(memcg->memory.max)), memory_failcnt);
  1365. if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
  1366. pr_info("swap: usage %llukB, limit %llukB, failcnt %lu\n",
  1367. K((u64)page_counter_read(&memcg->swap)),
  1368. K((u64)READ_ONCE(memcg->swap.max)),
  1369. atomic_long_read(&memcg->memory_events[MEMCG_SWAP_MAX]));
  1370. #ifdef CONFIG_MEMCG_V1
  1371. else {
  1372. pr_info("memory+swap: usage %llukB, limit %llukB, failcnt %lu\n",
  1373. K((u64)page_counter_read(&memcg->memsw)),
  1374. K((u64)memcg->memsw.max), memcg->memsw.failcnt);
  1375. pr_info("kmem: usage %llukB, limit %llukB, failcnt %lu\n",
  1376. K((u64)page_counter_read(&memcg->kmem)),
  1377. K((u64)memcg->kmem.max), memcg->kmem.failcnt);
  1378. }
  1379. #endif
  1380. pr_info("Memory cgroup stats for ");
  1381. pr_cont_cgroup_path(memcg->css.cgroup);
  1382. pr_cont(":");
  1383. seq_buf_init(&s, buf, SEQ_BUF_SIZE);
  1384. memory_stat_format(memcg, &s);
  1385. seq_buf_do_printk(&s, KERN_INFO);
  1386. }
  1387. /*
  1388. * Return the memory (and swap, if configured) limit for a memcg.
  1389. */
  1390. unsigned long mem_cgroup_get_max(struct mem_cgroup *memcg)
  1391. {
  1392. unsigned long max = READ_ONCE(memcg->memory.max);
  1393. if (do_memsw_account()) {
  1394. if (mem_cgroup_swappiness(memcg)) {
  1395. /* Calculate swap excess capacity from memsw limit */
  1396. unsigned long swap = READ_ONCE(memcg->memsw.max) - max;
  1397. max += min(swap, (unsigned long)total_swap_pages);
  1398. }
  1399. } else {
  1400. if (mem_cgroup_swappiness(memcg))
  1401. max += min(READ_ONCE(memcg->swap.max),
  1402. (unsigned long)total_swap_pages);
  1403. }
  1404. return max;
  1405. }
  1406. void __memcg_memory_event(struct mem_cgroup *memcg,
  1407. enum memcg_memory_event event, bool allow_spinning)
  1408. {
  1409. bool swap_event = event == MEMCG_SWAP_HIGH || event == MEMCG_SWAP_MAX ||
  1410. event == MEMCG_SWAP_FAIL;
  1411. /* For now only MEMCG_MAX can happen with !allow_spinning context. */
  1412. VM_WARN_ON_ONCE(!allow_spinning && event != MEMCG_MAX);
  1413. atomic_long_inc(&memcg->memory_events_local[event]);
  1414. if (!swap_event && allow_spinning)
  1415. cgroup_file_notify(&memcg->events_local_file);
  1416. do {
  1417. atomic_long_inc(&memcg->memory_events[event]);
  1418. if (allow_spinning) {
  1419. if (swap_event)
  1420. cgroup_file_notify(&memcg->swap_events_file);
  1421. else
  1422. cgroup_file_notify(&memcg->events_file);
  1423. }
  1424. if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
  1425. break;
  1426. if (cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_LOCAL_EVENTS)
  1427. break;
  1428. } while ((memcg = parent_mem_cgroup(memcg)) &&
  1429. !mem_cgroup_is_root(memcg));
  1430. }
  1431. EXPORT_SYMBOL_GPL(__memcg_memory_event);
  1432. static bool mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
  1433. int order)
  1434. {
  1435. struct oom_control oc = {
  1436. .zonelist = NULL,
  1437. .nodemask = NULL,
  1438. .memcg = memcg,
  1439. .gfp_mask = gfp_mask,
  1440. .order = order,
  1441. };
  1442. bool ret = true;
  1443. if (mutex_lock_killable(&oom_lock))
  1444. return true;
  1445. if (mem_cgroup_margin(memcg) >= (1 << order))
  1446. goto unlock;
  1447. /*
  1448. * A few threads which were not waiting at mutex_lock_killable() can
  1449. * fail to bail out. Therefore, check again after holding oom_lock.
  1450. */
  1451. ret = out_of_memory(&oc);
  1452. unlock:
  1453. mutex_unlock(&oom_lock);
  1454. return ret;
  1455. }
  1456. /*
  1457. * Returns true if successfully killed one or more processes. Though in some
  1458. * corner cases it can return true even without killing any process.
  1459. */
  1460. static bool mem_cgroup_oom(struct mem_cgroup *memcg, gfp_t mask, int order)
  1461. {
  1462. bool locked, ret;
  1463. if (order > PAGE_ALLOC_COSTLY_ORDER)
  1464. return false;
  1465. memcg_memory_event(memcg, MEMCG_OOM);
  1466. if (!memcg1_oom_prepare(memcg, &locked))
  1467. return false;
  1468. ret = mem_cgroup_out_of_memory(memcg, mask, order);
  1469. memcg1_oom_finish(memcg, locked);
  1470. return ret;
  1471. }
  1472. /**
  1473. * mem_cgroup_get_oom_group - get a memory cgroup to clean up after OOM
  1474. * @victim: task to be killed by the OOM killer
  1475. * @oom_domain: memcg in case of memcg OOM, NULL in case of system-wide OOM
  1476. *
  1477. * Returns a pointer to a memory cgroup, which has to be cleaned up
  1478. * by killing all belonging OOM-killable tasks.
  1479. *
  1480. * Caller has to call mem_cgroup_put() on the returned non-NULL memcg.
  1481. */
  1482. struct mem_cgroup *mem_cgroup_get_oom_group(struct task_struct *victim,
  1483. struct mem_cgroup *oom_domain)
  1484. {
  1485. struct mem_cgroup *oom_group = NULL;
  1486. struct mem_cgroup *memcg;
  1487. if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
  1488. return NULL;
  1489. if (!oom_domain)
  1490. oom_domain = root_mem_cgroup;
  1491. rcu_read_lock();
  1492. memcg = mem_cgroup_from_task(victim);
  1493. if (mem_cgroup_is_root(memcg))
  1494. goto out;
  1495. /*
  1496. * If the victim task has been asynchronously moved to a different
  1497. * memory cgroup, we might end up killing tasks outside oom_domain.
  1498. * In this case it's better to ignore memory.group.oom.
  1499. */
  1500. if (unlikely(!mem_cgroup_is_descendant(memcg, oom_domain)))
  1501. goto out;
  1502. /*
  1503. * Traverse the memory cgroup hierarchy from the victim task's
  1504. * cgroup up to the OOMing cgroup (or root) to find the
  1505. * highest-level memory cgroup with oom.group set.
  1506. */
  1507. for (; memcg; memcg = parent_mem_cgroup(memcg)) {
  1508. if (READ_ONCE(memcg->oom_group))
  1509. oom_group = memcg;
  1510. if (memcg == oom_domain)
  1511. break;
  1512. }
  1513. if (oom_group)
  1514. css_get(&oom_group->css);
  1515. out:
  1516. rcu_read_unlock();
  1517. return oom_group;
  1518. }
  1519. void mem_cgroup_print_oom_group(struct mem_cgroup *memcg)
  1520. {
  1521. pr_info("Tasks in ");
  1522. pr_cont_cgroup_path(memcg->css.cgroup);
  1523. pr_cont(" are going to be killed due to memory.oom.group set\n");
  1524. }
  1525. /*
  1526. * The value of NR_MEMCG_STOCK is selected to keep the cached memcgs and their
  1527. * nr_pages in a single cacheline. This may change in future.
  1528. */
  1529. #define NR_MEMCG_STOCK 7
  1530. #define FLUSHING_CACHED_CHARGE 0
  1531. struct memcg_stock_pcp {
  1532. local_trylock_t lock;
  1533. uint8_t nr_pages[NR_MEMCG_STOCK];
  1534. struct mem_cgroup *cached[NR_MEMCG_STOCK];
  1535. struct work_struct work;
  1536. unsigned long flags;
  1537. };
  1538. static DEFINE_PER_CPU_ALIGNED(struct memcg_stock_pcp, memcg_stock) = {
  1539. .lock = INIT_LOCAL_TRYLOCK(lock),
  1540. };
  1541. struct obj_stock_pcp {
  1542. local_trylock_t lock;
  1543. unsigned int nr_bytes;
  1544. struct obj_cgroup *cached_objcg;
  1545. struct pglist_data *cached_pgdat;
  1546. int nr_slab_reclaimable_b;
  1547. int nr_slab_unreclaimable_b;
  1548. struct work_struct work;
  1549. unsigned long flags;
  1550. };
  1551. static DEFINE_PER_CPU_ALIGNED(struct obj_stock_pcp, obj_stock) = {
  1552. .lock = INIT_LOCAL_TRYLOCK(lock),
  1553. };
  1554. static DEFINE_MUTEX(percpu_charge_mutex);
  1555. static void drain_obj_stock(struct obj_stock_pcp *stock);
  1556. static bool obj_stock_flush_required(struct obj_stock_pcp *stock,
  1557. struct mem_cgroup *root_memcg);
  1558. /**
  1559. * consume_stock: Try to consume stocked charge on this cpu.
  1560. * @memcg: memcg to consume from.
  1561. * @nr_pages: how many pages to charge.
  1562. *
  1563. * Consume the cached charge if enough nr_pages are present otherwise return
  1564. * failure. Also return failure for charge request larger than
  1565. * MEMCG_CHARGE_BATCH or if the local lock is already taken.
  1566. *
  1567. * returns true if successful, false otherwise.
  1568. */
  1569. static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
  1570. {
  1571. struct memcg_stock_pcp *stock;
  1572. uint8_t stock_pages;
  1573. bool ret = false;
  1574. int i;
  1575. if (nr_pages > MEMCG_CHARGE_BATCH ||
  1576. !local_trylock(&memcg_stock.lock))
  1577. return ret;
  1578. stock = this_cpu_ptr(&memcg_stock);
  1579. for (i = 0; i < NR_MEMCG_STOCK; ++i) {
  1580. if (memcg != READ_ONCE(stock->cached[i]))
  1581. continue;
  1582. stock_pages = READ_ONCE(stock->nr_pages[i]);
  1583. if (stock_pages >= nr_pages) {
  1584. WRITE_ONCE(stock->nr_pages[i], stock_pages - nr_pages);
  1585. ret = true;
  1586. }
  1587. break;
  1588. }
  1589. local_unlock(&memcg_stock.lock);
  1590. return ret;
  1591. }
  1592. static void memcg_uncharge(struct mem_cgroup *memcg, unsigned int nr_pages)
  1593. {
  1594. page_counter_uncharge(&memcg->memory, nr_pages);
  1595. if (do_memsw_account())
  1596. page_counter_uncharge(&memcg->memsw, nr_pages);
  1597. }
  1598. /*
  1599. * Returns stocks cached in percpu and reset cached information.
  1600. */
  1601. static void drain_stock(struct memcg_stock_pcp *stock, int i)
  1602. {
  1603. struct mem_cgroup *old = READ_ONCE(stock->cached[i]);
  1604. uint8_t stock_pages;
  1605. if (!old)
  1606. return;
  1607. stock_pages = READ_ONCE(stock->nr_pages[i]);
  1608. if (stock_pages) {
  1609. memcg_uncharge(old, stock_pages);
  1610. WRITE_ONCE(stock->nr_pages[i], 0);
  1611. }
  1612. css_put(&old->css);
  1613. WRITE_ONCE(stock->cached[i], NULL);
  1614. }
  1615. static void drain_stock_fully(struct memcg_stock_pcp *stock)
  1616. {
  1617. int i;
  1618. for (i = 0; i < NR_MEMCG_STOCK; ++i)
  1619. drain_stock(stock, i);
  1620. }
  1621. static void drain_local_memcg_stock(struct work_struct *dummy)
  1622. {
  1623. struct memcg_stock_pcp *stock;
  1624. if (WARN_ONCE(!in_task(), "drain in non-task context"))
  1625. return;
  1626. local_lock(&memcg_stock.lock);
  1627. stock = this_cpu_ptr(&memcg_stock);
  1628. drain_stock_fully(stock);
  1629. clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
  1630. local_unlock(&memcg_stock.lock);
  1631. }
  1632. static void drain_local_obj_stock(struct work_struct *dummy)
  1633. {
  1634. struct obj_stock_pcp *stock;
  1635. if (WARN_ONCE(!in_task(), "drain in non-task context"))
  1636. return;
  1637. local_lock(&obj_stock.lock);
  1638. stock = this_cpu_ptr(&obj_stock);
  1639. drain_obj_stock(stock);
  1640. clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
  1641. local_unlock(&obj_stock.lock);
  1642. }
  1643. static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
  1644. {
  1645. struct memcg_stock_pcp *stock;
  1646. struct mem_cgroup *cached;
  1647. uint8_t stock_pages;
  1648. bool success = false;
  1649. int empty_slot = -1;
  1650. int i;
  1651. /*
  1652. * For now limit MEMCG_CHARGE_BATCH to 127 and less. In future if we
  1653. * decide to increase it more than 127 then we will need more careful
  1654. * handling of nr_pages[] in struct memcg_stock_pcp.
  1655. */
  1656. BUILD_BUG_ON(MEMCG_CHARGE_BATCH > S8_MAX);
  1657. VM_WARN_ON_ONCE(mem_cgroup_is_root(memcg));
  1658. if (nr_pages > MEMCG_CHARGE_BATCH ||
  1659. !local_trylock(&memcg_stock.lock)) {
  1660. /*
  1661. * In case of larger than batch refill or unlikely failure to
  1662. * lock the percpu memcg_stock.lock, uncharge memcg directly.
  1663. */
  1664. memcg_uncharge(memcg, nr_pages);
  1665. return;
  1666. }
  1667. stock = this_cpu_ptr(&memcg_stock);
  1668. for (i = 0; i < NR_MEMCG_STOCK; ++i) {
  1669. cached = READ_ONCE(stock->cached[i]);
  1670. if (!cached && empty_slot == -1)
  1671. empty_slot = i;
  1672. if (memcg == READ_ONCE(stock->cached[i])) {
  1673. stock_pages = READ_ONCE(stock->nr_pages[i]) + nr_pages;
  1674. WRITE_ONCE(stock->nr_pages[i], stock_pages);
  1675. if (stock_pages > MEMCG_CHARGE_BATCH)
  1676. drain_stock(stock, i);
  1677. success = true;
  1678. break;
  1679. }
  1680. }
  1681. if (!success) {
  1682. i = empty_slot;
  1683. if (i == -1) {
  1684. i = get_random_u32_below(NR_MEMCG_STOCK);
  1685. drain_stock(stock, i);
  1686. }
  1687. css_get(&memcg->css);
  1688. WRITE_ONCE(stock->cached[i], memcg);
  1689. WRITE_ONCE(stock->nr_pages[i], nr_pages);
  1690. }
  1691. local_unlock(&memcg_stock.lock);
  1692. }
  1693. static bool is_memcg_drain_needed(struct memcg_stock_pcp *stock,
  1694. struct mem_cgroup *root_memcg)
  1695. {
  1696. struct mem_cgroup *memcg;
  1697. bool flush = false;
  1698. int i;
  1699. rcu_read_lock();
  1700. for (i = 0; i < NR_MEMCG_STOCK; ++i) {
  1701. memcg = READ_ONCE(stock->cached[i]);
  1702. if (!memcg)
  1703. continue;
  1704. if (READ_ONCE(stock->nr_pages[i]) &&
  1705. mem_cgroup_is_descendant(memcg, root_memcg)) {
  1706. flush = true;
  1707. break;
  1708. }
  1709. }
  1710. rcu_read_unlock();
  1711. return flush;
  1712. }
  1713. static void schedule_drain_work(int cpu, struct work_struct *work)
  1714. {
  1715. /*
  1716. * Protect housekeeping cpumask read and work enqueue together
  1717. * in the same RCU critical section so that later cpuset isolated
  1718. * partition update only need to wait for an RCU GP and flush the
  1719. * pending work on newly isolated CPUs.
  1720. */
  1721. guard(rcu)();
  1722. if (!cpu_is_isolated(cpu))
  1723. queue_work_on(cpu, memcg_wq, work);
  1724. }
  1725. /*
  1726. * Drains all per-CPU charge caches for given root_memcg resp. subtree
  1727. * of the hierarchy under it.
  1728. */
  1729. void drain_all_stock(struct mem_cgroup *root_memcg)
  1730. {
  1731. int cpu, curcpu;
  1732. /* If someone's already draining, avoid adding running more workers. */
  1733. if (!mutex_trylock(&percpu_charge_mutex))
  1734. return;
  1735. /*
  1736. * Notify other cpus that system-wide "drain" is running
  1737. * We do not care about races with the cpu hotplug because cpu down
  1738. * as well as workers from this path always operate on the local
  1739. * per-cpu data. CPU up doesn't touch memcg_stock at all.
  1740. */
  1741. migrate_disable();
  1742. curcpu = smp_processor_id();
  1743. for_each_online_cpu(cpu) {
  1744. struct memcg_stock_pcp *memcg_st = &per_cpu(memcg_stock, cpu);
  1745. struct obj_stock_pcp *obj_st = &per_cpu(obj_stock, cpu);
  1746. if (!test_bit(FLUSHING_CACHED_CHARGE, &memcg_st->flags) &&
  1747. is_memcg_drain_needed(memcg_st, root_memcg) &&
  1748. !test_and_set_bit(FLUSHING_CACHED_CHARGE,
  1749. &memcg_st->flags)) {
  1750. if (cpu == curcpu)
  1751. drain_local_memcg_stock(&memcg_st->work);
  1752. else
  1753. schedule_drain_work(cpu, &memcg_st->work);
  1754. }
  1755. if (!test_bit(FLUSHING_CACHED_CHARGE, &obj_st->flags) &&
  1756. obj_stock_flush_required(obj_st, root_memcg) &&
  1757. !test_and_set_bit(FLUSHING_CACHED_CHARGE,
  1758. &obj_st->flags)) {
  1759. if (cpu == curcpu)
  1760. drain_local_obj_stock(&obj_st->work);
  1761. else
  1762. schedule_drain_work(cpu, &obj_st->work);
  1763. }
  1764. }
  1765. migrate_enable();
  1766. mutex_unlock(&percpu_charge_mutex);
  1767. }
  1768. static int memcg_hotplug_cpu_dead(unsigned int cpu)
  1769. {
  1770. /* no need for the local lock */
  1771. drain_obj_stock(&per_cpu(obj_stock, cpu));
  1772. drain_stock_fully(&per_cpu(memcg_stock, cpu));
  1773. return 0;
  1774. }
  1775. static unsigned long reclaim_high(struct mem_cgroup *memcg,
  1776. unsigned int nr_pages,
  1777. gfp_t gfp_mask)
  1778. {
  1779. unsigned long nr_reclaimed = 0;
  1780. do {
  1781. unsigned long pflags;
  1782. if (page_counter_read(&memcg->memory) <=
  1783. READ_ONCE(memcg->memory.high))
  1784. continue;
  1785. memcg_memory_event(memcg, MEMCG_HIGH);
  1786. psi_memstall_enter(&pflags);
  1787. nr_reclaimed += try_to_free_mem_cgroup_pages(memcg, nr_pages,
  1788. gfp_mask,
  1789. MEMCG_RECLAIM_MAY_SWAP,
  1790. NULL);
  1791. psi_memstall_leave(&pflags);
  1792. } while ((memcg = parent_mem_cgroup(memcg)) &&
  1793. !mem_cgroup_is_root(memcg));
  1794. return nr_reclaimed;
  1795. }
  1796. static void high_work_func(struct work_struct *work)
  1797. {
  1798. struct mem_cgroup *memcg;
  1799. memcg = container_of(work, struct mem_cgroup, high_work);
  1800. reclaim_high(memcg, MEMCG_CHARGE_BATCH, GFP_KERNEL);
  1801. }
  1802. /*
  1803. * Clamp the maximum sleep time per allocation batch to 2 seconds. This is
  1804. * enough to still cause a significant slowdown in most cases, while still
  1805. * allowing diagnostics and tracing to proceed without becoming stuck.
  1806. */
  1807. #define MEMCG_MAX_HIGH_DELAY_JIFFIES (2UL*HZ)
  1808. /*
  1809. * When calculating the delay, we use these either side of the exponentiation to
  1810. * maintain precision and scale to a reasonable number of jiffies (see the table
  1811. * below.
  1812. *
  1813. * - MEMCG_DELAY_PRECISION_SHIFT: Extra precision bits while translating the
  1814. * overage ratio to a delay.
  1815. * - MEMCG_DELAY_SCALING_SHIFT: The number of bits to scale down the
  1816. * proposed penalty in order to reduce to a reasonable number of jiffies, and
  1817. * to produce a reasonable delay curve.
  1818. *
  1819. * MEMCG_DELAY_SCALING_SHIFT just happens to be a number that produces a
  1820. * reasonable delay curve compared to precision-adjusted overage, not
  1821. * penalising heavily at first, but still making sure that growth beyond the
  1822. * limit penalises misbehaviour cgroups by slowing them down exponentially. For
  1823. * example, with a high of 100 megabytes:
  1824. *
  1825. * +-------+------------------------+
  1826. * | usage | time to allocate in ms |
  1827. * +-------+------------------------+
  1828. * | 100M | 0 |
  1829. * | 101M | 6 |
  1830. * | 102M | 25 |
  1831. * | 103M | 57 |
  1832. * | 104M | 102 |
  1833. * | 105M | 159 |
  1834. * | 106M | 230 |
  1835. * | 107M | 313 |
  1836. * | 108M | 409 |
  1837. * | 109M | 518 |
  1838. * | 110M | 639 |
  1839. * | 111M | 774 |
  1840. * | 112M | 921 |
  1841. * | 113M | 1081 |
  1842. * | 114M | 1254 |
  1843. * | 115M | 1439 |
  1844. * | 116M | 1638 |
  1845. * | 117M | 1849 |
  1846. * | 118M | 2000 |
  1847. * | 119M | 2000 |
  1848. * | 120M | 2000 |
  1849. * +-------+------------------------+
  1850. */
  1851. #define MEMCG_DELAY_PRECISION_SHIFT 20
  1852. #define MEMCG_DELAY_SCALING_SHIFT 14
  1853. static u64 calculate_overage(unsigned long usage, unsigned long high)
  1854. {
  1855. u64 overage;
  1856. if (usage <= high)
  1857. return 0;
  1858. /*
  1859. * Prevent division by 0 in overage calculation by acting as if
  1860. * it was a threshold of 1 page
  1861. */
  1862. high = max(high, 1UL);
  1863. overage = usage - high;
  1864. overage <<= MEMCG_DELAY_PRECISION_SHIFT;
  1865. return div64_u64(overage, high);
  1866. }
  1867. static u64 mem_find_max_overage(struct mem_cgroup *memcg)
  1868. {
  1869. u64 overage, max_overage = 0;
  1870. do {
  1871. overage = calculate_overage(page_counter_read(&memcg->memory),
  1872. READ_ONCE(memcg->memory.high));
  1873. max_overage = max(overage, max_overage);
  1874. } while ((memcg = parent_mem_cgroup(memcg)) &&
  1875. !mem_cgroup_is_root(memcg));
  1876. return max_overage;
  1877. }
  1878. static u64 swap_find_max_overage(struct mem_cgroup *memcg)
  1879. {
  1880. u64 overage, max_overage = 0;
  1881. do {
  1882. overage = calculate_overage(page_counter_read(&memcg->swap),
  1883. READ_ONCE(memcg->swap.high));
  1884. if (overage)
  1885. memcg_memory_event(memcg, MEMCG_SWAP_HIGH);
  1886. max_overage = max(overage, max_overage);
  1887. } while ((memcg = parent_mem_cgroup(memcg)) &&
  1888. !mem_cgroup_is_root(memcg));
  1889. return max_overage;
  1890. }
  1891. /*
  1892. * Get the number of jiffies that we should penalise a mischievous cgroup which
  1893. * is exceeding its memory.high by checking both it and its ancestors.
  1894. */
  1895. static unsigned long calculate_high_delay(struct mem_cgroup *memcg,
  1896. unsigned int nr_pages,
  1897. u64 max_overage)
  1898. {
  1899. unsigned long penalty_jiffies;
  1900. if (!max_overage)
  1901. return 0;
  1902. /*
  1903. * We use overage compared to memory.high to calculate the number of
  1904. * jiffies to sleep (penalty_jiffies). Ideally this value should be
  1905. * fairly lenient on small overages, and increasingly harsh when the
  1906. * memcg in question makes it clear that it has no intention of stopping
  1907. * its crazy behaviour, so we exponentially increase the delay based on
  1908. * overage amount.
  1909. */
  1910. penalty_jiffies = max_overage * max_overage * HZ;
  1911. penalty_jiffies >>= MEMCG_DELAY_PRECISION_SHIFT;
  1912. penalty_jiffies >>= MEMCG_DELAY_SCALING_SHIFT;
  1913. /*
  1914. * Factor in the task's own contribution to the overage, such that four
  1915. * N-sized allocations are throttled approximately the same as one
  1916. * 4N-sized allocation.
  1917. *
  1918. * MEMCG_CHARGE_BATCH pages is nominal, so work out how much smaller or
  1919. * larger the current charge patch is than that.
  1920. */
  1921. return penalty_jiffies * nr_pages / MEMCG_CHARGE_BATCH;
  1922. }
  1923. /*
  1924. * Reclaims memory over the high limit. Called directly from
  1925. * try_charge() (context permitting), as well as from the userland
  1926. * return path where reclaim is always able to block.
  1927. */
  1928. void __mem_cgroup_handle_over_high(gfp_t gfp_mask)
  1929. {
  1930. unsigned long penalty_jiffies;
  1931. unsigned long pflags;
  1932. unsigned long nr_reclaimed;
  1933. unsigned int nr_pages = current->memcg_nr_pages_over_high;
  1934. int nr_retries = MAX_RECLAIM_RETRIES;
  1935. struct mem_cgroup *memcg;
  1936. bool in_retry = false;
  1937. memcg = get_mem_cgroup_from_mm(current->mm);
  1938. current->memcg_nr_pages_over_high = 0;
  1939. retry_reclaim:
  1940. /*
  1941. * Bail if the task is already exiting. Unlike memory.max,
  1942. * memory.high enforcement isn't as strict, and there is no
  1943. * OOM killer involved, which means the excess could already
  1944. * be much bigger (and still growing) than it could for
  1945. * memory.max; the dying task could get stuck in fruitless
  1946. * reclaim for a long time, which isn't desirable.
  1947. */
  1948. if (task_is_dying())
  1949. goto out;
  1950. /*
  1951. * The allocating task should reclaim at least the batch size, but for
  1952. * subsequent retries we only want to do what's necessary to prevent oom
  1953. * or breaching resource isolation.
  1954. *
  1955. * This is distinct from memory.max or page allocator behaviour because
  1956. * memory.high is currently batched, whereas memory.max and the page
  1957. * allocator run every time an allocation is made.
  1958. */
  1959. nr_reclaimed = reclaim_high(memcg,
  1960. in_retry ? SWAP_CLUSTER_MAX : nr_pages,
  1961. gfp_mask);
  1962. /*
  1963. * memory.high is breached and reclaim is unable to keep up. Throttle
  1964. * allocators proactively to slow down excessive growth.
  1965. */
  1966. penalty_jiffies = calculate_high_delay(memcg, nr_pages,
  1967. mem_find_max_overage(memcg));
  1968. penalty_jiffies += calculate_high_delay(memcg, nr_pages,
  1969. swap_find_max_overage(memcg));
  1970. /*
  1971. * Clamp the max delay per usermode return so as to still keep the
  1972. * application moving forwards and also permit diagnostics, albeit
  1973. * extremely slowly.
  1974. */
  1975. penalty_jiffies = min(penalty_jiffies, MEMCG_MAX_HIGH_DELAY_JIFFIES);
  1976. /*
  1977. * Don't sleep if the amount of jiffies this memcg owes us is so low
  1978. * that it's not even worth doing, in an attempt to be nice to those who
  1979. * go only a small amount over their memory.high value and maybe haven't
  1980. * been aggressively reclaimed enough yet.
  1981. */
  1982. if (penalty_jiffies <= HZ / 100)
  1983. goto out;
  1984. /*
  1985. * If reclaim is making forward progress but we're still over
  1986. * memory.high, we want to encourage that rather than doing allocator
  1987. * throttling.
  1988. */
  1989. if (nr_reclaimed || nr_retries--) {
  1990. in_retry = true;
  1991. goto retry_reclaim;
  1992. }
  1993. /*
  1994. * Reclaim didn't manage to push usage below the limit, slow
  1995. * this allocating task down.
  1996. *
  1997. * If we exit early, we're guaranteed to die (since
  1998. * schedule_timeout_killable sets TASK_KILLABLE). This means we don't
  1999. * need to account for any ill-begotten jiffies to pay them off later.
  2000. */
  2001. psi_memstall_enter(&pflags);
  2002. schedule_timeout_killable(penalty_jiffies);
  2003. psi_memstall_leave(&pflags);
  2004. out:
  2005. css_put(&memcg->css);
  2006. }
  2007. static int try_charge_memcg(struct mem_cgroup *memcg, gfp_t gfp_mask,
  2008. unsigned int nr_pages)
  2009. {
  2010. unsigned int batch = max(MEMCG_CHARGE_BATCH, nr_pages);
  2011. int nr_retries = MAX_RECLAIM_RETRIES;
  2012. struct mem_cgroup *mem_over_limit;
  2013. struct page_counter *counter;
  2014. unsigned long nr_reclaimed;
  2015. bool passed_oom = false;
  2016. unsigned int reclaim_options = MEMCG_RECLAIM_MAY_SWAP;
  2017. bool drained = false;
  2018. bool raised_max_event = false;
  2019. unsigned long pflags;
  2020. bool allow_spinning = gfpflags_allow_spinning(gfp_mask);
  2021. retry:
  2022. if (consume_stock(memcg, nr_pages))
  2023. return 0;
  2024. if (!allow_spinning)
  2025. /* Avoid the refill and flush of the older stock */
  2026. batch = nr_pages;
  2027. if (!do_memsw_account() ||
  2028. page_counter_try_charge(&memcg->memsw, batch, &counter)) {
  2029. if (page_counter_try_charge(&memcg->memory, batch, &counter))
  2030. goto done_restock;
  2031. if (do_memsw_account())
  2032. page_counter_uncharge(&memcg->memsw, batch);
  2033. mem_over_limit = mem_cgroup_from_counter(counter, memory);
  2034. } else {
  2035. mem_over_limit = mem_cgroup_from_counter(counter, memsw);
  2036. reclaim_options &= ~MEMCG_RECLAIM_MAY_SWAP;
  2037. }
  2038. if (batch > nr_pages) {
  2039. batch = nr_pages;
  2040. goto retry;
  2041. }
  2042. /*
  2043. * Prevent unbounded recursion when reclaim operations need to
  2044. * allocate memory. This might exceed the limits temporarily,
  2045. * but we prefer facilitating memory reclaim and getting back
  2046. * under the limit over triggering OOM kills in these cases.
  2047. */
  2048. if (unlikely(current->flags & PF_MEMALLOC))
  2049. goto force;
  2050. if (unlikely(task_in_memcg_oom(current)))
  2051. goto nomem;
  2052. if (!gfpflags_allow_blocking(gfp_mask))
  2053. goto nomem;
  2054. __memcg_memory_event(mem_over_limit, MEMCG_MAX, allow_spinning);
  2055. raised_max_event = true;
  2056. psi_memstall_enter(&pflags);
  2057. nr_reclaimed = try_to_free_mem_cgroup_pages(mem_over_limit, nr_pages,
  2058. gfp_mask, reclaim_options, NULL);
  2059. psi_memstall_leave(&pflags);
  2060. if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
  2061. goto retry;
  2062. if (!drained) {
  2063. drain_all_stock(mem_over_limit);
  2064. drained = true;
  2065. goto retry;
  2066. }
  2067. if (gfp_mask & __GFP_NORETRY)
  2068. goto nomem;
  2069. /*
  2070. * Even though the limit is exceeded at this point, reclaim
  2071. * may have been able to free some pages. Retry the charge
  2072. * before killing the task.
  2073. *
  2074. * Only for regular pages, though: huge pages are rather
  2075. * unlikely to succeed so close to the limit, and we fall back
  2076. * to regular pages anyway in case of failure.
  2077. */
  2078. if (nr_reclaimed && nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER))
  2079. goto retry;
  2080. if (nr_retries--)
  2081. goto retry;
  2082. if (gfp_mask & __GFP_RETRY_MAYFAIL)
  2083. goto nomem;
  2084. /* Avoid endless loop for tasks bypassed by the oom killer */
  2085. if (passed_oom && task_is_dying())
  2086. goto nomem;
  2087. /*
  2088. * keep retrying as long as the memcg oom killer is able to make
  2089. * a forward progress or bypass the charge if the oom killer
  2090. * couldn't make any progress.
  2091. */
  2092. if (mem_cgroup_oom(mem_over_limit, gfp_mask,
  2093. get_order(nr_pages * PAGE_SIZE))) {
  2094. passed_oom = true;
  2095. nr_retries = MAX_RECLAIM_RETRIES;
  2096. goto retry;
  2097. }
  2098. nomem:
  2099. /*
  2100. * Memcg doesn't have a dedicated reserve for atomic
  2101. * allocations. But like the global atomic pool, we need to
  2102. * put the burden of reclaim on regular allocation requests
  2103. * and let these go through as privileged allocations.
  2104. */
  2105. if (!(gfp_mask & (__GFP_NOFAIL | __GFP_HIGH)))
  2106. return -ENOMEM;
  2107. force:
  2108. /*
  2109. * If the allocation has to be enforced, don't forget to raise
  2110. * a MEMCG_MAX event.
  2111. */
  2112. if (!raised_max_event)
  2113. __memcg_memory_event(mem_over_limit, MEMCG_MAX, allow_spinning);
  2114. /*
  2115. * The allocation either can't fail or will lead to more memory
  2116. * being freed very soon. Allow memory usage go over the limit
  2117. * temporarily by force charging it.
  2118. */
  2119. page_counter_charge(&memcg->memory, nr_pages);
  2120. if (do_memsw_account())
  2121. page_counter_charge(&memcg->memsw, nr_pages);
  2122. return 0;
  2123. done_restock:
  2124. if (batch > nr_pages)
  2125. refill_stock(memcg, batch - nr_pages);
  2126. /*
  2127. * If the hierarchy is above the normal consumption range, schedule
  2128. * reclaim on returning to userland. We can perform reclaim here
  2129. * if __GFP_RECLAIM but let's always punt for simplicity and so that
  2130. * GFP_KERNEL can consistently be used during reclaim. @memcg is
  2131. * not recorded as it most likely matches current's and won't
  2132. * change in the meantime. As high limit is checked again before
  2133. * reclaim, the cost of mismatch is negligible.
  2134. */
  2135. do {
  2136. bool mem_high, swap_high;
  2137. mem_high = page_counter_read(&memcg->memory) >
  2138. READ_ONCE(memcg->memory.high);
  2139. swap_high = page_counter_read(&memcg->swap) >
  2140. READ_ONCE(memcg->swap.high);
  2141. /* Don't bother a random interrupted task */
  2142. if (!in_task()) {
  2143. if (mem_high) {
  2144. schedule_work(&memcg->high_work);
  2145. break;
  2146. }
  2147. continue;
  2148. }
  2149. if (mem_high || swap_high) {
  2150. /*
  2151. * The allocating tasks in this cgroup will need to do
  2152. * reclaim or be throttled to prevent further growth
  2153. * of the memory or swap footprints.
  2154. *
  2155. * Target some best-effort fairness between the tasks,
  2156. * and distribute reclaim work and delay penalties
  2157. * based on how much each task is actually allocating.
  2158. */
  2159. current->memcg_nr_pages_over_high += batch;
  2160. set_notify_resume(current);
  2161. break;
  2162. }
  2163. } while ((memcg = parent_mem_cgroup(memcg)));
  2164. /*
  2165. * Reclaim is set up above to be called from the userland
  2166. * return path. But also attempt synchronous reclaim to avoid
  2167. * excessive overrun while the task is still inside the
  2168. * kernel. If this is successful, the return path will see it
  2169. * when it rechecks the overage and simply bail out.
  2170. */
  2171. if (current->memcg_nr_pages_over_high > MEMCG_CHARGE_BATCH &&
  2172. !(current->flags & PF_MEMALLOC) &&
  2173. gfpflags_allow_blocking(gfp_mask))
  2174. __mem_cgroup_handle_over_high(gfp_mask);
  2175. return 0;
  2176. }
  2177. static inline int try_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
  2178. unsigned int nr_pages)
  2179. {
  2180. if (mem_cgroup_is_root(memcg))
  2181. return 0;
  2182. return try_charge_memcg(memcg, gfp_mask, nr_pages);
  2183. }
  2184. static void commit_charge(struct folio *folio, struct mem_cgroup *memcg)
  2185. {
  2186. VM_BUG_ON_FOLIO(folio_memcg_charged(folio), folio);
  2187. /*
  2188. * Any of the following ensures page's memcg stability:
  2189. *
  2190. * - the page lock
  2191. * - LRU isolation
  2192. * - exclusive reference
  2193. */
  2194. folio->memcg_data = (unsigned long)memcg;
  2195. }
  2196. #ifdef CONFIG_MEMCG_NMI_SAFETY_REQUIRES_ATOMIC
  2197. static inline void account_slab_nmi_safe(struct mem_cgroup *memcg,
  2198. struct pglist_data *pgdat,
  2199. enum node_stat_item idx, int nr)
  2200. {
  2201. struct lruvec *lruvec;
  2202. if (likely(!in_nmi())) {
  2203. lruvec = mem_cgroup_lruvec(memcg, pgdat);
  2204. mod_memcg_lruvec_state(lruvec, idx, nr);
  2205. } else {
  2206. struct mem_cgroup_per_node *pn = memcg->nodeinfo[pgdat->node_id];
  2207. /* preemption is disabled in_nmi(). */
  2208. css_rstat_updated(&memcg->css, smp_processor_id());
  2209. if (idx == NR_SLAB_RECLAIMABLE_B)
  2210. atomic_add(nr, &pn->slab_reclaimable);
  2211. else
  2212. atomic_add(nr, &pn->slab_unreclaimable);
  2213. }
  2214. }
  2215. #else
  2216. static inline void account_slab_nmi_safe(struct mem_cgroup *memcg,
  2217. struct pglist_data *pgdat,
  2218. enum node_stat_item idx, int nr)
  2219. {
  2220. struct lruvec *lruvec;
  2221. lruvec = mem_cgroup_lruvec(memcg, pgdat);
  2222. mod_memcg_lruvec_state(lruvec, idx, nr);
  2223. }
  2224. #endif
  2225. static inline void mod_objcg_mlstate(struct obj_cgroup *objcg,
  2226. struct pglist_data *pgdat,
  2227. enum node_stat_item idx, int nr)
  2228. {
  2229. struct mem_cgroup *memcg;
  2230. rcu_read_lock();
  2231. memcg = obj_cgroup_memcg(objcg);
  2232. account_slab_nmi_safe(memcg, pgdat, idx, nr);
  2233. rcu_read_unlock();
  2234. }
  2235. static __always_inline
  2236. struct mem_cgroup *mem_cgroup_from_obj_slab(struct slab *slab, void *p)
  2237. {
  2238. /*
  2239. * Slab objects are accounted individually, not per-page.
  2240. * Memcg membership data for each individual object is saved in
  2241. * slab->obj_exts.
  2242. */
  2243. unsigned long obj_exts;
  2244. struct slabobj_ext *obj_ext;
  2245. unsigned int off;
  2246. obj_exts = slab_obj_exts(slab);
  2247. if (!obj_exts)
  2248. return NULL;
  2249. get_slab_obj_exts(obj_exts);
  2250. off = obj_to_index(slab->slab_cache, slab, p);
  2251. obj_ext = slab_obj_ext(slab, obj_exts, off);
  2252. if (obj_ext->objcg) {
  2253. struct obj_cgroup *objcg = obj_ext->objcg;
  2254. put_slab_obj_exts(obj_exts);
  2255. return obj_cgroup_memcg(objcg);
  2256. }
  2257. put_slab_obj_exts(obj_exts);
  2258. return NULL;
  2259. }
  2260. /*
  2261. * Returns a pointer to the memory cgroup to which the kernel object is charged.
  2262. * It is not suitable for objects allocated using vmalloc().
  2263. *
  2264. * A passed kernel object must be a slab object or a generic kernel page.
  2265. *
  2266. * The caller must ensure the memcg lifetime, e.g. by taking rcu_read_lock(),
  2267. * cgroup_mutex, etc.
  2268. */
  2269. struct mem_cgroup *mem_cgroup_from_virt(void *p)
  2270. {
  2271. struct slab *slab;
  2272. if (mem_cgroup_disabled())
  2273. return NULL;
  2274. slab = virt_to_slab(p);
  2275. if (slab)
  2276. return mem_cgroup_from_obj_slab(slab, p);
  2277. return folio_memcg_check(virt_to_folio(p));
  2278. }
  2279. static struct obj_cgroup *__get_obj_cgroup_from_memcg(struct mem_cgroup *memcg)
  2280. {
  2281. struct obj_cgroup *objcg = NULL;
  2282. for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg)) {
  2283. objcg = rcu_dereference(memcg->objcg);
  2284. if (likely(objcg && obj_cgroup_tryget(objcg)))
  2285. break;
  2286. objcg = NULL;
  2287. }
  2288. return objcg;
  2289. }
  2290. static struct obj_cgroup *current_objcg_update(void)
  2291. {
  2292. struct mem_cgroup *memcg;
  2293. struct obj_cgroup *old, *objcg = NULL;
  2294. do {
  2295. /* Atomically drop the update bit. */
  2296. old = xchg(&current->objcg, NULL);
  2297. if (old) {
  2298. old = (struct obj_cgroup *)
  2299. ((unsigned long)old & ~CURRENT_OBJCG_UPDATE_FLAG);
  2300. obj_cgroup_put(old);
  2301. old = NULL;
  2302. }
  2303. /* If new objcg is NULL, no reason for the second atomic update. */
  2304. if (!current->mm || (current->flags & PF_KTHREAD))
  2305. return NULL;
  2306. /*
  2307. * Release the objcg pointer from the previous iteration,
  2308. * if try_cmpxcg() below fails.
  2309. */
  2310. if (unlikely(objcg)) {
  2311. obj_cgroup_put(objcg);
  2312. objcg = NULL;
  2313. }
  2314. /*
  2315. * Obtain the new objcg pointer. The current task can be
  2316. * asynchronously moved to another memcg and the previous
  2317. * memcg can be offlined. So let's get the memcg pointer
  2318. * and try get a reference to objcg under a rcu read lock.
  2319. */
  2320. rcu_read_lock();
  2321. memcg = mem_cgroup_from_task(current);
  2322. objcg = __get_obj_cgroup_from_memcg(memcg);
  2323. rcu_read_unlock();
  2324. /*
  2325. * Try set up a new objcg pointer atomically. If it
  2326. * fails, it means the update flag was set concurrently, so
  2327. * the whole procedure should be repeated.
  2328. */
  2329. } while (!try_cmpxchg(&current->objcg, &old, objcg));
  2330. return objcg;
  2331. }
  2332. __always_inline struct obj_cgroup *current_obj_cgroup(void)
  2333. {
  2334. struct mem_cgroup *memcg;
  2335. struct obj_cgroup *objcg;
  2336. if (IS_ENABLED(CONFIG_MEMCG_NMI_UNSAFE) && in_nmi())
  2337. return NULL;
  2338. if (in_task()) {
  2339. memcg = current->active_memcg;
  2340. if (unlikely(memcg))
  2341. goto from_memcg;
  2342. objcg = READ_ONCE(current->objcg);
  2343. if (unlikely((unsigned long)objcg & CURRENT_OBJCG_UPDATE_FLAG))
  2344. objcg = current_objcg_update();
  2345. /*
  2346. * Objcg reference is kept by the task, so it's safe
  2347. * to use the objcg by the current task.
  2348. */
  2349. return objcg;
  2350. }
  2351. memcg = this_cpu_read(int_active_memcg);
  2352. if (unlikely(memcg))
  2353. goto from_memcg;
  2354. return NULL;
  2355. from_memcg:
  2356. objcg = NULL;
  2357. for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg)) {
  2358. /*
  2359. * Memcg pointer is protected by scope (see set_active_memcg())
  2360. * and is pinning the corresponding objcg, so objcg can't go
  2361. * away and can be used within the scope without any additional
  2362. * protection.
  2363. */
  2364. objcg = rcu_dereference_check(memcg->objcg, 1);
  2365. if (likely(objcg))
  2366. break;
  2367. }
  2368. return objcg;
  2369. }
  2370. struct obj_cgroup *get_obj_cgroup_from_folio(struct folio *folio)
  2371. {
  2372. struct obj_cgroup *objcg;
  2373. if (!memcg_kmem_online())
  2374. return NULL;
  2375. if (folio_memcg_kmem(folio)) {
  2376. objcg = __folio_objcg(folio);
  2377. obj_cgroup_get(objcg);
  2378. } else {
  2379. struct mem_cgroup *memcg;
  2380. rcu_read_lock();
  2381. memcg = __folio_memcg(folio);
  2382. if (memcg)
  2383. objcg = __get_obj_cgroup_from_memcg(memcg);
  2384. else
  2385. objcg = NULL;
  2386. rcu_read_unlock();
  2387. }
  2388. return objcg;
  2389. }
  2390. #ifdef CONFIG_MEMCG_NMI_SAFETY_REQUIRES_ATOMIC
  2391. static inline void account_kmem_nmi_safe(struct mem_cgroup *memcg, int val)
  2392. {
  2393. if (likely(!in_nmi())) {
  2394. mod_memcg_state(memcg, MEMCG_KMEM, val);
  2395. } else {
  2396. /* preemption is disabled in_nmi(). */
  2397. css_rstat_updated(&memcg->css, smp_processor_id());
  2398. atomic_add(val, &memcg->kmem_stat);
  2399. }
  2400. }
  2401. #else
  2402. static inline void account_kmem_nmi_safe(struct mem_cgroup *memcg, int val)
  2403. {
  2404. mod_memcg_state(memcg, MEMCG_KMEM, val);
  2405. }
  2406. #endif
  2407. /*
  2408. * obj_cgroup_uncharge_pages: uncharge a number of kernel pages from a objcg
  2409. * @objcg: object cgroup to uncharge
  2410. * @nr_pages: number of pages to uncharge
  2411. */
  2412. static void obj_cgroup_uncharge_pages(struct obj_cgroup *objcg,
  2413. unsigned int nr_pages)
  2414. {
  2415. struct mem_cgroup *memcg;
  2416. memcg = get_mem_cgroup_from_objcg(objcg);
  2417. account_kmem_nmi_safe(memcg, -nr_pages);
  2418. memcg1_account_kmem(memcg, -nr_pages);
  2419. if (!mem_cgroup_is_root(memcg))
  2420. refill_stock(memcg, nr_pages);
  2421. css_put(&memcg->css);
  2422. }
  2423. /*
  2424. * obj_cgroup_charge_pages: charge a number of kernel pages to a objcg
  2425. * @objcg: object cgroup to charge
  2426. * @gfp: reclaim mode
  2427. * @nr_pages: number of pages to charge
  2428. *
  2429. * Returns 0 on success, an error code on failure.
  2430. */
  2431. static int obj_cgroup_charge_pages(struct obj_cgroup *objcg, gfp_t gfp,
  2432. unsigned int nr_pages)
  2433. {
  2434. struct mem_cgroup *memcg;
  2435. int ret;
  2436. memcg = get_mem_cgroup_from_objcg(objcg);
  2437. ret = try_charge_memcg(memcg, gfp, nr_pages);
  2438. if (ret)
  2439. goto out;
  2440. account_kmem_nmi_safe(memcg, nr_pages);
  2441. memcg1_account_kmem(memcg, nr_pages);
  2442. out:
  2443. css_put(&memcg->css);
  2444. return ret;
  2445. }
  2446. static struct obj_cgroup *page_objcg(const struct page *page)
  2447. {
  2448. unsigned long memcg_data = page->memcg_data;
  2449. if (mem_cgroup_disabled() || !memcg_data)
  2450. return NULL;
  2451. VM_BUG_ON_PAGE((memcg_data & OBJEXTS_FLAGS_MASK) != MEMCG_DATA_KMEM,
  2452. page);
  2453. return (struct obj_cgroup *)(memcg_data - MEMCG_DATA_KMEM);
  2454. }
  2455. static void page_set_objcg(struct page *page, const struct obj_cgroup *objcg)
  2456. {
  2457. page->memcg_data = (unsigned long)objcg | MEMCG_DATA_KMEM;
  2458. }
  2459. /**
  2460. * __memcg_kmem_charge_page: charge a kmem page to the current memory cgroup
  2461. * @page: page to charge
  2462. * @gfp: reclaim mode
  2463. * @order: allocation order
  2464. *
  2465. * Returns 0 on success, an error code on failure.
  2466. */
  2467. int __memcg_kmem_charge_page(struct page *page, gfp_t gfp, int order)
  2468. {
  2469. struct obj_cgroup *objcg;
  2470. int ret = 0;
  2471. objcg = current_obj_cgroup();
  2472. if (objcg) {
  2473. ret = obj_cgroup_charge_pages(objcg, gfp, 1 << order);
  2474. if (!ret) {
  2475. obj_cgroup_get(objcg);
  2476. page_set_objcg(page, objcg);
  2477. return 0;
  2478. }
  2479. }
  2480. return ret;
  2481. }
  2482. /**
  2483. * __memcg_kmem_uncharge_page: uncharge a kmem page
  2484. * @page: page to uncharge
  2485. * @order: allocation order
  2486. */
  2487. void __memcg_kmem_uncharge_page(struct page *page, int order)
  2488. {
  2489. struct obj_cgroup *objcg = page_objcg(page);
  2490. unsigned int nr_pages = 1 << order;
  2491. if (!objcg)
  2492. return;
  2493. obj_cgroup_uncharge_pages(objcg, nr_pages);
  2494. page->memcg_data = 0;
  2495. obj_cgroup_put(objcg);
  2496. }
  2497. static void __account_obj_stock(struct obj_cgroup *objcg,
  2498. struct obj_stock_pcp *stock, int nr,
  2499. struct pglist_data *pgdat, enum node_stat_item idx)
  2500. {
  2501. int *bytes;
  2502. /*
  2503. * Save vmstat data in stock and skip vmstat array update unless
  2504. * accumulating over a page of vmstat data or when pgdat changes.
  2505. */
  2506. if (stock->cached_pgdat != pgdat) {
  2507. /* Flush the existing cached vmstat data */
  2508. struct pglist_data *oldpg = stock->cached_pgdat;
  2509. if (stock->nr_slab_reclaimable_b) {
  2510. mod_objcg_mlstate(objcg, oldpg, NR_SLAB_RECLAIMABLE_B,
  2511. stock->nr_slab_reclaimable_b);
  2512. stock->nr_slab_reclaimable_b = 0;
  2513. }
  2514. if (stock->nr_slab_unreclaimable_b) {
  2515. mod_objcg_mlstate(objcg, oldpg, NR_SLAB_UNRECLAIMABLE_B,
  2516. stock->nr_slab_unreclaimable_b);
  2517. stock->nr_slab_unreclaimable_b = 0;
  2518. }
  2519. stock->cached_pgdat = pgdat;
  2520. }
  2521. bytes = (idx == NR_SLAB_RECLAIMABLE_B) ? &stock->nr_slab_reclaimable_b
  2522. : &stock->nr_slab_unreclaimable_b;
  2523. /*
  2524. * Even for large object >= PAGE_SIZE, the vmstat data will still be
  2525. * cached locally at least once before pushing it out.
  2526. */
  2527. if (!*bytes) {
  2528. *bytes = nr;
  2529. nr = 0;
  2530. } else {
  2531. *bytes += nr;
  2532. if (abs(*bytes) > PAGE_SIZE) {
  2533. nr = *bytes;
  2534. *bytes = 0;
  2535. } else {
  2536. nr = 0;
  2537. }
  2538. }
  2539. if (nr)
  2540. mod_objcg_mlstate(objcg, pgdat, idx, nr);
  2541. }
  2542. static bool consume_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes,
  2543. struct pglist_data *pgdat, enum node_stat_item idx)
  2544. {
  2545. struct obj_stock_pcp *stock;
  2546. bool ret = false;
  2547. if (!local_trylock(&obj_stock.lock))
  2548. return ret;
  2549. stock = this_cpu_ptr(&obj_stock);
  2550. if (objcg == READ_ONCE(stock->cached_objcg) && stock->nr_bytes >= nr_bytes) {
  2551. stock->nr_bytes -= nr_bytes;
  2552. ret = true;
  2553. if (pgdat)
  2554. __account_obj_stock(objcg, stock, nr_bytes, pgdat, idx);
  2555. }
  2556. local_unlock(&obj_stock.lock);
  2557. return ret;
  2558. }
  2559. static void drain_obj_stock(struct obj_stock_pcp *stock)
  2560. {
  2561. struct obj_cgroup *old = READ_ONCE(stock->cached_objcg);
  2562. if (!old)
  2563. return;
  2564. if (stock->nr_bytes) {
  2565. unsigned int nr_pages = stock->nr_bytes >> PAGE_SHIFT;
  2566. unsigned int nr_bytes = stock->nr_bytes & (PAGE_SIZE - 1);
  2567. if (nr_pages) {
  2568. struct mem_cgroup *memcg;
  2569. memcg = get_mem_cgroup_from_objcg(old);
  2570. mod_memcg_state(memcg, MEMCG_KMEM, -nr_pages);
  2571. memcg1_account_kmem(memcg, -nr_pages);
  2572. if (!mem_cgroup_is_root(memcg))
  2573. memcg_uncharge(memcg, nr_pages);
  2574. css_put(&memcg->css);
  2575. }
  2576. /*
  2577. * The leftover is flushed to the centralized per-memcg value.
  2578. * On the next attempt to refill obj stock it will be moved
  2579. * to a per-cpu stock (probably, on an other CPU), see
  2580. * refill_obj_stock().
  2581. *
  2582. * How often it's flushed is a trade-off between the memory
  2583. * limit enforcement accuracy and potential CPU contention,
  2584. * so it might be changed in the future.
  2585. */
  2586. atomic_add(nr_bytes, &old->nr_charged_bytes);
  2587. stock->nr_bytes = 0;
  2588. }
  2589. /*
  2590. * Flush the vmstat data in current stock
  2591. */
  2592. if (stock->nr_slab_reclaimable_b || stock->nr_slab_unreclaimable_b) {
  2593. if (stock->nr_slab_reclaimable_b) {
  2594. mod_objcg_mlstate(old, stock->cached_pgdat,
  2595. NR_SLAB_RECLAIMABLE_B,
  2596. stock->nr_slab_reclaimable_b);
  2597. stock->nr_slab_reclaimable_b = 0;
  2598. }
  2599. if (stock->nr_slab_unreclaimable_b) {
  2600. mod_objcg_mlstate(old, stock->cached_pgdat,
  2601. NR_SLAB_UNRECLAIMABLE_B,
  2602. stock->nr_slab_unreclaimable_b);
  2603. stock->nr_slab_unreclaimable_b = 0;
  2604. }
  2605. stock->cached_pgdat = NULL;
  2606. }
  2607. WRITE_ONCE(stock->cached_objcg, NULL);
  2608. obj_cgroup_put(old);
  2609. }
  2610. static bool obj_stock_flush_required(struct obj_stock_pcp *stock,
  2611. struct mem_cgroup *root_memcg)
  2612. {
  2613. struct obj_cgroup *objcg = READ_ONCE(stock->cached_objcg);
  2614. struct mem_cgroup *memcg;
  2615. bool flush = false;
  2616. rcu_read_lock();
  2617. if (objcg) {
  2618. memcg = obj_cgroup_memcg(objcg);
  2619. if (memcg && mem_cgroup_is_descendant(memcg, root_memcg))
  2620. flush = true;
  2621. }
  2622. rcu_read_unlock();
  2623. return flush;
  2624. }
  2625. static void refill_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes,
  2626. bool allow_uncharge, int nr_acct, struct pglist_data *pgdat,
  2627. enum node_stat_item idx)
  2628. {
  2629. struct obj_stock_pcp *stock;
  2630. unsigned int nr_pages = 0;
  2631. if (!local_trylock(&obj_stock.lock)) {
  2632. if (pgdat)
  2633. mod_objcg_mlstate(objcg, pgdat, idx, nr_acct);
  2634. nr_pages = nr_bytes >> PAGE_SHIFT;
  2635. nr_bytes = nr_bytes & (PAGE_SIZE - 1);
  2636. atomic_add(nr_bytes, &objcg->nr_charged_bytes);
  2637. goto out;
  2638. }
  2639. stock = this_cpu_ptr(&obj_stock);
  2640. if (READ_ONCE(stock->cached_objcg) != objcg) { /* reset if necessary */
  2641. drain_obj_stock(stock);
  2642. obj_cgroup_get(objcg);
  2643. stock->nr_bytes = atomic_read(&objcg->nr_charged_bytes)
  2644. ? atomic_xchg(&objcg->nr_charged_bytes, 0) : 0;
  2645. WRITE_ONCE(stock->cached_objcg, objcg);
  2646. allow_uncharge = true; /* Allow uncharge when objcg changes */
  2647. }
  2648. stock->nr_bytes += nr_bytes;
  2649. if (pgdat)
  2650. __account_obj_stock(objcg, stock, nr_acct, pgdat, idx);
  2651. if (allow_uncharge && (stock->nr_bytes > PAGE_SIZE)) {
  2652. nr_pages = stock->nr_bytes >> PAGE_SHIFT;
  2653. stock->nr_bytes &= (PAGE_SIZE - 1);
  2654. }
  2655. local_unlock(&obj_stock.lock);
  2656. out:
  2657. if (nr_pages)
  2658. obj_cgroup_uncharge_pages(objcg, nr_pages);
  2659. }
  2660. static int obj_cgroup_charge_account(struct obj_cgroup *objcg, gfp_t gfp, size_t size,
  2661. struct pglist_data *pgdat, enum node_stat_item idx)
  2662. {
  2663. unsigned int nr_pages, nr_bytes;
  2664. int ret;
  2665. if (likely(consume_obj_stock(objcg, size, pgdat, idx)))
  2666. return 0;
  2667. /*
  2668. * In theory, objcg->nr_charged_bytes can have enough
  2669. * pre-charged bytes to satisfy the allocation. However,
  2670. * flushing objcg->nr_charged_bytes requires two atomic
  2671. * operations, and objcg->nr_charged_bytes can't be big.
  2672. * The shared objcg->nr_charged_bytes can also become a
  2673. * performance bottleneck if all tasks of the same memcg are
  2674. * trying to update it. So it's better to ignore it and try
  2675. * grab some new pages. The stock's nr_bytes will be flushed to
  2676. * objcg->nr_charged_bytes later on when objcg changes.
  2677. *
  2678. * The stock's nr_bytes may contain enough pre-charged bytes
  2679. * to allow one less page from being charged, but we can't rely
  2680. * on the pre-charged bytes not being changed outside of
  2681. * consume_obj_stock() or refill_obj_stock(). So ignore those
  2682. * pre-charged bytes as well when charging pages. To avoid a
  2683. * page uncharge right after a page charge, we set the
  2684. * allow_uncharge flag to false when calling refill_obj_stock()
  2685. * to temporarily allow the pre-charged bytes to exceed the page
  2686. * size limit. The maximum reachable value of the pre-charged
  2687. * bytes is (sizeof(object) + PAGE_SIZE - 2) if there is no data
  2688. * race.
  2689. */
  2690. nr_pages = size >> PAGE_SHIFT;
  2691. nr_bytes = size & (PAGE_SIZE - 1);
  2692. if (nr_bytes)
  2693. nr_pages += 1;
  2694. ret = obj_cgroup_charge_pages(objcg, gfp, nr_pages);
  2695. if (!ret && (nr_bytes || pgdat))
  2696. refill_obj_stock(objcg, nr_bytes ? PAGE_SIZE - nr_bytes : 0,
  2697. false, size, pgdat, idx);
  2698. return ret;
  2699. }
  2700. int obj_cgroup_charge(struct obj_cgroup *objcg, gfp_t gfp, size_t size)
  2701. {
  2702. return obj_cgroup_charge_account(objcg, gfp, size, NULL, 0);
  2703. }
  2704. void obj_cgroup_uncharge(struct obj_cgroup *objcg, size_t size)
  2705. {
  2706. refill_obj_stock(objcg, size, true, 0, NULL, 0);
  2707. }
  2708. static inline size_t obj_full_size(struct kmem_cache *s)
  2709. {
  2710. /*
  2711. * For each accounted object there is an extra space which is used
  2712. * to store obj_cgroup membership. Charge it too.
  2713. */
  2714. return s->size + sizeof(struct obj_cgroup *);
  2715. }
  2716. bool __memcg_slab_post_alloc_hook(struct kmem_cache *s, struct list_lru *lru,
  2717. gfp_t flags, size_t size, void **p)
  2718. {
  2719. struct obj_cgroup *objcg;
  2720. struct slab *slab;
  2721. unsigned long off;
  2722. size_t i;
  2723. /*
  2724. * The obtained objcg pointer is safe to use within the current scope,
  2725. * defined by current task or set_active_memcg() pair.
  2726. * obj_cgroup_get() is used to get a permanent reference.
  2727. */
  2728. objcg = current_obj_cgroup();
  2729. if (!objcg)
  2730. return true;
  2731. /*
  2732. * slab_alloc_node() avoids the NULL check, so we might be called with a
  2733. * single NULL object. kmem_cache_alloc_bulk() aborts if it can't fill
  2734. * the whole requested size.
  2735. * return success as there's nothing to free back
  2736. */
  2737. if (unlikely(*p == NULL))
  2738. return true;
  2739. flags &= gfp_allowed_mask;
  2740. if (lru) {
  2741. int ret;
  2742. struct mem_cgroup *memcg;
  2743. memcg = get_mem_cgroup_from_objcg(objcg);
  2744. ret = memcg_list_lru_alloc(memcg, lru, flags);
  2745. css_put(&memcg->css);
  2746. if (ret)
  2747. return false;
  2748. }
  2749. for (i = 0; i < size; i++) {
  2750. unsigned long obj_exts;
  2751. struct slabobj_ext *obj_ext;
  2752. slab = virt_to_slab(p[i]);
  2753. if (!slab_obj_exts(slab) &&
  2754. alloc_slab_obj_exts(slab, s, flags, false)) {
  2755. continue;
  2756. }
  2757. /*
  2758. * if we fail and size is 1, memcg_alloc_abort_single() will
  2759. * just free the object, which is ok as we have not assigned
  2760. * objcg to its obj_ext yet
  2761. *
  2762. * for larger sizes, kmem_cache_free_bulk() will uncharge
  2763. * any objects that were already charged and obj_ext assigned
  2764. *
  2765. * TODO: we could batch this until slab_pgdat(slab) changes
  2766. * between iterations, with a more complicated undo
  2767. */
  2768. if (obj_cgroup_charge_account(objcg, flags, obj_full_size(s),
  2769. slab_pgdat(slab), cache_vmstat_idx(s)))
  2770. return false;
  2771. obj_exts = slab_obj_exts(slab);
  2772. get_slab_obj_exts(obj_exts);
  2773. off = obj_to_index(s, slab, p[i]);
  2774. obj_ext = slab_obj_ext(slab, obj_exts, off);
  2775. obj_cgroup_get(objcg);
  2776. obj_ext->objcg = objcg;
  2777. put_slab_obj_exts(obj_exts);
  2778. }
  2779. return true;
  2780. }
  2781. void __memcg_slab_free_hook(struct kmem_cache *s, struct slab *slab,
  2782. void **p, int objects, unsigned long obj_exts)
  2783. {
  2784. size_t obj_size = obj_full_size(s);
  2785. for (int i = 0; i < objects; i++) {
  2786. struct obj_cgroup *objcg;
  2787. struct slabobj_ext *obj_ext;
  2788. unsigned int off;
  2789. off = obj_to_index(s, slab, p[i]);
  2790. obj_ext = slab_obj_ext(slab, obj_exts, off);
  2791. objcg = obj_ext->objcg;
  2792. if (!objcg)
  2793. continue;
  2794. obj_ext->objcg = NULL;
  2795. refill_obj_stock(objcg, obj_size, true, -obj_size,
  2796. slab_pgdat(slab), cache_vmstat_idx(s));
  2797. obj_cgroup_put(objcg);
  2798. }
  2799. }
  2800. /*
  2801. * The objcg is only set on the first page, so transfer it to all the
  2802. * other pages.
  2803. */
  2804. void split_page_memcg(struct page *page, unsigned order)
  2805. {
  2806. struct obj_cgroup *objcg = page_objcg(page);
  2807. unsigned int i, nr = 1 << order;
  2808. if (!objcg)
  2809. return;
  2810. for (i = 1; i < nr; i++)
  2811. page_set_objcg(&page[i], objcg);
  2812. obj_cgroup_get_many(objcg, nr - 1);
  2813. }
  2814. void folio_split_memcg_refs(struct folio *folio, unsigned old_order,
  2815. unsigned new_order)
  2816. {
  2817. unsigned new_refs;
  2818. if (mem_cgroup_disabled() || !folio_memcg_charged(folio))
  2819. return;
  2820. new_refs = (1 << (old_order - new_order)) - 1;
  2821. css_get_many(&__folio_memcg(folio)->css, new_refs);
  2822. }
  2823. static int memcg_online_kmem(struct mem_cgroup *memcg)
  2824. {
  2825. struct obj_cgroup *objcg;
  2826. if (mem_cgroup_kmem_disabled())
  2827. return 0;
  2828. if (unlikely(mem_cgroup_is_root(memcg)))
  2829. return 0;
  2830. objcg = obj_cgroup_alloc();
  2831. if (!objcg)
  2832. return -ENOMEM;
  2833. objcg->memcg = memcg;
  2834. rcu_assign_pointer(memcg->objcg, objcg);
  2835. obj_cgroup_get(objcg);
  2836. memcg->orig_objcg = objcg;
  2837. static_branch_enable(&memcg_kmem_online_key);
  2838. memcg->kmemcg_id = memcg->id.id;
  2839. return 0;
  2840. }
  2841. static void memcg_offline_kmem(struct mem_cgroup *memcg)
  2842. {
  2843. struct mem_cgroup *parent;
  2844. if (mem_cgroup_kmem_disabled())
  2845. return;
  2846. if (unlikely(mem_cgroup_is_root(memcg)))
  2847. return;
  2848. parent = parent_mem_cgroup(memcg);
  2849. if (!parent)
  2850. parent = root_mem_cgroup;
  2851. memcg_reparent_list_lrus(memcg, parent);
  2852. /*
  2853. * Objcg's reparenting must be after list_lru's, make sure list_lru
  2854. * helpers won't use parent's list_lru until child is drained.
  2855. */
  2856. memcg_reparent_objcgs(memcg, parent);
  2857. }
  2858. #ifdef CONFIG_CGROUP_WRITEBACK
  2859. #include <trace/events/writeback.h>
  2860. static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
  2861. {
  2862. return wb_domain_init(&memcg->cgwb_domain, gfp);
  2863. }
  2864. static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
  2865. {
  2866. wb_domain_exit(&memcg->cgwb_domain);
  2867. }
  2868. static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
  2869. {
  2870. wb_domain_size_changed(&memcg->cgwb_domain);
  2871. }
  2872. struct wb_domain *mem_cgroup_wb_domain(struct bdi_writeback *wb)
  2873. {
  2874. struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
  2875. if (!memcg->css.parent)
  2876. return NULL;
  2877. return &memcg->cgwb_domain;
  2878. }
  2879. /**
  2880. * mem_cgroup_wb_stats - retrieve writeback related stats from its memcg
  2881. * @wb: bdi_writeback in question
  2882. * @pfilepages: out parameter for number of file pages
  2883. * @pheadroom: out parameter for number of allocatable pages according to memcg
  2884. * @pdirty: out parameter for number of dirty pages
  2885. * @pwriteback: out parameter for number of pages under writeback
  2886. *
  2887. * Determine the numbers of file, headroom, dirty, and writeback pages in
  2888. * @wb's memcg. File, dirty and writeback are self-explanatory. Headroom
  2889. * is a bit more involved.
  2890. *
  2891. * A memcg's headroom is "min(max, high) - used". In the hierarchy, the
  2892. * headroom is calculated as the lowest headroom of itself and the
  2893. * ancestors. Note that this doesn't consider the actual amount of
  2894. * available memory in the system. The caller should further cap
  2895. * *@pheadroom accordingly.
  2896. */
  2897. void mem_cgroup_wb_stats(struct bdi_writeback *wb, unsigned long *pfilepages,
  2898. unsigned long *pheadroom, unsigned long *pdirty,
  2899. unsigned long *pwriteback)
  2900. {
  2901. struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
  2902. struct mem_cgroup *parent;
  2903. mem_cgroup_flush_stats_ratelimited(memcg);
  2904. *pdirty = memcg_page_state(memcg, NR_FILE_DIRTY);
  2905. *pwriteback = memcg_page_state(memcg, NR_WRITEBACK);
  2906. *pfilepages = memcg_page_state(memcg, NR_INACTIVE_FILE) +
  2907. memcg_page_state(memcg, NR_ACTIVE_FILE);
  2908. *pheadroom = PAGE_COUNTER_MAX;
  2909. while ((parent = parent_mem_cgroup(memcg))) {
  2910. unsigned long ceiling = min(READ_ONCE(memcg->memory.max),
  2911. READ_ONCE(memcg->memory.high));
  2912. unsigned long used = page_counter_read(&memcg->memory);
  2913. *pheadroom = min(*pheadroom, ceiling - min(ceiling, used));
  2914. memcg = parent;
  2915. }
  2916. }
  2917. /*
  2918. * Foreign dirty flushing
  2919. *
  2920. * There's an inherent mismatch between memcg and writeback. The former
  2921. * tracks ownership per-page while the latter per-inode. This was a
  2922. * deliberate design decision because honoring per-page ownership in the
  2923. * writeback path is complicated, may lead to higher CPU and IO overheads
  2924. * and deemed unnecessary given that write-sharing an inode across
  2925. * different cgroups isn't a common use-case.
  2926. *
  2927. * Combined with inode majority-writer ownership switching, this works well
  2928. * enough in most cases but there are some pathological cases. For
  2929. * example, let's say there are two cgroups A and B which keep writing to
  2930. * different but confined parts of the same inode. B owns the inode and
  2931. * A's memory is limited far below B's. A's dirty ratio can rise enough to
  2932. * trigger balance_dirty_pages() sleeps but B's can be low enough to avoid
  2933. * triggering background writeback. A will be slowed down without a way to
  2934. * make writeback of the dirty pages happen.
  2935. *
  2936. * Conditions like the above can lead to a cgroup getting repeatedly and
  2937. * severely throttled after making some progress after each
  2938. * dirty_expire_interval while the underlying IO device is almost
  2939. * completely idle.
  2940. *
  2941. * Solving this problem completely requires matching the ownership tracking
  2942. * granularities between memcg and writeback in either direction. However,
  2943. * the more egregious behaviors can be avoided by simply remembering the
  2944. * most recent foreign dirtying events and initiating remote flushes on
  2945. * them when local writeback isn't enough to keep the memory clean enough.
  2946. *
  2947. * The following two functions implement such mechanism. When a foreign
  2948. * page - a page whose memcg and writeback ownerships don't match - is
  2949. * dirtied, mem_cgroup_track_foreign_dirty() records the inode owning
  2950. * bdi_writeback on the page owning memcg. When balance_dirty_pages()
  2951. * decides that the memcg needs to sleep due to high dirty ratio, it calls
  2952. * mem_cgroup_flush_foreign() which queues writeback on the recorded
  2953. * foreign bdi_writebacks which haven't expired. Both the numbers of
  2954. * recorded bdi_writebacks and concurrent in-flight foreign writebacks are
  2955. * limited to MEMCG_CGWB_FRN_CNT.
  2956. *
  2957. * The mechanism only remembers IDs and doesn't hold any object references.
  2958. * As being wrong occasionally doesn't matter, updates and accesses to the
  2959. * records are lockless and racy.
  2960. */
  2961. void mem_cgroup_track_foreign_dirty_slowpath(struct folio *folio,
  2962. struct bdi_writeback *wb)
  2963. {
  2964. struct mem_cgroup *memcg = folio_memcg(folio);
  2965. struct memcg_cgwb_frn *frn;
  2966. u64 now = get_jiffies_64();
  2967. u64 oldest_at = now;
  2968. int oldest = -1;
  2969. int i;
  2970. trace_track_foreign_dirty(folio, wb);
  2971. /*
  2972. * Pick the slot to use. If there is already a slot for @wb, keep
  2973. * using it. If not replace the oldest one which isn't being
  2974. * written out.
  2975. */
  2976. for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
  2977. frn = &memcg->cgwb_frn[i];
  2978. if (frn->bdi_id == wb->bdi->id &&
  2979. frn->memcg_id == wb->memcg_css->id)
  2980. break;
  2981. if (time_before64(frn->at, oldest_at) &&
  2982. atomic_read(&frn->done.cnt) == 1) {
  2983. oldest = i;
  2984. oldest_at = frn->at;
  2985. }
  2986. }
  2987. if (i < MEMCG_CGWB_FRN_CNT) {
  2988. /*
  2989. * Re-using an existing one. Update timestamp lazily to
  2990. * avoid making the cacheline hot. We want them to be
  2991. * reasonably up-to-date and significantly shorter than
  2992. * dirty_expire_interval as that's what expires the record.
  2993. * Use the shorter of 1s and dirty_expire_interval / 8.
  2994. */
  2995. unsigned long update_intv =
  2996. min_t(unsigned long, HZ,
  2997. msecs_to_jiffies(dirty_expire_interval * 10) / 8);
  2998. if (time_before64(frn->at, now - update_intv))
  2999. frn->at = now;
  3000. } else if (oldest >= 0) {
  3001. /* replace the oldest free one */
  3002. frn = &memcg->cgwb_frn[oldest];
  3003. frn->bdi_id = wb->bdi->id;
  3004. frn->memcg_id = wb->memcg_css->id;
  3005. frn->at = now;
  3006. }
  3007. }
  3008. /* issue foreign writeback flushes for recorded foreign dirtying events */
  3009. void mem_cgroup_flush_foreign(struct bdi_writeback *wb)
  3010. {
  3011. struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
  3012. unsigned long intv = msecs_to_jiffies(dirty_expire_interval * 10);
  3013. u64 now = jiffies_64;
  3014. int i;
  3015. for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
  3016. struct memcg_cgwb_frn *frn = &memcg->cgwb_frn[i];
  3017. /*
  3018. * If the record is older than dirty_expire_interval,
  3019. * writeback on it has already started. No need to kick it
  3020. * off again. Also, don't start a new one if there's
  3021. * already one in flight.
  3022. */
  3023. if (time_after64(frn->at, now - intv) &&
  3024. atomic_read(&frn->done.cnt) == 1) {
  3025. frn->at = 0;
  3026. trace_flush_foreign(wb, frn->bdi_id, frn->memcg_id);
  3027. cgroup_writeback_by_id(frn->bdi_id, frn->memcg_id,
  3028. WB_REASON_FOREIGN_FLUSH,
  3029. &frn->done);
  3030. }
  3031. }
  3032. }
  3033. #else /* CONFIG_CGROUP_WRITEBACK */
  3034. static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
  3035. {
  3036. return 0;
  3037. }
  3038. static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
  3039. {
  3040. }
  3041. static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
  3042. {
  3043. }
  3044. #endif /* CONFIG_CGROUP_WRITEBACK */
  3045. /*
  3046. * Private memory cgroup IDR
  3047. *
  3048. * Swap-out records and page cache shadow entries need to store memcg
  3049. * references in constrained space, so we maintain an ID space that is
  3050. * limited to 16 bit (MEM_CGROUP_ID_MAX), limiting the total number of
  3051. * memory-controlled cgroups to 64k.
  3052. *
  3053. * However, there usually are many references to the offline CSS after
  3054. * the cgroup has been destroyed, such as page cache or reclaimable
  3055. * slab objects, that don't need to hang on to the ID. We want to keep
  3056. * those dead CSS from occupying IDs, or we might quickly exhaust the
  3057. * relatively small ID space and prevent the creation of new cgroups
  3058. * even when there are much fewer than 64k cgroups - possibly none.
  3059. *
  3060. * Maintain a private 16-bit ID space for memcg, and allow the ID to
  3061. * be freed and recycled when it's no longer needed, which is usually
  3062. * when the CSS is offlined.
  3063. *
  3064. * The only exception to that are records of swapped out tmpfs/shmem
  3065. * pages that need to be attributed to live ancestors on swapin. But
  3066. * those references are manageable from userspace.
  3067. */
  3068. #define MEM_CGROUP_ID_MAX ((1UL << MEM_CGROUP_ID_SHIFT) - 1)
  3069. static DEFINE_XARRAY_ALLOC1(mem_cgroup_private_ids);
  3070. static void mem_cgroup_private_id_remove(struct mem_cgroup *memcg)
  3071. {
  3072. if (memcg->id.id > 0) {
  3073. xa_erase(&mem_cgroup_private_ids, memcg->id.id);
  3074. memcg->id.id = 0;
  3075. }
  3076. }
  3077. void __maybe_unused mem_cgroup_private_id_get_many(struct mem_cgroup *memcg,
  3078. unsigned int n)
  3079. {
  3080. refcount_add(n, &memcg->id.ref);
  3081. }
  3082. static void mem_cgroup_private_id_put_many(struct mem_cgroup *memcg, unsigned int n)
  3083. {
  3084. if (refcount_sub_and_test(n, &memcg->id.ref)) {
  3085. mem_cgroup_private_id_remove(memcg);
  3086. /* Memcg ID pins CSS */
  3087. css_put(&memcg->css);
  3088. }
  3089. }
  3090. static inline void mem_cgroup_private_id_put(struct mem_cgroup *memcg)
  3091. {
  3092. mem_cgroup_private_id_put_many(memcg, 1);
  3093. }
  3094. struct mem_cgroup *mem_cgroup_private_id_get_online(struct mem_cgroup *memcg)
  3095. {
  3096. while (!refcount_inc_not_zero(&memcg->id.ref)) {
  3097. /*
  3098. * The root cgroup cannot be destroyed, so it's refcount must
  3099. * always be >= 1.
  3100. */
  3101. if (WARN_ON_ONCE(mem_cgroup_is_root(memcg))) {
  3102. VM_BUG_ON(1);
  3103. break;
  3104. }
  3105. memcg = parent_mem_cgroup(memcg);
  3106. if (!memcg)
  3107. memcg = root_mem_cgroup;
  3108. }
  3109. return memcg;
  3110. }
  3111. /**
  3112. * mem_cgroup_from_private_id - look up a memcg from a memcg id
  3113. * @id: the memcg id to look up
  3114. *
  3115. * Caller must hold rcu_read_lock().
  3116. */
  3117. struct mem_cgroup *mem_cgroup_from_private_id(unsigned short id)
  3118. {
  3119. WARN_ON_ONCE(!rcu_read_lock_held());
  3120. return xa_load(&mem_cgroup_private_ids, id);
  3121. }
  3122. struct mem_cgroup *mem_cgroup_get_from_id(u64 id)
  3123. {
  3124. struct cgroup *cgrp;
  3125. struct cgroup_subsys_state *css;
  3126. struct mem_cgroup *memcg = NULL;
  3127. cgrp = cgroup_get_from_id(id);
  3128. if (IS_ERR(cgrp))
  3129. return NULL;
  3130. css = cgroup_get_e_css(cgrp, &memory_cgrp_subsys);
  3131. if (css)
  3132. memcg = container_of(css, struct mem_cgroup, css);
  3133. cgroup_put(cgrp);
  3134. return memcg;
  3135. }
  3136. static void free_mem_cgroup_per_node_info(struct mem_cgroup_per_node *pn)
  3137. {
  3138. if (!pn)
  3139. return;
  3140. free_percpu(pn->lruvec_stats_percpu);
  3141. kfree(pn->lruvec_stats);
  3142. kfree(pn);
  3143. }
  3144. static bool alloc_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
  3145. {
  3146. struct mem_cgroup_per_node *pn;
  3147. pn = kmem_cache_alloc_node(memcg_pn_cachep, GFP_KERNEL | __GFP_ZERO,
  3148. node);
  3149. if (!pn)
  3150. return false;
  3151. pn->lruvec_stats = kzalloc_node(sizeof(struct lruvec_stats),
  3152. GFP_KERNEL_ACCOUNT, node);
  3153. if (!pn->lruvec_stats)
  3154. goto fail;
  3155. pn->lruvec_stats_percpu = alloc_percpu_gfp(struct lruvec_stats_percpu,
  3156. GFP_KERNEL_ACCOUNT);
  3157. if (!pn->lruvec_stats_percpu)
  3158. goto fail;
  3159. lruvec_init(&pn->lruvec);
  3160. pn->memcg = memcg;
  3161. memcg->nodeinfo[node] = pn;
  3162. return true;
  3163. fail:
  3164. free_mem_cgroup_per_node_info(pn);
  3165. return false;
  3166. }
  3167. static void __mem_cgroup_free(struct mem_cgroup *memcg)
  3168. {
  3169. int node;
  3170. obj_cgroup_put(memcg->orig_objcg);
  3171. for_each_node(node)
  3172. free_mem_cgroup_per_node_info(memcg->nodeinfo[node]);
  3173. memcg1_free_events(memcg);
  3174. kfree(memcg->vmstats);
  3175. free_percpu(memcg->vmstats_percpu);
  3176. kfree(memcg);
  3177. }
  3178. static void mem_cgroup_free(struct mem_cgroup *memcg)
  3179. {
  3180. lru_gen_exit_memcg(memcg);
  3181. memcg_wb_domain_exit(memcg);
  3182. __mem_cgroup_free(memcg);
  3183. }
  3184. static struct mem_cgroup *mem_cgroup_alloc(struct mem_cgroup *parent)
  3185. {
  3186. struct memcg_vmstats_percpu *statc;
  3187. struct memcg_vmstats_percpu __percpu *pstatc_pcpu;
  3188. struct mem_cgroup *memcg;
  3189. int node, cpu;
  3190. int __maybe_unused i;
  3191. long error;
  3192. memcg = kmem_cache_zalloc(memcg_cachep, GFP_KERNEL);
  3193. if (!memcg)
  3194. return ERR_PTR(-ENOMEM);
  3195. error = xa_alloc(&mem_cgroup_private_ids, &memcg->id.id, NULL,
  3196. XA_LIMIT(1, MEM_CGROUP_ID_MAX), GFP_KERNEL);
  3197. if (error)
  3198. goto fail;
  3199. error = -ENOMEM;
  3200. memcg->vmstats = kzalloc_obj(struct memcg_vmstats, GFP_KERNEL_ACCOUNT);
  3201. if (!memcg->vmstats)
  3202. goto fail;
  3203. memcg->vmstats_percpu = alloc_percpu_gfp(struct memcg_vmstats_percpu,
  3204. GFP_KERNEL_ACCOUNT);
  3205. if (!memcg->vmstats_percpu)
  3206. goto fail;
  3207. if (!memcg1_alloc_events(memcg))
  3208. goto fail;
  3209. for_each_possible_cpu(cpu) {
  3210. if (parent)
  3211. pstatc_pcpu = parent->vmstats_percpu;
  3212. statc = per_cpu_ptr(memcg->vmstats_percpu, cpu);
  3213. statc->parent_pcpu = parent ? pstatc_pcpu : NULL;
  3214. statc->vmstats = memcg->vmstats;
  3215. }
  3216. for_each_node(node)
  3217. if (!alloc_mem_cgroup_per_node_info(memcg, node))
  3218. goto fail;
  3219. if (memcg_wb_domain_init(memcg, GFP_KERNEL))
  3220. goto fail;
  3221. INIT_WORK(&memcg->high_work, high_work_func);
  3222. vmpressure_init(&memcg->vmpressure);
  3223. INIT_LIST_HEAD(&memcg->memory_peaks);
  3224. INIT_LIST_HEAD(&memcg->swap_peaks);
  3225. spin_lock_init(&memcg->peaks_lock);
  3226. memcg->socket_pressure = get_jiffies_64();
  3227. #if BITS_PER_LONG < 64
  3228. seqlock_init(&memcg->socket_pressure_seqlock);
  3229. #endif
  3230. memcg1_memcg_init(memcg);
  3231. memcg->kmemcg_id = -1;
  3232. INIT_LIST_HEAD(&memcg->objcg_list);
  3233. #ifdef CONFIG_CGROUP_WRITEBACK
  3234. INIT_LIST_HEAD(&memcg->cgwb_list);
  3235. for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
  3236. memcg->cgwb_frn[i].done =
  3237. __WB_COMPLETION_INIT(&memcg_cgwb_frn_waitq);
  3238. #endif
  3239. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  3240. spin_lock_init(&memcg->deferred_split_queue.split_queue_lock);
  3241. INIT_LIST_HEAD(&memcg->deferred_split_queue.split_queue);
  3242. memcg->deferred_split_queue.split_queue_len = 0;
  3243. #endif
  3244. lru_gen_init_memcg(memcg);
  3245. return memcg;
  3246. fail:
  3247. mem_cgroup_private_id_remove(memcg);
  3248. __mem_cgroup_free(memcg);
  3249. return ERR_PTR(error);
  3250. }
  3251. static struct cgroup_subsys_state * __ref
  3252. mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
  3253. {
  3254. struct mem_cgroup *parent = mem_cgroup_from_css(parent_css);
  3255. struct mem_cgroup *memcg, *old_memcg;
  3256. bool memcg_on_dfl = cgroup_subsys_on_dfl(memory_cgrp_subsys);
  3257. old_memcg = set_active_memcg(parent);
  3258. memcg = mem_cgroup_alloc(parent);
  3259. set_active_memcg(old_memcg);
  3260. if (IS_ERR(memcg))
  3261. return ERR_CAST(memcg);
  3262. page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
  3263. memcg1_soft_limit_reset(memcg);
  3264. #ifdef CONFIG_ZSWAP
  3265. memcg->zswap_max = PAGE_COUNTER_MAX;
  3266. WRITE_ONCE(memcg->zswap_writeback, true);
  3267. #endif
  3268. page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
  3269. if (parent) {
  3270. WRITE_ONCE(memcg->swappiness, mem_cgroup_swappiness(parent));
  3271. page_counter_init(&memcg->memory, &parent->memory, memcg_on_dfl);
  3272. page_counter_init(&memcg->swap, &parent->swap, false);
  3273. #ifdef CONFIG_MEMCG_V1
  3274. memcg->memory.track_failcnt = !memcg_on_dfl;
  3275. WRITE_ONCE(memcg->oom_kill_disable, READ_ONCE(parent->oom_kill_disable));
  3276. page_counter_init(&memcg->kmem, &parent->kmem, false);
  3277. page_counter_init(&memcg->tcpmem, &parent->tcpmem, false);
  3278. #endif
  3279. } else {
  3280. init_memcg_stats();
  3281. init_memcg_events();
  3282. page_counter_init(&memcg->memory, NULL, true);
  3283. page_counter_init(&memcg->swap, NULL, false);
  3284. #ifdef CONFIG_MEMCG_V1
  3285. page_counter_init(&memcg->kmem, NULL, false);
  3286. page_counter_init(&memcg->tcpmem, NULL, false);
  3287. #endif
  3288. root_mem_cgroup = memcg;
  3289. return &memcg->css;
  3290. }
  3291. if (memcg_on_dfl && !cgroup_memory_nosocket)
  3292. static_branch_inc(&memcg_sockets_enabled_key);
  3293. if (!cgroup_memory_nobpf)
  3294. static_branch_inc(&memcg_bpf_enabled_key);
  3295. return &memcg->css;
  3296. }
  3297. static int mem_cgroup_css_online(struct cgroup_subsys_state *css)
  3298. {
  3299. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3300. if (memcg_online_kmem(memcg))
  3301. goto remove_id;
  3302. /*
  3303. * A memcg must be visible for expand_shrinker_info()
  3304. * by the time the maps are allocated. So, we allocate maps
  3305. * here, when for_each_mem_cgroup() can't skip it.
  3306. */
  3307. if (alloc_shrinker_info(memcg))
  3308. goto offline_kmem;
  3309. if (unlikely(mem_cgroup_is_root(memcg)) && !mem_cgroup_disabled())
  3310. queue_delayed_work(system_dfl_wq, &stats_flush_dwork,
  3311. FLUSH_TIME);
  3312. lru_gen_online_memcg(memcg);
  3313. /* Online state pins memcg ID, memcg ID pins CSS */
  3314. refcount_set(&memcg->id.ref, 1);
  3315. css_get(css);
  3316. /*
  3317. * Ensure mem_cgroup_from_private_id() works once we're fully online.
  3318. *
  3319. * We could do this earlier and require callers to filter with
  3320. * css_tryget_online(). But right now there are no users that
  3321. * need earlier access, and the workingset code relies on the
  3322. * cgroup tree linkage (mem_cgroup_get_nr_swap_pages()). So
  3323. * publish it here at the end of onlining. This matches the
  3324. * regular ID destruction during offlining.
  3325. */
  3326. xa_store(&mem_cgroup_private_ids, memcg->id.id, memcg, GFP_KERNEL);
  3327. return 0;
  3328. offline_kmem:
  3329. memcg_offline_kmem(memcg);
  3330. remove_id:
  3331. mem_cgroup_private_id_remove(memcg);
  3332. return -ENOMEM;
  3333. }
  3334. static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
  3335. {
  3336. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3337. memcg1_css_offline(memcg);
  3338. page_counter_set_min(&memcg->memory, 0);
  3339. page_counter_set_low(&memcg->memory, 0);
  3340. zswap_memcg_offline_cleanup(memcg);
  3341. memcg_offline_kmem(memcg);
  3342. reparent_deferred_split_queue(memcg);
  3343. reparent_shrinker_deferred(memcg);
  3344. wb_memcg_offline(memcg);
  3345. lru_gen_offline_memcg(memcg);
  3346. drain_all_stock(memcg);
  3347. mem_cgroup_private_id_put(memcg);
  3348. }
  3349. static void mem_cgroup_css_released(struct cgroup_subsys_state *css)
  3350. {
  3351. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3352. invalidate_reclaim_iterators(memcg);
  3353. lru_gen_release_memcg(memcg);
  3354. }
  3355. static void mem_cgroup_css_free(struct cgroup_subsys_state *css)
  3356. {
  3357. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3358. int __maybe_unused i;
  3359. #ifdef CONFIG_CGROUP_WRITEBACK
  3360. for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
  3361. wb_wait_for_completion(&memcg->cgwb_frn[i].done);
  3362. #endif
  3363. if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
  3364. static_branch_dec(&memcg_sockets_enabled_key);
  3365. if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && memcg1_tcpmem_active(memcg))
  3366. static_branch_dec(&memcg_sockets_enabled_key);
  3367. if (!cgroup_memory_nobpf)
  3368. static_branch_dec(&memcg_bpf_enabled_key);
  3369. vmpressure_cleanup(&memcg->vmpressure);
  3370. cancel_work_sync(&memcg->high_work);
  3371. memcg1_remove_from_trees(memcg);
  3372. free_shrinker_info(memcg);
  3373. mem_cgroup_free(memcg);
  3374. }
  3375. /**
  3376. * mem_cgroup_css_reset - reset the states of a mem_cgroup
  3377. * @css: the target css
  3378. *
  3379. * Reset the states of the mem_cgroup associated with @css. This is
  3380. * invoked when the userland requests disabling on the default hierarchy
  3381. * but the memcg is pinned through dependency. The memcg should stop
  3382. * applying policies and should revert to the vanilla state as it may be
  3383. * made visible again.
  3384. *
  3385. * The current implementation only resets the essential configurations.
  3386. * This needs to be expanded to cover all the visible parts.
  3387. */
  3388. static void mem_cgroup_css_reset(struct cgroup_subsys_state *css)
  3389. {
  3390. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3391. page_counter_set_max(&memcg->memory, PAGE_COUNTER_MAX);
  3392. page_counter_set_max(&memcg->swap, PAGE_COUNTER_MAX);
  3393. #ifdef CONFIG_MEMCG_V1
  3394. page_counter_set_max(&memcg->kmem, PAGE_COUNTER_MAX);
  3395. page_counter_set_max(&memcg->tcpmem, PAGE_COUNTER_MAX);
  3396. #endif
  3397. page_counter_set_min(&memcg->memory, 0);
  3398. page_counter_set_low(&memcg->memory, 0);
  3399. page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
  3400. memcg1_soft_limit_reset(memcg);
  3401. page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
  3402. memcg_wb_domain_size_changed(memcg);
  3403. }
  3404. struct aggregate_control {
  3405. /* pointer to the aggregated (CPU and subtree aggregated) counters */
  3406. long *aggregate;
  3407. /* pointer to the non-hierarchichal (CPU aggregated) counters */
  3408. long *local;
  3409. /* pointer to the pending child counters during tree propagation */
  3410. long *pending;
  3411. /* pointer to the parent's pending counters, could be NULL */
  3412. long *ppending;
  3413. /* pointer to the percpu counters to be aggregated */
  3414. long *cstat;
  3415. /* pointer to the percpu counters of the last aggregation*/
  3416. long *cstat_prev;
  3417. /* size of the above counters */
  3418. int size;
  3419. };
  3420. static void mem_cgroup_stat_aggregate(struct aggregate_control *ac)
  3421. {
  3422. int i;
  3423. long delta, delta_cpu, v;
  3424. for (i = 0; i < ac->size; i++) {
  3425. /*
  3426. * Collect the aggregated propagation counts of groups
  3427. * below us. We're in a per-cpu loop here and this is
  3428. * a global counter, so the first cycle will get them.
  3429. */
  3430. delta = ac->pending[i];
  3431. if (delta)
  3432. ac->pending[i] = 0;
  3433. /* Add CPU changes on this level since the last flush */
  3434. delta_cpu = 0;
  3435. v = READ_ONCE(ac->cstat[i]);
  3436. if (v != ac->cstat_prev[i]) {
  3437. delta_cpu = v - ac->cstat_prev[i];
  3438. delta += delta_cpu;
  3439. ac->cstat_prev[i] = v;
  3440. }
  3441. /* Aggregate counts on this level and propagate upwards */
  3442. if (delta_cpu)
  3443. ac->local[i] += delta_cpu;
  3444. if (delta) {
  3445. ac->aggregate[i] += delta;
  3446. if (ac->ppending)
  3447. ac->ppending[i] += delta;
  3448. }
  3449. }
  3450. }
  3451. #ifdef CONFIG_MEMCG_NMI_SAFETY_REQUIRES_ATOMIC
  3452. static void flush_nmi_stats(struct mem_cgroup *memcg, struct mem_cgroup *parent,
  3453. int cpu)
  3454. {
  3455. int nid;
  3456. if (atomic_read(&memcg->kmem_stat)) {
  3457. int kmem = atomic_xchg(&memcg->kmem_stat, 0);
  3458. int index = memcg_stats_index(MEMCG_KMEM);
  3459. memcg->vmstats->state[index] += kmem;
  3460. if (parent)
  3461. parent->vmstats->state_pending[index] += kmem;
  3462. }
  3463. for_each_node_state(nid, N_MEMORY) {
  3464. struct mem_cgroup_per_node *pn = memcg->nodeinfo[nid];
  3465. struct lruvec_stats *lstats = pn->lruvec_stats;
  3466. struct lruvec_stats *plstats = NULL;
  3467. if (parent)
  3468. plstats = parent->nodeinfo[nid]->lruvec_stats;
  3469. if (atomic_read(&pn->slab_reclaimable)) {
  3470. int slab = atomic_xchg(&pn->slab_reclaimable, 0);
  3471. int index = memcg_stats_index(NR_SLAB_RECLAIMABLE_B);
  3472. lstats->state[index] += slab;
  3473. if (plstats)
  3474. plstats->state_pending[index] += slab;
  3475. }
  3476. if (atomic_read(&pn->slab_unreclaimable)) {
  3477. int slab = atomic_xchg(&pn->slab_unreclaimable, 0);
  3478. int index = memcg_stats_index(NR_SLAB_UNRECLAIMABLE_B);
  3479. lstats->state[index] += slab;
  3480. if (plstats)
  3481. plstats->state_pending[index] += slab;
  3482. }
  3483. }
  3484. }
  3485. #else
  3486. static void flush_nmi_stats(struct mem_cgroup *memcg, struct mem_cgroup *parent,
  3487. int cpu)
  3488. {}
  3489. #endif
  3490. static void mem_cgroup_css_rstat_flush(struct cgroup_subsys_state *css, int cpu)
  3491. {
  3492. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3493. struct mem_cgroup *parent = parent_mem_cgroup(memcg);
  3494. struct memcg_vmstats_percpu *statc;
  3495. struct aggregate_control ac;
  3496. int nid;
  3497. flush_nmi_stats(memcg, parent, cpu);
  3498. statc = per_cpu_ptr(memcg->vmstats_percpu, cpu);
  3499. ac = (struct aggregate_control) {
  3500. .aggregate = memcg->vmstats->state,
  3501. .local = memcg->vmstats->state_local,
  3502. .pending = memcg->vmstats->state_pending,
  3503. .ppending = parent ? parent->vmstats->state_pending : NULL,
  3504. .cstat = statc->state,
  3505. .cstat_prev = statc->state_prev,
  3506. .size = MEMCG_VMSTAT_SIZE,
  3507. };
  3508. mem_cgroup_stat_aggregate(&ac);
  3509. ac = (struct aggregate_control) {
  3510. .aggregate = memcg->vmstats->events,
  3511. .local = memcg->vmstats->events_local,
  3512. .pending = memcg->vmstats->events_pending,
  3513. .ppending = parent ? parent->vmstats->events_pending : NULL,
  3514. .cstat = statc->events,
  3515. .cstat_prev = statc->events_prev,
  3516. .size = NR_MEMCG_EVENTS,
  3517. };
  3518. mem_cgroup_stat_aggregate(&ac);
  3519. for_each_node_state(nid, N_MEMORY) {
  3520. struct mem_cgroup_per_node *pn = memcg->nodeinfo[nid];
  3521. struct lruvec_stats *lstats = pn->lruvec_stats;
  3522. struct lruvec_stats *plstats = NULL;
  3523. struct lruvec_stats_percpu *lstatc;
  3524. if (parent)
  3525. plstats = parent->nodeinfo[nid]->lruvec_stats;
  3526. lstatc = per_cpu_ptr(pn->lruvec_stats_percpu, cpu);
  3527. ac = (struct aggregate_control) {
  3528. .aggregate = lstats->state,
  3529. .local = lstats->state_local,
  3530. .pending = lstats->state_pending,
  3531. .ppending = plstats ? plstats->state_pending : NULL,
  3532. .cstat = lstatc->state,
  3533. .cstat_prev = lstatc->state_prev,
  3534. .size = NR_MEMCG_NODE_STAT_ITEMS,
  3535. };
  3536. mem_cgroup_stat_aggregate(&ac);
  3537. }
  3538. WRITE_ONCE(statc->stats_updates, 0);
  3539. /* We are in a per-cpu loop here, only do the atomic write once */
  3540. if (atomic_read(&memcg->vmstats->stats_updates))
  3541. atomic_set(&memcg->vmstats->stats_updates, 0);
  3542. }
  3543. static void mem_cgroup_fork(struct task_struct *task)
  3544. {
  3545. /*
  3546. * Set the update flag to cause task->objcg to be initialized lazily
  3547. * on the first allocation. It can be done without any synchronization
  3548. * because it's always performed on the current task, so does
  3549. * current_objcg_update().
  3550. */
  3551. task->objcg = (struct obj_cgroup *)CURRENT_OBJCG_UPDATE_FLAG;
  3552. }
  3553. static void mem_cgroup_exit(struct task_struct *task)
  3554. {
  3555. struct obj_cgroup *objcg = task->objcg;
  3556. objcg = (struct obj_cgroup *)
  3557. ((unsigned long)objcg & ~CURRENT_OBJCG_UPDATE_FLAG);
  3558. obj_cgroup_put(objcg);
  3559. /*
  3560. * Some kernel allocations can happen after this point,
  3561. * but let's ignore them. It can be done without any synchronization
  3562. * because it's always performed on the current task, so does
  3563. * current_objcg_update().
  3564. */
  3565. task->objcg = NULL;
  3566. }
  3567. #ifdef CONFIG_LRU_GEN
  3568. static void mem_cgroup_lru_gen_attach(struct cgroup_taskset *tset)
  3569. {
  3570. struct task_struct *task;
  3571. struct cgroup_subsys_state *css;
  3572. /* find the first leader if there is any */
  3573. cgroup_taskset_for_each_leader(task, css, tset)
  3574. break;
  3575. if (!task)
  3576. return;
  3577. task_lock(task);
  3578. if (task->mm && READ_ONCE(task->mm->owner) == task)
  3579. lru_gen_migrate_mm(task->mm);
  3580. task_unlock(task);
  3581. }
  3582. #else
  3583. static void mem_cgroup_lru_gen_attach(struct cgroup_taskset *tset) {}
  3584. #endif /* CONFIG_LRU_GEN */
  3585. static void mem_cgroup_kmem_attach(struct cgroup_taskset *tset)
  3586. {
  3587. struct task_struct *task;
  3588. struct cgroup_subsys_state *css;
  3589. cgroup_taskset_for_each(task, css, tset) {
  3590. /* atomically set the update bit */
  3591. set_bit(CURRENT_OBJCG_UPDATE_BIT, (unsigned long *)&task->objcg);
  3592. }
  3593. }
  3594. static void mem_cgroup_attach(struct cgroup_taskset *tset)
  3595. {
  3596. mem_cgroup_lru_gen_attach(tset);
  3597. mem_cgroup_kmem_attach(tset);
  3598. }
  3599. static int seq_puts_memcg_tunable(struct seq_file *m, unsigned long value)
  3600. {
  3601. if (value == PAGE_COUNTER_MAX)
  3602. seq_puts(m, "max\n");
  3603. else
  3604. seq_printf(m, "%llu\n", (u64)value * PAGE_SIZE);
  3605. return 0;
  3606. }
  3607. static u64 memory_current_read(struct cgroup_subsys_state *css,
  3608. struct cftype *cft)
  3609. {
  3610. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3611. return (u64)page_counter_read(&memcg->memory) * PAGE_SIZE;
  3612. }
  3613. #define OFP_PEAK_UNSET (((-1UL)))
  3614. static int peak_show(struct seq_file *sf, void *v, struct page_counter *pc)
  3615. {
  3616. struct cgroup_of_peak *ofp = of_peak(sf->private);
  3617. u64 fd_peak = READ_ONCE(ofp->value), peak;
  3618. /* User wants global or local peak? */
  3619. if (fd_peak == OFP_PEAK_UNSET)
  3620. peak = pc->watermark;
  3621. else
  3622. peak = max(fd_peak, READ_ONCE(pc->local_watermark));
  3623. seq_printf(sf, "%llu\n", peak * PAGE_SIZE);
  3624. return 0;
  3625. }
  3626. static int memory_peak_show(struct seq_file *sf, void *v)
  3627. {
  3628. struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(sf));
  3629. return peak_show(sf, v, &memcg->memory);
  3630. }
  3631. static int peak_open(struct kernfs_open_file *of)
  3632. {
  3633. struct cgroup_of_peak *ofp = of_peak(of);
  3634. ofp->value = OFP_PEAK_UNSET;
  3635. return 0;
  3636. }
  3637. static void peak_release(struct kernfs_open_file *of)
  3638. {
  3639. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  3640. struct cgroup_of_peak *ofp = of_peak(of);
  3641. if (ofp->value == OFP_PEAK_UNSET) {
  3642. /* fast path (no writes on this fd) */
  3643. return;
  3644. }
  3645. spin_lock(&memcg->peaks_lock);
  3646. list_del(&ofp->list);
  3647. spin_unlock(&memcg->peaks_lock);
  3648. }
  3649. static ssize_t peak_write(struct kernfs_open_file *of, char *buf, size_t nbytes,
  3650. loff_t off, struct page_counter *pc,
  3651. struct list_head *watchers)
  3652. {
  3653. unsigned long usage;
  3654. struct cgroup_of_peak *peer_ctx;
  3655. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  3656. struct cgroup_of_peak *ofp = of_peak(of);
  3657. spin_lock(&memcg->peaks_lock);
  3658. usage = page_counter_read(pc);
  3659. WRITE_ONCE(pc->local_watermark, usage);
  3660. list_for_each_entry(peer_ctx, watchers, list)
  3661. if (usage > peer_ctx->value)
  3662. WRITE_ONCE(peer_ctx->value, usage);
  3663. /* initial write, register watcher */
  3664. if (ofp->value == OFP_PEAK_UNSET)
  3665. list_add(&ofp->list, watchers);
  3666. WRITE_ONCE(ofp->value, usage);
  3667. spin_unlock(&memcg->peaks_lock);
  3668. return nbytes;
  3669. }
  3670. static ssize_t memory_peak_write(struct kernfs_open_file *of, char *buf,
  3671. size_t nbytes, loff_t off)
  3672. {
  3673. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  3674. return peak_write(of, buf, nbytes, off, &memcg->memory,
  3675. &memcg->memory_peaks);
  3676. }
  3677. #undef OFP_PEAK_UNSET
  3678. static int memory_min_show(struct seq_file *m, void *v)
  3679. {
  3680. return seq_puts_memcg_tunable(m,
  3681. READ_ONCE(mem_cgroup_from_seq(m)->memory.min));
  3682. }
  3683. static ssize_t memory_min_write(struct kernfs_open_file *of,
  3684. char *buf, size_t nbytes, loff_t off)
  3685. {
  3686. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  3687. unsigned long min;
  3688. int err;
  3689. buf = strstrip(buf);
  3690. err = page_counter_memparse(buf, "max", &min);
  3691. if (err)
  3692. return err;
  3693. page_counter_set_min(&memcg->memory, min);
  3694. return nbytes;
  3695. }
  3696. static int memory_low_show(struct seq_file *m, void *v)
  3697. {
  3698. return seq_puts_memcg_tunable(m,
  3699. READ_ONCE(mem_cgroup_from_seq(m)->memory.low));
  3700. }
  3701. static ssize_t memory_low_write(struct kernfs_open_file *of,
  3702. char *buf, size_t nbytes, loff_t off)
  3703. {
  3704. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  3705. unsigned long low;
  3706. int err;
  3707. buf = strstrip(buf);
  3708. err = page_counter_memparse(buf, "max", &low);
  3709. if (err)
  3710. return err;
  3711. page_counter_set_low(&memcg->memory, low);
  3712. return nbytes;
  3713. }
  3714. static int memory_high_show(struct seq_file *m, void *v)
  3715. {
  3716. return seq_puts_memcg_tunable(m,
  3717. READ_ONCE(mem_cgroup_from_seq(m)->memory.high));
  3718. }
  3719. static ssize_t memory_high_write(struct kernfs_open_file *of,
  3720. char *buf, size_t nbytes, loff_t off)
  3721. {
  3722. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  3723. unsigned int nr_retries = MAX_RECLAIM_RETRIES;
  3724. bool drained = false;
  3725. unsigned long high;
  3726. int err;
  3727. buf = strstrip(buf);
  3728. err = page_counter_memparse(buf, "max", &high);
  3729. if (err)
  3730. return err;
  3731. page_counter_set_high(&memcg->memory, high);
  3732. if (of->file->f_flags & O_NONBLOCK)
  3733. goto out;
  3734. for (;;) {
  3735. unsigned long nr_pages = page_counter_read(&memcg->memory);
  3736. unsigned long reclaimed;
  3737. if (nr_pages <= high)
  3738. break;
  3739. if (signal_pending(current))
  3740. break;
  3741. if (!drained) {
  3742. drain_all_stock(memcg);
  3743. drained = true;
  3744. continue;
  3745. }
  3746. reclaimed = try_to_free_mem_cgroup_pages(memcg, nr_pages - high,
  3747. GFP_KERNEL, MEMCG_RECLAIM_MAY_SWAP, NULL);
  3748. if (!reclaimed && !nr_retries--)
  3749. break;
  3750. }
  3751. out:
  3752. memcg_wb_domain_size_changed(memcg);
  3753. return nbytes;
  3754. }
  3755. static int memory_max_show(struct seq_file *m, void *v)
  3756. {
  3757. return seq_puts_memcg_tunable(m,
  3758. READ_ONCE(mem_cgroup_from_seq(m)->memory.max));
  3759. }
  3760. static ssize_t memory_max_write(struct kernfs_open_file *of,
  3761. char *buf, size_t nbytes, loff_t off)
  3762. {
  3763. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  3764. unsigned int nr_reclaims = MAX_RECLAIM_RETRIES;
  3765. bool drained = false;
  3766. unsigned long max;
  3767. int err;
  3768. buf = strstrip(buf);
  3769. err = page_counter_memparse(buf, "max", &max);
  3770. if (err)
  3771. return err;
  3772. xchg(&memcg->memory.max, max);
  3773. if (of->file->f_flags & O_NONBLOCK)
  3774. goto out;
  3775. for (;;) {
  3776. unsigned long nr_pages = page_counter_read(&memcg->memory);
  3777. if (nr_pages <= max)
  3778. break;
  3779. if (signal_pending(current))
  3780. break;
  3781. if (!drained) {
  3782. drain_all_stock(memcg);
  3783. drained = true;
  3784. continue;
  3785. }
  3786. if (nr_reclaims) {
  3787. if (!try_to_free_mem_cgroup_pages(memcg, nr_pages - max,
  3788. GFP_KERNEL, MEMCG_RECLAIM_MAY_SWAP, NULL))
  3789. nr_reclaims--;
  3790. continue;
  3791. }
  3792. memcg_memory_event(memcg, MEMCG_OOM);
  3793. if (!mem_cgroup_out_of_memory(memcg, GFP_KERNEL, 0))
  3794. break;
  3795. cond_resched();
  3796. }
  3797. out:
  3798. memcg_wb_domain_size_changed(memcg);
  3799. return nbytes;
  3800. }
  3801. /*
  3802. * Note: don't forget to update the 'samples/cgroup/memcg_event_listener'
  3803. * if any new events become available.
  3804. */
  3805. static void __memory_events_show(struct seq_file *m, atomic_long_t *events)
  3806. {
  3807. seq_printf(m, "low %lu\n", atomic_long_read(&events[MEMCG_LOW]));
  3808. seq_printf(m, "high %lu\n", atomic_long_read(&events[MEMCG_HIGH]));
  3809. seq_printf(m, "max %lu\n", atomic_long_read(&events[MEMCG_MAX]));
  3810. seq_printf(m, "oom %lu\n", atomic_long_read(&events[MEMCG_OOM]));
  3811. seq_printf(m, "oom_kill %lu\n",
  3812. atomic_long_read(&events[MEMCG_OOM_KILL]));
  3813. seq_printf(m, "oom_group_kill %lu\n",
  3814. atomic_long_read(&events[MEMCG_OOM_GROUP_KILL]));
  3815. seq_printf(m, "sock_throttled %lu\n",
  3816. atomic_long_read(&events[MEMCG_SOCK_THROTTLED]));
  3817. }
  3818. static int memory_events_show(struct seq_file *m, void *v)
  3819. {
  3820. struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
  3821. __memory_events_show(m, memcg->memory_events);
  3822. return 0;
  3823. }
  3824. static int memory_events_local_show(struct seq_file *m, void *v)
  3825. {
  3826. struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
  3827. __memory_events_show(m, memcg->memory_events_local);
  3828. return 0;
  3829. }
  3830. int memory_stat_show(struct seq_file *m, void *v)
  3831. {
  3832. struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
  3833. char *buf = kmalloc(SEQ_BUF_SIZE, GFP_KERNEL);
  3834. struct seq_buf s;
  3835. if (!buf)
  3836. return -ENOMEM;
  3837. seq_buf_init(&s, buf, SEQ_BUF_SIZE);
  3838. memory_stat_format(memcg, &s);
  3839. seq_puts(m, buf);
  3840. kfree(buf);
  3841. return 0;
  3842. }
  3843. #ifdef CONFIG_NUMA
  3844. static inline unsigned long lruvec_page_state_output(struct lruvec *lruvec,
  3845. int item)
  3846. {
  3847. return lruvec_page_state(lruvec, item) *
  3848. memcg_page_state_output_unit(item);
  3849. }
  3850. static int memory_numa_stat_show(struct seq_file *m, void *v)
  3851. {
  3852. int i;
  3853. struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
  3854. mem_cgroup_flush_stats(memcg);
  3855. for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
  3856. int nid;
  3857. if (memory_stats[i].idx >= NR_VM_NODE_STAT_ITEMS)
  3858. continue;
  3859. seq_printf(m, "%s", memory_stats[i].name);
  3860. for_each_node_state(nid, N_MEMORY) {
  3861. u64 size;
  3862. struct lruvec *lruvec;
  3863. lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
  3864. size = lruvec_page_state_output(lruvec,
  3865. memory_stats[i].idx);
  3866. seq_printf(m, " N%d=%llu", nid, size);
  3867. }
  3868. seq_putc(m, '\n');
  3869. }
  3870. return 0;
  3871. }
  3872. #endif
  3873. static int memory_oom_group_show(struct seq_file *m, void *v)
  3874. {
  3875. struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
  3876. seq_printf(m, "%d\n", READ_ONCE(memcg->oom_group));
  3877. return 0;
  3878. }
  3879. static ssize_t memory_oom_group_write(struct kernfs_open_file *of,
  3880. char *buf, size_t nbytes, loff_t off)
  3881. {
  3882. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  3883. int ret, oom_group;
  3884. buf = strstrip(buf);
  3885. if (!buf)
  3886. return -EINVAL;
  3887. ret = kstrtoint(buf, 0, &oom_group);
  3888. if (ret)
  3889. return ret;
  3890. if (oom_group != 0 && oom_group != 1)
  3891. return -EINVAL;
  3892. WRITE_ONCE(memcg->oom_group, oom_group);
  3893. return nbytes;
  3894. }
  3895. static ssize_t memory_reclaim(struct kernfs_open_file *of, char *buf,
  3896. size_t nbytes, loff_t off)
  3897. {
  3898. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  3899. int ret;
  3900. ret = user_proactive_reclaim(buf, memcg, NULL);
  3901. if (ret)
  3902. return ret;
  3903. return nbytes;
  3904. }
  3905. static struct cftype memory_files[] = {
  3906. {
  3907. .name = "current",
  3908. .flags = CFTYPE_NOT_ON_ROOT,
  3909. .read_u64 = memory_current_read,
  3910. },
  3911. {
  3912. .name = "peak",
  3913. .flags = CFTYPE_NOT_ON_ROOT,
  3914. .open = peak_open,
  3915. .release = peak_release,
  3916. .seq_show = memory_peak_show,
  3917. .write = memory_peak_write,
  3918. },
  3919. {
  3920. .name = "min",
  3921. .flags = CFTYPE_NOT_ON_ROOT,
  3922. .seq_show = memory_min_show,
  3923. .write = memory_min_write,
  3924. },
  3925. {
  3926. .name = "low",
  3927. .flags = CFTYPE_NOT_ON_ROOT,
  3928. .seq_show = memory_low_show,
  3929. .write = memory_low_write,
  3930. },
  3931. {
  3932. .name = "high",
  3933. .flags = CFTYPE_NOT_ON_ROOT,
  3934. .seq_show = memory_high_show,
  3935. .write = memory_high_write,
  3936. },
  3937. {
  3938. .name = "max",
  3939. .flags = CFTYPE_NOT_ON_ROOT,
  3940. .seq_show = memory_max_show,
  3941. .write = memory_max_write,
  3942. },
  3943. {
  3944. .name = "events",
  3945. .flags = CFTYPE_NOT_ON_ROOT,
  3946. .file_offset = offsetof(struct mem_cgroup, events_file),
  3947. .seq_show = memory_events_show,
  3948. },
  3949. {
  3950. .name = "events.local",
  3951. .flags = CFTYPE_NOT_ON_ROOT,
  3952. .file_offset = offsetof(struct mem_cgroup, events_local_file),
  3953. .seq_show = memory_events_local_show,
  3954. },
  3955. {
  3956. .name = "stat",
  3957. .seq_show = memory_stat_show,
  3958. },
  3959. #ifdef CONFIG_NUMA
  3960. {
  3961. .name = "numa_stat",
  3962. .seq_show = memory_numa_stat_show,
  3963. },
  3964. #endif
  3965. {
  3966. .name = "oom.group",
  3967. .flags = CFTYPE_NOT_ON_ROOT | CFTYPE_NS_DELEGATABLE,
  3968. .seq_show = memory_oom_group_show,
  3969. .write = memory_oom_group_write,
  3970. },
  3971. {
  3972. .name = "reclaim",
  3973. .flags = CFTYPE_NS_DELEGATABLE,
  3974. .write = memory_reclaim,
  3975. },
  3976. { } /* terminate */
  3977. };
  3978. struct cgroup_subsys memory_cgrp_subsys = {
  3979. .css_alloc = mem_cgroup_css_alloc,
  3980. .css_online = mem_cgroup_css_online,
  3981. .css_offline = mem_cgroup_css_offline,
  3982. .css_released = mem_cgroup_css_released,
  3983. .css_free = mem_cgroup_css_free,
  3984. .css_reset = mem_cgroup_css_reset,
  3985. .css_rstat_flush = mem_cgroup_css_rstat_flush,
  3986. .attach = mem_cgroup_attach,
  3987. .fork = mem_cgroup_fork,
  3988. .exit = mem_cgroup_exit,
  3989. .dfl_cftypes = memory_files,
  3990. #ifdef CONFIG_MEMCG_V1
  3991. .legacy_cftypes = mem_cgroup_legacy_files,
  3992. #endif
  3993. .early_init = 0,
  3994. };
  3995. /**
  3996. * mem_cgroup_calculate_protection - check if memory consumption is in the normal range
  3997. * @root: the top ancestor of the sub-tree being checked
  3998. * @memcg: the memory cgroup to check
  3999. *
  4000. * WARNING: This function is not stateless! It can only be used as part
  4001. * of a top-down tree iteration, not for isolated queries.
  4002. */
  4003. void mem_cgroup_calculate_protection(struct mem_cgroup *root,
  4004. struct mem_cgroup *memcg)
  4005. {
  4006. bool recursive_protection =
  4007. cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_RECURSIVE_PROT;
  4008. if (mem_cgroup_disabled())
  4009. return;
  4010. if (!root)
  4011. root = root_mem_cgroup;
  4012. page_counter_calculate_protection(&root->memory, &memcg->memory, recursive_protection);
  4013. }
  4014. static int charge_memcg(struct folio *folio, struct mem_cgroup *memcg,
  4015. gfp_t gfp)
  4016. {
  4017. int ret;
  4018. ret = try_charge(memcg, gfp, folio_nr_pages(folio));
  4019. if (ret)
  4020. goto out;
  4021. css_get(&memcg->css);
  4022. commit_charge(folio, memcg);
  4023. memcg1_commit_charge(folio, memcg);
  4024. out:
  4025. return ret;
  4026. }
  4027. int __mem_cgroup_charge(struct folio *folio, struct mm_struct *mm, gfp_t gfp)
  4028. {
  4029. struct mem_cgroup *memcg;
  4030. int ret;
  4031. memcg = get_mem_cgroup_from_mm(mm);
  4032. ret = charge_memcg(folio, memcg, gfp);
  4033. css_put(&memcg->css);
  4034. return ret;
  4035. }
  4036. /**
  4037. * mem_cgroup_charge_hugetlb - charge the memcg for a hugetlb folio
  4038. * @folio: folio being charged
  4039. * @gfp: reclaim mode
  4040. *
  4041. * This function is called when allocating a huge page folio, after the page has
  4042. * already been obtained and charged to the appropriate hugetlb cgroup
  4043. * controller (if it is enabled).
  4044. *
  4045. * Returns ENOMEM if the memcg is already full.
  4046. * Returns 0 if either the charge was successful, or if we skip the charging.
  4047. */
  4048. int mem_cgroup_charge_hugetlb(struct folio *folio, gfp_t gfp)
  4049. {
  4050. struct mem_cgroup *memcg = get_mem_cgroup_from_current();
  4051. int ret = 0;
  4052. /*
  4053. * Even memcg does not account for hugetlb, we still want to update
  4054. * system-level stats via lruvec_stat_mod_folio. Return 0, and skip
  4055. * charging the memcg.
  4056. */
  4057. if (mem_cgroup_disabled() || !memcg_accounts_hugetlb() ||
  4058. !memcg || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
  4059. goto out;
  4060. if (charge_memcg(folio, memcg, gfp))
  4061. ret = -ENOMEM;
  4062. out:
  4063. mem_cgroup_put(memcg);
  4064. return ret;
  4065. }
  4066. /**
  4067. * mem_cgroup_swapin_charge_folio - Charge a newly allocated folio for swapin.
  4068. * @folio: folio to charge.
  4069. * @mm: mm context of the victim
  4070. * @gfp: reclaim mode
  4071. * @entry: swap entry for which the folio is allocated
  4072. *
  4073. * This function charges a folio allocated for swapin. Please call this before
  4074. * adding the folio to the swapcache.
  4075. *
  4076. * Returns 0 on success. Otherwise, an error code is returned.
  4077. */
  4078. int mem_cgroup_swapin_charge_folio(struct folio *folio, struct mm_struct *mm,
  4079. gfp_t gfp, swp_entry_t entry)
  4080. {
  4081. struct mem_cgroup *memcg;
  4082. unsigned short id;
  4083. int ret;
  4084. if (mem_cgroup_disabled())
  4085. return 0;
  4086. id = lookup_swap_cgroup_id(entry);
  4087. rcu_read_lock();
  4088. memcg = mem_cgroup_from_private_id(id);
  4089. if (!memcg || !css_tryget_online(&memcg->css))
  4090. memcg = get_mem_cgroup_from_mm(mm);
  4091. rcu_read_unlock();
  4092. ret = charge_memcg(folio, memcg, gfp);
  4093. css_put(&memcg->css);
  4094. return ret;
  4095. }
  4096. struct uncharge_gather {
  4097. struct mem_cgroup *memcg;
  4098. unsigned long nr_memory;
  4099. unsigned long pgpgout;
  4100. unsigned long nr_kmem;
  4101. int nid;
  4102. };
  4103. static inline void uncharge_gather_clear(struct uncharge_gather *ug)
  4104. {
  4105. memset(ug, 0, sizeof(*ug));
  4106. }
  4107. static void uncharge_batch(const struct uncharge_gather *ug)
  4108. {
  4109. if (ug->nr_memory) {
  4110. memcg_uncharge(ug->memcg, ug->nr_memory);
  4111. if (ug->nr_kmem) {
  4112. mod_memcg_state(ug->memcg, MEMCG_KMEM, -ug->nr_kmem);
  4113. memcg1_account_kmem(ug->memcg, -ug->nr_kmem);
  4114. }
  4115. memcg1_oom_recover(ug->memcg);
  4116. }
  4117. memcg1_uncharge_batch(ug->memcg, ug->pgpgout, ug->nr_memory, ug->nid);
  4118. /* drop reference from uncharge_folio */
  4119. css_put(&ug->memcg->css);
  4120. }
  4121. static void uncharge_folio(struct folio *folio, struct uncharge_gather *ug)
  4122. {
  4123. long nr_pages;
  4124. struct mem_cgroup *memcg;
  4125. struct obj_cgroup *objcg;
  4126. VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
  4127. /*
  4128. * Nobody should be changing or seriously looking at
  4129. * folio memcg or objcg at this point, we have fully
  4130. * exclusive access to the folio.
  4131. */
  4132. if (folio_memcg_kmem(folio)) {
  4133. objcg = __folio_objcg(folio);
  4134. /*
  4135. * This get matches the put at the end of the function and
  4136. * kmem pages do not hold memcg references anymore.
  4137. */
  4138. memcg = get_mem_cgroup_from_objcg(objcg);
  4139. } else {
  4140. memcg = __folio_memcg(folio);
  4141. }
  4142. if (!memcg)
  4143. return;
  4144. if (ug->memcg != memcg) {
  4145. if (ug->memcg) {
  4146. uncharge_batch(ug);
  4147. uncharge_gather_clear(ug);
  4148. }
  4149. ug->memcg = memcg;
  4150. ug->nid = folio_nid(folio);
  4151. /* pairs with css_put in uncharge_batch */
  4152. css_get(&memcg->css);
  4153. }
  4154. nr_pages = folio_nr_pages(folio);
  4155. if (folio_memcg_kmem(folio)) {
  4156. ug->nr_memory += nr_pages;
  4157. ug->nr_kmem += nr_pages;
  4158. folio->memcg_data = 0;
  4159. obj_cgroup_put(objcg);
  4160. } else {
  4161. /* LRU pages aren't accounted at the root level */
  4162. if (!mem_cgroup_is_root(memcg))
  4163. ug->nr_memory += nr_pages;
  4164. ug->pgpgout++;
  4165. WARN_ON_ONCE(folio_unqueue_deferred_split(folio));
  4166. folio->memcg_data = 0;
  4167. }
  4168. css_put(&memcg->css);
  4169. }
  4170. void __mem_cgroup_uncharge(struct folio *folio)
  4171. {
  4172. struct uncharge_gather ug;
  4173. /* Don't touch folio->lru of any random page, pre-check: */
  4174. if (!folio_memcg_charged(folio))
  4175. return;
  4176. uncharge_gather_clear(&ug);
  4177. uncharge_folio(folio, &ug);
  4178. uncharge_batch(&ug);
  4179. }
  4180. void __mem_cgroup_uncharge_folios(struct folio_batch *folios)
  4181. {
  4182. struct uncharge_gather ug;
  4183. unsigned int i;
  4184. uncharge_gather_clear(&ug);
  4185. for (i = 0; i < folios->nr; i++)
  4186. uncharge_folio(folios->folios[i], &ug);
  4187. if (ug.memcg)
  4188. uncharge_batch(&ug);
  4189. }
  4190. /**
  4191. * mem_cgroup_replace_folio - Charge a folio's replacement.
  4192. * @old: Currently circulating folio.
  4193. * @new: Replacement folio.
  4194. *
  4195. * Charge @new as a replacement folio for @old. @old will
  4196. * be uncharged upon free.
  4197. *
  4198. * Both folios must be locked, @new->mapping must be set up.
  4199. */
  4200. void mem_cgroup_replace_folio(struct folio *old, struct folio *new)
  4201. {
  4202. struct mem_cgroup *memcg;
  4203. long nr_pages = folio_nr_pages(new);
  4204. VM_BUG_ON_FOLIO(!folio_test_locked(old), old);
  4205. VM_BUG_ON_FOLIO(!folio_test_locked(new), new);
  4206. VM_BUG_ON_FOLIO(folio_test_anon(old) != folio_test_anon(new), new);
  4207. VM_BUG_ON_FOLIO(folio_nr_pages(old) != nr_pages, new);
  4208. if (mem_cgroup_disabled())
  4209. return;
  4210. /* Page cache replacement: new folio already charged? */
  4211. if (folio_memcg_charged(new))
  4212. return;
  4213. memcg = folio_memcg(old);
  4214. VM_WARN_ON_ONCE_FOLIO(!memcg, old);
  4215. if (!memcg)
  4216. return;
  4217. /* Force-charge the new page. The old one will be freed soon */
  4218. if (!mem_cgroup_is_root(memcg)) {
  4219. page_counter_charge(&memcg->memory, nr_pages);
  4220. if (do_memsw_account())
  4221. page_counter_charge(&memcg->memsw, nr_pages);
  4222. }
  4223. css_get(&memcg->css);
  4224. commit_charge(new, memcg);
  4225. memcg1_commit_charge(new, memcg);
  4226. }
  4227. /**
  4228. * mem_cgroup_migrate - Transfer the memcg data from the old to the new folio.
  4229. * @old: Currently circulating folio.
  4230. * @new: Replacement folio.
  4231. *
  4232. * Transfer the memcg data from the old folio to the new folio for migration.
  4233. * The old folio's data info will be cleared. Note that the memory counters
  4234. * will remain unchanged throughout the process.
  4235. *
  4236. * Both folios must be locked, @new->mapping must be set up.
  4237. */
  4238. void mem_cgroup_migrate(struct folio *old, struct folio *new)
  4239. {
  4240. struct mem_cgroup *memcg;
  4241. VM_BUG_ON_FOLIO(!folio_test_locked(old), old);
  4242. VM_BUG_ON_FOLIO(!folio_test_locked(new), new);
  4243. VM_BUG_ON_FOLIO(folio_test_anon(old) != folio_test_anon(new), new);
  4244. VM_BUG_ON_FOLIO(folio_nr_pages(old) != folio_nr_pages(new), new);
  4245. VM_BUG_ON_FOLIO(folio_test_lru(old), old);
  4246. if (mem_cgroup_disabled())
  4247. return;
  4248. memcg = folio_memcg(old);
  4249. /*
  4250. * Note that it is normal to see !memcg for a hugetlb folio.
  4251. * For e.g, it could have been allocated when memory_hugetlb_accounting
  4252. * was not selected.
  4253. */
  4254. VM_WARN_ON_ONCE_FOLIO(!folio_test_hugetlb(old) && !memcg, old);
  4255. if (!memcg)
  4256. return;
  4257. /* Transfer the charge and the css ref */
  4258. commit_charge(new, memcg);
  4259. /* Warning should never happen, so don't worry about refcount non-0 */
  4260. WARN_ON_ONCE(folio_unqueue_deferred_split(old));
  4261. old->memcg_data = 0;
  4262. }
  4263. DEFINE_STATIC_KEY_FALSE(memcg_sockets_enabled_key);
  4264. EXPORT_SYMBOL(memcg_sockets_enabled_key);
  4265. void mem_cgroup_sk_alloc(struct sock *sk)
  4266. {
  4267. struct mem_cgroup *memcg;
  4268. if (!mem_cgroup_sockets_enabled)
  4269. return;
  4270. /* Do not associate the sock with unrelated interrupted task's memcg. */
  4271. if (!in_task())
  4272. return;
  4273. rcu_read_lock();
  4274. memcg = mem_cgroup_from_task(current);
  4275. if (mem_cgroup_is_root(memcg))
  4276. goto out;
  4277. if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && !memcg1_tcpmem_active(memcg))
  4278. goto out;
  4279. if (css_tryget(&memcg->css))
  4280. sk->sk_memcg = memcg;
  4281. out:
  4282. rcu_read_unlock();
  4283. }
  4284. void mem_cgroup_sk_free(struct sock *sk)
  4285. {
  4286. struct mem_cgroup *memcg = mem_cgroup_from_sk(sk);
  4287. if (memcg)
  4288. css_put(&memcg->css);
  4289. }
  4290. void mem_cgroup_sk_inherit(const struct sock *sk, struct sock *newsk)
  4291. {
  4292. struct mem_cgroup *memcg;
  4293. if (sk->sk_memcg == newsk->sk_memcg)
  4294. return;
  4295. mem_cgroup_sk_free(newsk);
  4296. memcg = mem_cgroup_from_sk(sk);
  4297. if (memcg)
  4298. css_get(&memcg->css);
  4299. newsk->sk_memcg = sk->sk_memcg;
  4300. }
  4301. /**
  4302. * mem_cgroup_sk_charge - charge socket memory
  4303. * @sk: socket in memcg to charge
  4304. * @nr_pages: number of pages to charge
  4305. * @gfp_mask: reclaim mode
  4306. *
  4307. * Charges @nr_pages to @memcg. Returns %true if the charge fit within
  4308. * @memcg's configured limit, %false if it doesn't.
  4309. */
  4310. bool mem_cgroup_sk_charge(const struct sock *sk, unsigned int nr_pages,
  4311. gfp_t gfp_mask)
  4312. {
  4313. struct mem_cgroup *memcg = mem_cgroup_from_sk(sk);
  4314. if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
  4315. return memcg1_charge_skmem(memcg, nr_pages, gfp_mask);
  4316. if (try_charge_memcg(memcg, gfp_mask, nr_pages) == 0) {
  4317. mod_memcg_state(memcg, MEMCG_SOCK, nr_pages);
  4318. return true;
  4319. }
  4320. return false;
  4321. }
  4322. /**
  4323. * mem_cgroup_sk_uncharge - uncharge socket memory
  4324. * @sk: socket in memcg to uncharge
  4325. * @nr_pages: number of pages to uncharge
  4326. */
  4327. void mem_cgroup_sk_uncharge(const struct sock *sk, unsigned int nr_pages)
  4328. {
  4329. struct mem_cgroup *memcg = mem_cgroup_from_sk(sk);
  4330. if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
  4331. memcg1_uncharge_skmem(memcg, nr_pages);
  4332. return;
  4333. }
  4334. mod_memcg_state(memcg, MEMCG_SOCK, -nr_pages);
  4335. refill_stock(memcg, nr_pages);
  4336. }
  4337. void mem_cgroup_flush_workqueue(void)
  4338. {
  4339. flush_workqueue(memcg_wq);
  4340. }
  4341. static int __init cgroup_memory(char *s)
  4342. {
  4343. char *token;
  4344. while ((token = strsep(&s, ",")) != NULL) {
  4345. if (!*token)
  4346. continue;
  4347. if (!strcmp(token, "nosocket"))
  4348. cgroup_memory_nosocket = true;
  4349. if (!strcmp(token, "nokmem"))
  4350. cgroup_memory_nokmem = true;
  4351. if (!strcmp(token, "nobpf"))
  4352. cgroup_memory_nobpf = true;
  4353. }
  4354. return 1;
  4355. }
  4356. __setup("cgroup.memory=", cgroup_memory);
  4357. /*
  4358. * Memory controller init before cgroup_init() initialize root_mem_cgroup.
  4359. *
  4360. * Some parts like memcg_hotplug_cpu_dead() have to be initialized from this
  4361. * context because of lock dependencies (cgroup_lock -> cpu hotplug) but
  4362. * basically everything that doesn't depend on a specific mem_cgroup structure
  4363. * should be initialized from here.
  4364. */
  4365. int __init mem_cgroup_init(void)
  4366. {
  4367. unsigned int memcg_size;
  4368. int cpu;
  4369. /*
  4370. * Currently s32 type (can refer to struct batched_lruvec_stat) is
  4371. * used for per-memcg-per-cpu caching of per-node statistics. In order
  4372. * to work fine, we should make sure that the overfill threshold can't
  4373. * exceed S32_MAX / PAGE_SIZE.
  4374. */
  4375. BUILD_BUG_ON(MEMCG_CHARGE_BATCH > S32_MAX / PAGE_SIZE);
  4376. cpuhp_setup_state_nocalls(CPUHP_MM_MEMCQ_DEAD, "mm/memctrl:dead", NULL,
  4377. memcg_hotplug_cpu_dead);
  4378. memcg_wq = alloc_workqueue("memcg", WQ_PERCPU, 0);
  4379. WARN_ON(!memcg_wq);
  4380. for_each_possible_cpu(cpu) {
  4381. INIT_WORK(&per_cpu_ptr(&memcg_stock, cpu)->work,
  4382. drain_local_memcg_stock);
  4383. INIT_WORK(&per_cpu_ptr(&obj_stock, cpu)->work,
  4384. drain_local_obj_stock);
  4385. }
  4386. memcg_size = struct_size_t(struct mem_cgroup, nodeinfo, nr_node_ids);
  4387. memcg_cachep = kmem_cache_create("mem_cgroup", memcg_size, 0,
  4388. SLAB_PANIC | SLAB_HWCACHE_ALIGN, NULL);
  4389. memcg_pn_cachep = KMEM_CACHE(mem_cgroup_per_node,
  4390. SLAB_PANIC | SLAB_HWCACHE_ALIGN);
  4391. return 0;
  4392. }
  4393. #ifdef CONFIG_SWAP
  4394. /**
  4395. * __mem_cgroup_try_charge_swap - try charging swap space for a folio
  4396. * @folio: folio being added to swap
  4397. * @entry: swap entry to charge
  4398. *
  4399. * Try to charge @folio's memcg for the swap space at @entry.
  4400. *
  4401. * Returns 0 on success, -ENOMEM on failure.
  4402. */
  4403. int __mem_cgroup_try_charge_swap(struct folio *folio, swp_entry_t entry)
  4404. {
  4405. unsigned int nr_pages = folio_nr_pages(folio);
  4406. struct page_counter *counter;
  4407. struct mem_cgroup *memcg;
  4408. if (do_memsw_account())
  4409. return 0;
  4410. memcg = folio_memcg(folio);
  4411. VM_WARN_ON_ONCE_FOLIO(!memcg, folio);
  4412. if (!memcg)
  4413. return 0;
  4414. if (!entry.val) {
  4415. memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
  4416. return 0;
  4417. }
  4418. memcg = mem_cgroup_private_id_get_online(memcg);
  4419. if (!mem_cgroup_is_root(memcg) &&
  4420. !page_counter_try_charge(&memcg->swap, nr_pages, &counter)) {
  4421. memcg_memory_event(memcg, MEMCG_SWAP_MAX);
  4422. memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
  4423. mem_cgroup_private_id_put(memcg);
  4424. return -ENOMEM;
  4425. }
  4426. /* Get references for the tail pages, too */
  4427. if (nr_pages > 1)
  4428. mem_cgroup_private_id_get_many(memcg, nr_pages - 1);
  4429. mod_memcg_state(memcg, MEMCG_SWAP, nr_pages);
  4430. swap_cgroup_record(folio, mem_cgroup_private_id(memcg), entry);
  4431. return 0;
  4432. }
  4433. /**
  4434. * __mem_cgroup_uncharge_swap - uncharge swap space
  4435. * @entry: swap entry to uncharge
  4436. * @nr_pages: the amount of swap space to uncharge
  4437. */
  4438. void __mem_cgroup_uncharge_swap(swp_entry_t entry, unsigned int nr_pages)
  4439. {
  4440. struct mem_cgroup *memcg;
  4441. unsigned short id;
  4442. id = swap_cgroup_clear(entry, nr_pages);
  4443. rcu_read_lock();
  4444. memcg = mem_cgroup_from_private_id(id);
  4445. if (memcg) {
  4446. if (!mem_cgroup_is_root(memcg)) {
  4447. if (do_memsw_account())
  4448. page_counter_uncharge(&memcg->memsw, nr_pages);
  4449. else
  4450. page_counter_uncharge(&memcg->swap, nr_pages);
  4451. }
  4452. mod_memcg_state(memcg, MEMCG_SWAP, -nr_pages);
  4453. mem_cgroup_private_id_put_many(memcg, nr_pages);
  4454. }
  4455. rcu_read_unlock();
  4456. }
  4457. long mem_cgroup_get_nr_swap_pages(struct mem_cgroup *memcg)
  4458. {
  4459. long nr_swap_pages = get_nr_swap_pages();
  4460. if (mem_cgroup_disabled() || do_memsw_account())
  4461. return nr_swap_pages;
  4462. for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg))
  4463. nr_swap_pages = min_t(long, nr_swap_pages,
  4464. READ_ONCE(memcg->swap.max) -
  4465. page_counter_read(&memcg->swap));
  4466. return nr_swap_pages;
  4467. }
  4468. bool mem_cgroup_swap_full(struct folio *folio)
  4469. {
  4470. struct mem_cgroup *memcg;
  4471. VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
  4472. if (vm_swap_full())
  4473. return true;
  4474. if (do_memsw_account())
  4475. return false;
  4476. memcg = folio_memcg(folio);
  4477. if (!memcg)
  4478. return false;
  4479. for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg)) {
  4480. unsigned long usage = page_counter_read(&memcg->swap);
  4481. if (usage * 2 >= READ_ONCE(memcg->swap.high) ||
  4482. usage * 2 >= READ_ONCE(memcg->swap.max))
  4483. return true;
  4484. }
  4485. return false;
  4486. }
  4487. static int __init setup_swap_account(char *s)
  4488. {
  4489. bool res;
  4490. if (!kstrtobool(s, &res) && !res)
  4491. pr_warn_once("The swapaccount=0 commandline option is deprecated "
  4492. "in favor of configuring swap control via cgroupfs. "
  4493. "Please report your usecase to linux-mm@kvack.org if you "
  4494. "depend on this functionality.\n");
  4495. return 1;
  4496. }
  4497. __setup("swapaccount=", setup_swap_account);
  4498. static u64 swap_current_read(struct cgroup_subsys_state *css,
  4499. struct cftype *cft)
  4500. {
  4501. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  4502. return (u64)page_counter_read(&memcg->swap) * PAGE_SIZE;
  4503. }
  4504. static int swap_peak_show(struct seq_file *sf, void *v)
  4505. {
  4506. struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(sf));
  4507. return peak_show(sf, v, &memcg->swap);
  4508. }
  4509. static ssize_t swap_peak_write(struct kernfs_open_file *of, char *buf,
  4510. size_t nbytes, loff_t off)
  4511. {
  4512. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  4513. return peak_write(of, buf, nbytes, off, &memcg->swap,
  4514. &memcg->swap_peaks);
  4515. }
  4516. static int swap_high_show(struct seq_file *m, void *v)
  4517. {
  4518. return seq_puts_memcg_tunable(m,
  4519. READ_ONCE(mem_cgroup_from_seq(m)->swap.high));
  4520. }
  4521. static ssize_t swap_high_write(struct kernfs_open_file *of,
  4522. char *buf, size_t nbytes, loff_t off)
  4523. {
  4524. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  4525. unsigned long high;
  4526. int err;
  4527. buf = strstrip(buf);
  4528. err = page_counter_memparse(buf, "max", &high);
  4529. if (err)
  4530. return err;
  4531. page_counter_set_high(&memcg->swap, high);
  4532. return nbytes;
  4533. }
  4534. static int swap_max_show(struct seq_file *m, void *v)
  4535. {
  4536. return seq_puts_memcg_tunable(m,
  4537. READ_ONCE(mem_cgroup_from_seq(m)->swap.max));
  4538. }
  4539. static ssize_t swap_max_write(struct kernfs_open_file *of,
  4540. char *buf, size_t nbytes, loff_t off)
  4541. {
  4542. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  4543. unsigned long max;
  4544. int err;
  4545. buf = strstrip(buf);
  4546. err = page_counter_memparse(buf, "max", &max);
  4547. if (err)
  4548. return err;
  4549. xchg(&memcg->swap.max, max);
  4550. return nbytes;
  4551. }
  4552. static int swap_events_show(struct seq_file *m, void *v)
  4553. {
  4554. struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
  4555. seq_printf(m, "high %lu\n",
  4556. atomic_long_read(&memcg->memory_events[MEMCG_SWAP_HIGH]));
  4557. seq_printf(m, "max %lu\n",
  4558. atomic_long_read(&memcg->memory_events[MEMCG_SWAP_MAX]));
  4559. seq_printf(m, "fail %lu\n",
  4560. atomic_long_read(&memcg->memory_events[MEMCG_SWAP_FAIL]));
  4561. return 0;
  4562. }
  4563. static struct cftype swap_files[] = {
  4564. {
  4565. .name = "swap.current",
  4566. .flags = CFTYPE_NOT_ON_ROOT,
  4567. .read_u64 = swap_current_read,
  4568. },
  4569. {
  4570. .name = "swap.high",
  4571. .flags = CFTYPE_NOT_ON_ROOT,
  4572. .seq_show = swap_high_show,
  4573. .write = swap_high_write,
  4574. },
  4575. {
  4576. .name = "swap.max",
  4577. .flags = CFTYPE_NOT_ON_ROOT,
  4578. .seq_show = swap_max_show,
  4579. .write = swap_max_write,
  4580. },
  4581. {
  4582. .name = "swap.peak",
  4583. .flags = CFTYPE_NOT_ON_ROOT,
  4584. .open = peak_open,
  4585. .release = peak_release,
  4586. .seq_show = swap_peak_show,
  4587. .write = swap_peak_write,
  4588. },
  4589. {
  4590. .name = "swap.events",
  4591. .flags = CFTYPE_NOT_ON_ROOT,
  4592. .file_offset = offsetof(struct mem_cgroup, swap_events_file),
  4593. .seq_show = swap_events_show,
  4594. },
  4595. { } /* terminate */
  4596. };
  4597. #ifdef CONFIG_ZSWAP
  4598. /**
  4599. * obj_cgroup_may_zswap - check if this cgroup can zswap
  4600. * @objcg: the object cgroup
  4601. *
  4602. * Check if the hierarchical zswap limit has been reached.
  4603. *
  4604. * This doesn't check for specific headroom, and it is not atomic
  4605. * either. But with zswap, the size of the allocation is only known
  4606. * once compression has occurred, and this optimistic pre-check avoids
  4607. * spending cycles on compression when there is already no room left
  4608. * or zswap is disabled altogether somewhere in the hierarchy.
  4609. */
  4610. bool obj_cgroup_may_zswap(struct obj_cgroup *objcg)
  4611. {
  4612. struct mem_cgroup *memcg, *original_memcg;
  4613. bool ret = true;
  4614. if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
  4615. return true;
  4616. original_memcg = get_mem_cgroup_from_objcg(objcg);
  4617. for (memcg = original_memcg; !mem_cgroup_is_root(memcg);
  4618. memcg = parent_mem_cgroup(memcg)) {
  4619. unsigned long max = READ_ONCE(memcg->zswap_max);
  4620. unsigned long pages;
  4621. if (max == PAGE_COUNTER_MAX)
  4622. continue;
  4623. if (max == 0) {
  4624. ret = false;
  4625. break;
  4626. }
  4627. /* Force flush to get accurate stats for charging */
  4628. __mem_cgroup_flush_stats(memcg, true);
  4629. pages = memcg_page_state(memcg, MEMCG_ZSWAP_B) / PAGE_SIZE;
  4630. if (pages < max)
  4631. continue;
  4632. ret = false;
  4633. break;
  4634. }
  4635. mem_cgroup_put(original_memcg);
  4636. return ret;
  4637. }
  4638. /**
  4639. * obj_cgroup_charge_zswap - charge compression backend memory
  4640. * @objcg: the object cgroup
  4641. * @size: size of compressed object
  4642. *
  4643. * This forces the charge after obj_cgroup_may_zswap() allowed
  4644. * compression and storage in zswap for this cgroup to go ahead.
  4645. */
  4646. void obj_cgroup_charge_zswap(struct obj_cgroup *objcg, size_t size)
  4647. {
  4648. struct mem_cgroup *memcg;
  4649. if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
  4650. return;
  4651. VM_WARN_ON_ONCE(!(current->flags & PF_MEMALLOC));
  4652. /* PF_MEMALLOC context, charging must succeed */
  4653. if (obj_cgroup_charge(objcg, GFP_KERNEL, size))
  4654. VM_WARN_ON_ONCE(1);
  4655. rcu_read_lock();
  4656. memcg = obj_cgroup_memcg(objcg);
  4657. mod_memcg_state(memcg, MEMCG_ZSWAP_B, size);
  4658. mod_memcg_state(memcg, MEMCG_ZSWAPPED, 1);
  4659. rcu_read_unlock();
  4660. }
  4661. /**
  4662. * obj_cgroup_uncharge_zswap - uncharge compression backend memory
  4663. * @objcg: the object cgroup
  4664. * @size: size of compressed object
  4665. *
  4666. * Uncharges zswap memory on page in.
  4667. */
  4668. void obj_cgroup_uncharge_zswap(struct obj_cgroup *objcg, size_t size)
  4669. {
  4670. struct mem_cgroup *memcg;
  4671. if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
  4672. return;
  4673. obj_cgroup_uncharge(objcg, size);
  4674. rcu_read_lock();
  4675. memcg = obj_cgroup_memcg(objcg);
  4676. mod_memcg_state(memcg, MEMCG_ZSWAP_B, -size);
  4677. mod_memcg_state(memcg, MEMCG_ZSWAPPED, -1);
  4678. rcu_read_unlock();
  4679. }
  4680. bool mem_cgroup_zswap_writeback_enabled(struct mem_cgroup *memcg)
  4681. {
  4682. /* if zswap is disabled, do not block pages going to the swapping device */
  4683. if (!zswap_is_enabled())
  4684. return true;
  4685. for (; memcg; memcg = parent_mem_cgroup(memcg))
  4686. if (!READ_ONCE(memcg->zswap_writeback))
  4687. return false;
  4688. return true;
  4689. }
  4690. static u64 zswap_current_read(struct cgroup_subsys_state *css,
  4691. struct cftype *cft)
  4692. {
  4693. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  4694. mem_cgroup_flush_stats(memcg);
  4695. return memcg_page_state(memcg, MEMCG_ZSWAP_B);
  4696. }
  4697. static int zswap_max_show(struct seq_file *m, void *v)
  4698. {
  4699. return seq_puts_memcg_tunable(m,
  4700. READ_ONCE(mem_cgroup_from_seq(m)->zswap_max));
  4701. }
  4702. static ssize_t zswap_max_write(struct kernfs_open_file *of,
  4703. char *buf, size_t nbytes, loff_t off)
  4704. {
  4705. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  4706. unsigned long max;
  4707. int err;
  4708. buf = strstrip(buf);
  4709. err = page_counter_memparse(buf, "max", &max);
  4710. if (err)
  4711. return err;
  4712. xchg(&memcg->zswap_max, max);
  4713. return nbytes;
  4714. }
  4715. static int zswap_writeback_show(struct seq_file *m, void *v)
  4716. {
  4717. struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
  4718. seq_printf(m, "%d\n", READ_ONCE(memcg->zswap_writeback));
  4719. return 0;
  4720. }
  4721. static ssize_t zswap_writeback_write(struct kernfs_open_file *of,
  4722. char *buf, size_t nbytes, loff_t off)
  4723. {
  4724. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  4725. int zswap_writeback;
  4726. ssize_t parse_ret = kstrtoint(strstrip(buf), 0, &zswap_writeback);
  4727. if (parse_ret)
  4728. return parse_ret;
  4729. if (zswap_writeback != 0 && zswap_writeback != 1)
  4730. return -EINVAL;
  4731. WRITE_ONCE(memcg->zswap_writeback, zswap_writeback);
  4732. return nbytes;
  4733. }
  4734. static struct cftype zswap_files[] = {
  4735. {
  4736. .name = "zswap.current",
  4737. .flags = CFTYPE_NOT_ON_ROOT,
  4738. .read_u64 = zswap_current_read,
  4739. },
  4740. {
  4741. .name = "zswap.max",
  4742. .flags = CFTYPE_NOT_ON_ROOT,
  4743. .seq_show = zswap_max_show,
  4744. .write = zswap_max_write,
  4745. },
  4746. {
  4747. .name = "zswap.writeback",
  4748. .seq_show = zswap_writeback_show,
  4749. .write = zswap_writeback_write,
  4750. },
  4751. { } /* terminate */
  4752. };
  4753. #endif /* CONFIG_ZSWAP */
  4754. static int __init mem_cgroup_swap_init(void)
  4755. {
  4756. if (mem_cgroup_disabled())
  4757. return 0;
  4758. WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, swap_files));
  4759. #ifdef CONFIG_MEMCG_V1
  4760. WARN_ON(cgroup_add_legacy_cftypes(&memory_cgrp_subsys, memsw_files));
  4761. #endif
  4762. #ifdef CONFIG_ZSWAP
  4763. WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, zswap_files));
  4764. #endif
  4765. return 0;
  4766. }
  4767. subsys_initcall(mem_cgroup_swap_init);
  4768. #endif /* CONFIG_SWAP */
  4769. void mem_cgroup_node_filter_allowed(struct mem_cgroup *memcg, nodemask_t *mask)
  4770. {
  4771. nodemask_t allowed;
  4772. if (!memcg)
  4773. return;
  4774. /*
  4775. * Since this interface is intended for use by migration paths, and
  4776. * reclaim and migration are subject to race conditions such as changes
  4777. * in effective_mems and hot-unpluging of nodes, inaccurate allowed
  4778. * mask is acceptable.
  4779. */
  4780. cpuset_nodes_allowed(memcg->css.cgroup, &allowed);
  4781. nodes_and(*mask, *mask, allowed);
  4782. }
  4783. void mem_cgroup_show_protected_memory(struct mem_cgroup *memcg)
  4784. {
  4785. if (mem_cgroup_disabled() || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
  4786. return;
  4787. if (!memcg)
  4788. memcg = root_mem_cgroup;
  4789. pr_warn("Memory cgroup min protection %lukB -- low protection %lukB",
  4790. K(atomic_long_read(&memcg->memory.children_min_usage)),
  4791. K(atomic_long_read(&memcg->memory.children_low_usage)));
  4792. }