memcontrol.c 142 KB

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