memcontrol.c 201 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829
  1. // SPDX-License-Identifier: GPL-2.0-or-later
  2. /* memcontrol.c - Memory Controller
  3. *
  4. * Copyright IBM Corporation, 2007
  5. * Author Balbir Singh <[email protected]>
  6. *
  7. * Copyright 2007 OpenVZ SWsoft Inc
  8. * Author: Pavel Emelianov <[email protected]>
  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/page_counter.h>
  28. #include <linux/memcontrol.h>
  29. #include <linux/cgroup.h>
  30. #include <linux/pagewalk.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/vm_event_item.h>
  36. #include <linux/smp.h>
  37. #include <linux/page-flags.h>
  38. #include <linux/backing-dev.h>
  39. #include <linux/bit_spinlock.h>
  40. #include <linux/rcupdate.h>
  41. #include <linux/limits.h>
  42. #include <linux/export.h>
  43. #include <linux/mutex.h>
  44. #include <linux/rbtree.h>
  45. #include <linux/slab.h>
  46. #include <linux/swap.h>
  47. #include <linux/swapops.h>
  48. #include <linux/spinlock.h>
  49. #include <linux/eventfd.h>
  50. #include <linux/poll.h>
  51. #include <linux/sort.h>
  52. #include <linux/fs.h>
  53. #include <linux/seq_file.h>
  54. #include <linux/vmpressure.h>
  55. #include <linux/memremap.h>
  56. #include <linux/mm_inline.h>
  57. #include <linux/swap_cgroup.h>
  58. #include <linux/cpu.h>
  59. #include <linux/oom.h>
  60. #include <linux/lockdep.h>
  61. #include <linux/file.h>
  62. #include <linux/resume_user_mode.h>
  63. #include <linux/psi.h>
  64. #include <linux/seq_buf.h>
  65. #include "internal.h"
  66. #include <net/sock.h>
  67. #include <net/ip.h>
  68. #include "slab.h"
  69. #include "swap.h"
  70. #include <linux/uaccess.h>
  71. #include <trace/events/vmscan.h>
  72. #include <trace/hooks/mm.h>
  73. struct cgroup_subsys memory_cgrp_subsys __read_mostly;
  74. EXPORT_SYMBOL(memory_cgrp_subsys);
  75. struct mem_cgroup *root_mem_cgroup __read_mostly;
  76. EXPORT_SYMBOL_GPL(root_mem_cgroup);
  77. /* Active memory cgroup to use from an interrupt context */
  78. DEFINE_PER_CPU(struct mem_cgroup *, int_active_memcg);
  79. EXPORT_PER_CPU_SYMBOL_GPL(int_active_memcg);
  80. /* Socket memory accounting disabled? */
  81. static bool cgroup_memory_nosocket __ro_after_init;
  82. /* Kernel memory accounting disabled? */
  83. static bool cgroup_memory_nokmem __ro_after_init;
  84. #ifdef CONFIG_CGROUP_WRITEBACK
  85. static DECLARE_WAIT_QUEUE_HEAD(memcg_cgwb_frn_waitq);
  86. #endif
  87. /* Whether legacy memory+swap accounting is active */
  88. static bool do_memsw_account(void)
  89. {
  90. return !cgroup_subsys_on_dfl(memory_cgrp_subsys);
  91. }
  92. #define THRESHOLDS_EVENTS_TARGET 128
  93. #define SOFTLIMIT_EVENTS_TARGET 1024
  94. /*
  95. * Cgroups above their limits are maintained in a RB-Tree, independent of
  96. * their hierarchy representation
  97. */
  98. struct mem_cgroup_tree_per_node {
  99. struct rb_root rb_root;
  100. struct rb_node *rb_rightmost;
  101. spinlock_t lock;
  102. };
  103. struct mem_cgroup_tree {
  104. struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
  105. };
  106. static struct mem_cgroup_tree soft_limit_tree __read_mostly;
  107. /* for OOM */
  108. struct mem_cgroup_eventfd_list {
  109. struct list_head list;
  110. struct eventfd_ctx *eventfd;
  111. };
  112. /*
  113. * cgroup_event represents events which userspace want to receive.
  114. */
  115. struct mem_cgroup_event {
  116. /*
  117. * memcg which the event belongs to.
  118. */
  119. struct mem_cgroup *memcg;
  120. /*
  121. * eventfd to signal userspace about the event.
  122. */
  123. struct eventfd_ctx *eventfd;
  124. /*
  125. * Each of these stored in a list by the cgroup.
  126. */
  127. struct list_head list;
  128. /*
  129. * register_event() callback will be used to add new userspace
  130. * waiter for changes related to this event. Use eventfd_signal()
  131. * on eventfd to send notification to userspace.
  132. */
  133. int (*register_event)(struct mem_cgroup *memcg,
  134. struct eventfd_ctx *eventfd, const char *args);
  135. /*
  136. * unregister_event() callback will be called when userspace closes
  137. * the eventfd or on cgroup removing. This callback must be set,
  138. * if you want provide notification functionality.
  139. */
  140. void (*unregister_event)(struct mem_cgroup *memcg,
  141. struct eventfd_ctx *eventfd);
  142. /*
  143. * All fields below needed to unregister event when
  144. * userspace closes eventfd.
  145. */
  146. poll_table pt;
  147. wait_queue_head_t *wqh;
  148. wait_queue_entry_t wait;
  149. struct work_struct remove;
  150. };
  151. static void mem_cgroup_threshold(struct mem_cgroup *memcg);
  152. static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
  153. /* Stuffs for move charges at task migration. */
  154. /*
  155. * Types of charges to be moved.
  156. */
  157. #define MOVE_ANON 0x1U
  158. #define MOVE_FILE 0x2U
  159. #define MOVE_MASK (MOVE_ANON | MOVE_FILE)
  160. /* "mc" and its members are protected by cgroup_mutex */
  161. static struct move_charge_struct {
  162. spinlock_t lock; /* for from, to */
  163. struct mm_struct *mm;
  164. struct mem_cgroup *from;
  165. struct mem_cgroup *to;
  166. unsigned long flags;
  167. unsigned long precharge;
  168. unsigned long moved_charge;
  169. unsigned long moved_swap;
  170. struct task_struct *moving_task; /* a task moving charges */
  171. wait_queue_head_t waitq; /* a waitq for other context */
  172. } mc = {
  173. .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
  174. .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
  175. };
  176. /*
  177. * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
  178. * limit reclaim to prevent infinite loops, if they ever occur.
  179. */
  180. #define MEM_CGROUP_MAX_RECLAIM_LOOPS 100
  181. #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS 2
  182. /* for encoding cft->private value on file */
  183. enum res_type {
  184. _MEM,
  185. _MEMSWAP,
  186. _KMEM,
  187. _TCP,
  188. };
  189. #define MEMFILE_PRIVATE(x, val) ((x) << 16 | (val))
  190. #define MEMFILE_TYPE(val) ((val) >> 16 & 0xffff)
  191. #define MEMFILE_ATTR(val) ((val) & 0xffff)
  192. /*
  193. * Iteration constructs for visiting all cgroups (under a tree). If
  194. * loops are exited prematurely (break), mem_cgroup_iter_break() must
  195. * be used for reference counting.
  196. */
  197. #define for_each_mem_cgroup_tree(iter, root) \
  198. for (iter = mem_cgroup_iter(root, NULL, NULL); \
  199. iter != NULL; \
  200. iter = mem_cgroup_iter(root, iter, NULL))
  201. #define for_each_mem_cgroup(iter) \
  202. for (iter = mem_cgroup_iter(NULL, NULL, NULL); \
  203. iter != NULL; \
  204. iter = mem_cgroup_iter(NULL, iter, NULL))
  205. static inline bool task_is_dying(void)
  206. {
  207. return tsk_is_oom_victim(current) || fatal_signal_pending(current) ||
  208. (current->flags & PF_EXITING);
  209. }
  210. /* Some nice accessors for the vmpressure. */
  211. struct vmpressure *memcg_to_vmpressure(struct mem_cgroup *memcg)
  212. {
  213. if (!memcg)
  214. memcg = root_mem_cgroup;
  215. return &memcg->vmpressure;
  216. }
  217. struct mem_cgroup *vmpressure_to_memcg(struct vmpressure *vmpr)
  218. {
  219. return container_of(vmpr, struct mem_cgroup, vmpressure);
  220. }
  221. #ifdef CONFIG_MEMCG_KMEM
  222. static DEFINE_SPINLOCK(objcg_lock);
  223. bool mem_cgroup_kmem_disabled(void)
  224. {
  225. return cgroup_memory_nokmem;
  226. }
  227. static void obj_cgroup_uncharge_pages(struct obj_cgroup *objcg,
  228. unsigned int nr_pages);
  229. static void obj_cgroup_release(struct percpu_ref *ref)
  230. {
  231. struct obj_cgroup *objcg = container_of(ref, struct obj_cgroup, refcnt);
  232. unsigned int nr_bytes;
  233. unsigned int nr_pages;
  234. unsigned long flags;
  235. /*
  236. * At this point all allocated objects are freed, and
  237. * objcg->nr_charged_bytes can't have an arbitrary byte value.
  238. * However, it can be PAGE_SIZE or (x * PAGE_SIZE).
  239. *
  240. * The following sequence can lead to it:
  241. * 1) CPU0: objcg == stock->cached_objcg
  242. * 2) CPU1: we do a small allocation (e.g. 92 bytes),
  243. * PAGE_SIZE bytes are charged
  244. * 3) CPU1: a process from another memcg is allocating something,
  245. * the stock if flushed,
  246. * objcg->nr_charged_bytes = PAGE_SIZE - 92
  247. * 5) CPU0: we do release this object,
  248. * 92 bytes are added to stock->nr_bytes
  249. * 6) CPU0: stock is flushed,
  250. * 92 bytes are added to objcg->nr_charged_bytes
  251. *
  252. * In the result, nr_charged_bytes == PAGE_SIZE.
  253. * This page will be uncharged in obj_cgroup_release().
  254. */
  255. nr_bytes = atomic_read(&objcg->nr_charged_bytes);
  256. WARN_ON_ONCE(nr_bytes & (PAGE_SIZE - 1));
  257. nr_pages = nr_bytes >> PAGE_SHIFT;
  258. if (nr_pages)
  259. obj_cgroup_uncharge_pages(objcg, nr_pages);
  260. spin_lock_irqsave(&objcg_lock, flags);
  261. list_del(&objcg->list);
  262. spin_unlock_irqrestore(&objcg_lock, flags);
  263. percpu_ref_exit(ref);
  264. kfree_rcu(objcg, rcu);
  265. }
  266. static struct obj_cgroup *obj_cgroup_alloc(void)
  267. {
  268. struct obj_cgroup *objcg;
  269. int ret;
  270. objcg = kzalloc(sizeof(struct obj_cgroup), GFP_KERNEL);
  271. if (!objcg)
  272. return NULL;
  273. ret = percpu_ref_init(&objcg->refcnt, obj_cgroup_release, 0,
  274. GFP_KERNEL);
  275. if (ret) {
  276. kfree(objcg);
  277. return NULL;
  278. }
  279. INIT_LIST_HEAD(&objcg->list);
  280. return objcg;
  281. }
  282. static void memcg_reparent_objcgs(struct mem_cgroup *memcg,
  283. struct mem_cgroup *parent)
  284. {
  285. struct obj_cgroup *objcg, *iter;
  286. objcg = rcu_replace_pointer(memcg->objcg, NULL, true);
  287. spin_lock_irq(&objcg_lock);
  288. /* 1) Ready to reparent active objcg. */
  289. list_add(&objcg->list, &memcg->objcg_list);
  290. /* 2) Reparent active objcg and already reparented objcgs to parent. */
  291. list_for_each_entry(iter, &memcg->objcg_list, list)
  292. WRITE_ONCE(iter->memcg, parent);
  293. /* 3) Move already reparented objcgs to the parent's list */
  294. list_splice(&memcg->objcg_list, &parent->objcg_list);
  295. spin_unlock_irq(&objcg_lock);
  296. percpu_ref_kill(&objcg->refcnt);
  297. }
  298. /*
  299. * A lot of the calls to the cache allocation functions are expected to be
  300. * inlined by the compiler. Since the calls to memcg_slab_pre_alloc_hook() are
  301. * conditional to this static branch, we'll have to allow modules that does
  302. * kmem_cache_alloc and the such to see this symbol as well
  303. */
  304. DEFINE_STATIC_KEY_FALSE(memcg_kmem_enabled_key);
  305. EXPORT_SYMBOL(memcg_kmem_enabled_key);
  306. #endif
  307. /**
  308. * mem_cgroup_css_from_page - css of the memcg associated with a page
  309. * @page: page of interest
  310. *
  311. * If memcg is bound to the default hierarchy, css of the memcg associated
  312. * with @page is returned. The returned css remains associated with @page
  313. * until it is released.
  314. *
  315. * If memcg is bound to a traditional hierarchy, the css of root_mem_cgroup
  316. * is returned.
  317. */
  318. struct cgroup_subsys_state *mem_cgroup_css_from_page(struct page *page)
  319. {
  320. struct mem_cgroup *memcg;
  321. memcg = page_memcg(page);
  322. if (!memcg || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
  323. memcg = root_mem_cgroup;
  324. return &memcg->css;
  325. }
  326. /**
  327. * page_cgroup_ino - return inode number of the memcg a page is charged to
  328. * @page: the page
  329. *
  330. * Look up the closest online ancestor of the memory cgroup @page is charged to
  331. * and return its inode number or 0 if @page is not charged to any cgroup. It
  332. * is safe to call this function without holding a reference to @page.
  333. *
  334. * Note, this function is inherently racy, because there is nothing to prevent
  335. * the cgroup inode from getting torn down and potentially reallocated a moment
  336. * after page_cgroup_ino() returns, so it only should be used by callers that
  337. * do not care (such as procfs interfaces).
  338. */
  339. ino_t page_cgroup_ino(struct page *page)
  340. {
  341. struct mem_cgroup *memcg;
  342. unsigned long ino = 0;
  343. rcu_read_lock();
  344. memcg = page_memcg_check(page);
  345. while (memcg && !(memcg->css.flags & CSS_ONLINE))
  346. memcg = parent_mem_cgroup(memcg);
  347. if (memcg)
  348. ino = cgroup_ino(memcg->css.cgroup);
  349. rcu_read_unlock();
  350. return ino;
  351. }
  352. static void __mem_cgroup_insert_exceeded(struct mem_cgroup_per_node *mz,
  353. struct mem_cgroup_tree_per_node *mctz,
  354. unsigned long new_usage_in_excess)
  355. {
  356. struct rb_node **p = &mctz->rb_root.rb_node;
  357. struct rb_node *parent = NULL;
  358. struct mem_cgroup_per_node *mz_node;
  359. bool rightmost = true;
  360. if (mz->on_tree)
  361. return;
  362. mz->usage_in_excess = new_usage_in_excess;
  363. if (!mz->usage_in_excess)
  364. return;
  365. while (*p) {
  366. parent = *p;
  367. mz_node = rb_entry(parent, struct mem_cgroup_per_node,
  368. tree_node);
  369. if (mz->usage_in_excess < mz_node->usage_in_excess) {
  370. p = &(*p)->rb_left;
  371. rightmost = false;
  372. } else {
  373. p = &(*p)->rb_right;
  374. }
  375. }
  376. if (rightmost)
  377. mctz->rb_rightmost = &mz->tree_node;
  378. rb_link_node(&mz->tree_node, parent, p);
  379. rb_insert_color(&mz->tree_node, &mctz->rb_root);
  380. mz->on_tree = true;
  381. }
  382. static void __mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
  383. struct mem_cgroup_tree_per_node *mctz)
  384. {
  385. if (!mz->on_tree)
  386. return;
  387. if (&mz->tree_node == mctz->rb_rightmost)
  388. mctz->rb_rightmost = rb_prev(&mz->tree_node);
  389. rb_erase(&mz->tree_node, &mctz->rb_root);
  390. mz->on_tree = false;
  391. }
  392. static void mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
  393. struct mem_cgroup_tree_per_node *mctz)
  394. {
  395. unsigned long flags;
  396. spin_lock_irqsave(&mctz->lock, flags);
  397. __mem_cgroup_remove_exceeded(mz, mctz);
  398. spin_unlock_irqrestore(&mctz->lock, flags);
  399. }
  400. static unsigned long soft_limit_excess(struct mem_cgroup *memcg)
  401. {
  402. unsigned long nr_pages = page_counter_read(&memcg->memory);
  403. unsigned long soft_limit = READ_ONCE(memcg->soft_limit);
  404. unsigned long excess = 0;
  405. if (nr_pages > soft_limit)
  406. excess = nr_pages - soft_limit;
  407. return excess;
  408. }
  409. static void mem_cgroup_update_tree(struct mem_cgroup *memcg, int nid)
  410. {
  411. unsigned long excess;
  412. struct mem_cgroup_per_node *mz;
  413. struct mem_cgroup_tree_per_node *mctz;
  414. if (lru_gen_enabled()) {
  415. if (soft_limit_excess(memcg))
  416. lru_gen_soft_reclaim(&memcg->nodeinfo[nid]->lruvec);
  417. return;
  418. }
  419. mctz = soft_limit_tree.rb_tree_per_node[nid];
  420. if (!mctz)
  421. return;
  422. /*
  423. * Necessary to update all ancestors when hierarchy is used.
  424. * because their event counter is not touched.
  425. */
  426. for (; memcg; memcg = parent_mem_cgroup(memcg)) {
  427. mz = memcg->nodeinfo[nid];
  428. excess = soft_limit_excess(memcg);
  429. /*
  430. * We have to update the tree if mz is on RB-tree or
  431. * mem is over its softlimit.
  432. */
  433. if (excess || mz->on_tree) {
  434. unsigned long flags;
  435. spin_lock_irqsave(&mctz->lock, flags);
  436. /* if on-tree, remove it */
  437. if (mz->on_tree)
  438. __mem_cgroup_remove_exceeded(mz, mctz);
  439. /*
  440. * Insert again. mz->usage_in_excess will be updated.
  441. * If excess is 0, no tree ops.
  442. */
  443. __mem_cgroup_insert_exceeded(mz, mctz, excess);
  444. spin_unlock_irqrestore(&mctz->lock, flags);
  445. }
  446. }
  447. }
  448. static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
  449. {
  450. struct mem_cgroup_tree_per_node *mctz;
  451. struct mem_cgroup_per_node *mz;
  452. int nid;
  453. for_each_node(nid) {
  454. mz = memcg->nodeinfo[nid];
  455. mctz = soft_limit_tree.rb_tree_per_node[nid];
  456. if (mctz)
  457. mem_cgroup_remove_exceeded(mz, mctz);
  458. }
  459. }
  460. static struct mem_cgroup_per_node *
  461. __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
  462. {
  463. struct mem_cgroup_per_node *mz;
  464. retry:
  465. mz = NULL;
  466. if (!mctz->rb_rightmost)
  467. goto done; /* Nothing to reclaim from */
  468. mz = rb_entry(mctz->rb_rightmost,
  469. struct mem_cgroup_per_node, tree_node);
  470. /*
  471. * Remove the node now but someone else can add it back,
  472. * we will to add it back at the end of reclaim to its correct
  473. * position in the tree.
  474. */
  475. __mem_cgroup_remove_exceeded(mz, mctz);
  476. if (!soft_limit_excess(mz->memcg) ||
  477. !css_tryget(&mz->memcg->css))
  478. goto retry;
  479. done:
  480. return mz;
  481. }
  482. static struct mem_cgroup_per_node *
  483. mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
  484. {
  485. struct mem_cgroup_per_node *mz;
  486. spin_lock_irq(&mctz->lock);
  487. mz = __mem_cgroup_largest_soft_limit_node(mctz);
  488. spin_unlock_irq(&mctz->lock);
  489. return mz;
  490. }
  491. /*
  492. * memcg and lruvec stats flushing
  493. *
  494. * Many codepaths leading to stats update or read are performance sensitive and
  495. * adding stats flushing in such codepaths is not desirable. So, to optimize the
  496. * flushing the kernel does:
  497. *
  498. * 1) Periodically and asynchronously flush the stats every 2 seconds to not let
  499. * rstat update tree grow unbounded.
  500. *
  501. * 2) Flush the stats synchronously on reader side only when there are more than
  502. * (MEMCG_CHARGE_BATCH * nr_cpus) update events. Though this optimization
  503. * will let stats be out of sync by atmost (MEMCG_CHARGE_BATCH * nr_cpus) but
  504. * only for 2 seconds due to (1).
  505. */
  506. static void flush_memcg_stats_dwork(struct work_struct *w);
  507. static DECLARE_DEFERRABLE_WORK(stats_flush_dwork, flush_memcg_stats_dwork);
  508. static DEFINE_SPINLOCK(stats_flush_lock);
  509. static DEFINE_PER_CPU(unsigned int, stats_updates);
  510. static atomic_t stats_flush_threshold = ATOMIC_INIT(0);
  511. static u64 flush_next_time;
  512. #define FLUSH_TIME (2UL*HZ)
  513. /*
  514. * Accessors to ensure that preemption is disabled on PREEMPT_RT because it can
  515. * not rely on this as part of an acquired spinlock_t lock. These functions are
  516. * never used in hardirq context on PREEMPT_RT and therefore disabling preemtion
  517. * is sufficient.
  518. */
  519. static void memcg_stats_lock(void)
  520. {
  521. preempt_disable_nested();
  522. VM_WARN_ON_IRQS_ENABLED();
  523. }
  524. static void __memcg_stats_lock(void)
  525. {
  526. preempt_disable_nested();
  527. }
  528. static void memcg_stats_unlock(void)
  529. {
  530. preempt_enable_nested();
  531. }
  532. static inline void memcg_rstat_updated(struct mem_cgroup *memcg, int val)
  533. {
  534. unsigned int x;
  535. cgroup_rstat_updated(memcg->css.cgroup, smp_processor_id());
  536. x = __this_cpu_add_return(stats_updates, abs(val));
  537. if (x > MEMCG_CHARGE_BATCH) {
  538. /*
  539. * If stats_flush_threshold exceeds the threshold
  540. * (>num_online_cpus()), cgroup stats update will be triggered
  541. * in __mem_cgroup_flush_stats(). Increasing this var further
  542. * is redundant and simply adds overhead in atomic update.
  543. */
  544. if (atomic_read(&stats_flush_threshold) <= num_online_cpus())
  545. atomic_add(x / MEMCG_CHARGE_BATCH, &stats_flush_threshold);
  546. __this_cpu_write(stats_updates, 0);
  547. }
  548. }
  549. static void __mem_cgroup_flush_stats(void)
  550. {
  551. unsigned long flag;
  552. if (!spin_trylock_irqsave(&stats_flush_lock, flag))
  553. return;
  554. flush_next_time = jiffies_64 + 2*FLUSH_TIME;
  555. cgroup_rstat_flush_irqsafe(root_mem_cgroup->css.cgroup);
  556. atomic_set(&stats_flush_threshold, 0);
  557. spin_unlock_irqrestore(&stats_flush_lock, flag);
  558. }
  559. void mem_cgroup_flush_stats(void)
  560. {
  561. if (atomic_read(&stats_flush_threshold) > num_online_cpus())
  562. __mem_cgroup_flush_stats();
  563. }
  564. void mem_cgroup_flush_stats_delayed(void)
  565. {
  566. if (time_after64(jiffies_64, flush_next_time))
  567. mem_cgroup_flush_stats();
  568. }
  569. static void flush_memcg_stats_dwork(struct work_struct *w)
  570. {
  571. __mem_cgroup_flush_stats();
  572. queue_delayed_work(system_unbound_wq, &stats_flush_dwork, FLUSH_TIME);
  573. }
  574. /* Subset of vm_event_item to report for memcg event stats */
  575. static const unsigned int memcg_vm_event_stat[] = {
  576. PGPGIN,
  577. PGPGOUT,
  578. PGSCAN_KSWAPD,
  579. PGSCAN_DIRECT,
  580. PGSTEAL_KSWAPD,
  581. PGSTEAL_DIRECT,
  582. PGFAULT,
  583. PGMAJFAULT,
  584. PGREFILL,
  585. PGACTIVATE,
  586. PGDEACTIVATE,
  587. PGLAZYFREE,
  588. PGLAZYFREED,
  589. #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
  590. ZSWPIN,
  591. ZSWPOUT,
  592. #endif
  593. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  594. THP_FAULT_ALLOC,
  595. THP_COLLAPSE_ALLOC,
  596. #endif
  597. };
  598. #define NR_MEMCG_EVENTS ARRAY_SIZE(memcg_vm_event_stat)
  599. static int mem_cgroup_events_index[NR_VM_EVENT_ITEMS] __read_mostly;
  600. static void init_memcg_events(void)
  601. {
  602. int i;
  603. for (i = 0; i < NR_MEMCG_EVENTS; ++i)
  604. mem_cgroup_events_index[memcg_vm_event_stat[i]] = i + 1;
  605. }
  606. static inline int memcg_events_index(enum vm_event_item idx)
  607. {
  608. return mem_cgroup_events_index[idx] - 1;
  609. }
  610. struct memcg_vmstats_percpu {
  611. /* Local (CPU and cgroup) page state & events */
  612. long state[MEMCG_NR_STAT];
  613. unsigned long events[NR_MEMCG_EVENTS];
  614. /* Delta calculation for lockless upward propagation */
  615. long state_prev[MEMCG_NR_STAT];
  616. unsigned long events_prev[NR_MEMCG_EVENTS];
  617. /* Cgroup1: threshold notifications & softlimit tree updates */
  618. unsigned long nr_page_events;
  619. unsigned long targets[MEM_CGROUP_NTARGETS];
  620. };
  621. struct memcg_vmstats {
  622. /* Aggregated (CPU and subtree) page state & events */
  623. long state[MEMCG_NR_STAT];
  624. unsigned long events[NR_MEMCG_EVENTS];
  625. /* Pending child counts during tree propagation */
  626. long state_pending[MEMCG_NR_STAT];
  627. unsigned long events_pending[NR_MEMCG_EVENTS];
  628. };
  629. unsigned long memcg_page_state(struct mem_cgroup *memcg, int idx)
  630. {
  631. long x = READ_ONCE(memcg->vmstats->state[idx]);
  632. #ifdef CONFIG_SMP
  633. if (x < 0)
  634. x = 0;
  635. #endif
  636. return x;
  637. }
  638. /**
  639. * __mod_memcg_state - update cgroup memory statistics
  640. * @memcg: the memory cgroup
  641. * @idx: the stat item - can be enum memcg_stat_item or enum node_stat_item
  642. * @val: delta to add to the counter, can be negative
  643. */
  644. void __mod_memcg_state(struct mem_cgroup *memcg, int idx, int val)
  645. {
  646. if (mem_cgroup_disabled())
  647. return;
  648. __this_cpu_add(memcg->vmstats_percpu->state[idx], val);
  649. memcg_rstat_updated(memcg, val);
  650. }
  651. /* idx can be of type enum memcg_stat_item or node_stat_item. */
  652. static unsigned long memcg_page_state_local(struct mem_cgroup *memcg, int idx)
  653. {
  654. long x = 0;
  655. int cpu;
  656. for_each_possible_cpu(cpu)
  657. x += per_cpu(memcg->vmstats_percpu->state[idx], cpu);
  658. #ifdef CONFIG_SMP
  659. if (x < 0)
  660. x = 0;
  661. #endif
  662. return x;
  663. }
  664. void __mod_memcg_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
  665. int val)
  666. {
  667. struct mem_cgroup_per_node *pn;
  668. struct mem_cgroup *memcg;
  669. pn = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
  670. memcg = pn->memcg;
  671. /*
  672. * The caller from rmap relay on disabled preemption becase they never
  673. * update their counter from in-interrupt context. For these two
  674. * counters we check that the update is never performed from an
  675. * interrupt context while other caller need to have disabled interrupt.
  676. */
  677. __memcg_stats_lock();
  678. if (IS_ENABLED(CONFIG_DEBUG_VM)) {
  679. switch (idx) {
  680. case NR_ANON_MAPPED:
  681. case NR_FILE_MAPPED:
  682. case NR_ANON_THPS:
  683. case NR_SHMEM_PMDMAPPED:
  684. case NR_FILE_PMDMAPPED:
  685. WARN_ON_ONCE(!in_task());
  686. break;
  687. default:
  688. VM_WARN_ON_IRQS_ENABLED();
  689. }
  690. }
  691. /* Update memcg */
  692. __this_cpu_add(memcg->vmstats_percpu->state[idx], val);
  693. /* Update lruvec */
  694. __this_cpu_add(pn->lruvec_stats_percpu->state[idx], val);
  695. memcg_rstat_updated(memcg, val);
  696. memcg_stats_unlock();
  697. }
  698. /**
  699. * __mod_lruvec_state - update lruvec memory statistics
  700. * @lruvec: the lruvec
  701. * @idx: the stat item
  702. * @val: delta to add to the counter, can be negative
  703. *
  704. * The lruvec is the intersection of the NUMA node and a cgroup. This
  705. * function updates the all three counters that are affected by a
  706. * change of state at this level: per-node, per-cgroup, per-lruvec.
  707. */
  708. void __mod_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
  709. int val)
  710. {
  711. /* Update node */
  712. __mod_node_page_state(lruvec_pgdat(lruvec), idx, val);
  713. /* Update memcg and lruvec */
  714. if (!mem_cgroup_disabled())
  715. __mod_memcg_lruvec_state(lruvec, idx, val);
  716. }
  717. EXPORT_SYMBOL_GPL(__mod_lruvec_state);
  718. void __mod_lruvec_page_state(struct page *page, enum node_stat_item idx,
  719. int val)
  720. {
  721. struct page *head = compound_head(page); /* rmap on tail pages */
  722. struct mem_cgroup *memcg;
  723. pg_data_t *pgdat = page_pgdat(page);
  724. struct lruvec *lruvec;
  725. rcu_read_lock();
  726. memcg = page_memcg(head);
  727. /* Untracked pages have no memcg, no lruvec. Update only the node */
  728. if (!memcg) {
  729. rcu_read_unlock();
  730. __mod_node_page_state(pgdat, idx, val);
  731. return;
  732. }
  733. lruvec = mem_cgroup_lruvec(memcg, pgdat);
  734. __mod_lruvec_state(lruvec, idx, val);
  735. rcu_read_unlock();
  736. }
  737. EXPORT_SYMBOL(__mod_lruvec_page_state);
  738. void __mod_lruvec_kmem_state(void *p, enum node_stat_item idx, int val)
  739. {
  740. pg_data_t *pgdat = page_pgdat(virt_to_page(p));
  741. struct mem_cgroup *memcg;
  742. struct lruvec *lruvec;
  743. rcu_read_lock();
  744. memcg = mem_cgroup_from_slab_obj(p);
  745. /*
  746. * Untracked pages have no memcg, no lruvec. Update only the
  747. * node. If we reparent the slab objects to the root memcg,
  748. * when we free the slab object, we need to update the per-memcg
  749. * vmstats to keep it correct for the root memcg.
  750. */
  751. if (!memcg) {
  752. __mod_node_page_state(pgdat, idx, val);
  753. } else {
  754. lruvec = mem_cgroup_lruvec(memcg, pgdat);
  755. __mod_lruvec_state(lruvec, idx, val);
  756. }
  757. rcu_read_unlock();
  758. }
  759. /**
  760. * __count_memcg_events - account VM events in a cgroup
  761. * @memcg: the memory cgroup
  762. * @idx: the event item
  763. * @count: the number of events that occurred
  764. */
  765. void __count_memcg_events(struct mem_cgroup *memcg, enum vm_event_item idx,
  766. unsigned long count)
  767. {
  768. int index = memcg_events_index(idx);
  769. if (mem_cgroup_disabled() || index < 0)
  770. return;
  771. memcg_stats_lock();
  772. __this_cpu_add(memcg->vmstats_percpu->events[index], count);
  773. memcg_rstat_updated(memcg, count);
  774. memcg_stats_unlock();
  775. }
  776. static unsigned long memcg_events(struct mem_cgroup *memcg, int event)
  777. {
  778. int index = memcg_events_index(event);
  779. if (index < 0)
  780. return 0;
  781. return READ_ONCE(memcg->vmstats->events[index]);
  782. }
  783. static unsigned long memcg_events_local(struct mem_cgroup *memcg, int event)
  784. {
  785. long x = 0;
  786. int cpu;
  787. int index = memcg_events_index(event);
  788. if (index < 0)
  789. return 0;
  790. for_each_possible_cpu(cpu)
  791. x += per_cpu(memcg->vmstats_percpu->events[index], cpu);
  792. return x;
  793. }
  794. static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
  795. int nr_pages)
  796. {
  797. /* pagein of a big page is an event. So, ignore page size */
  798. if (nr_pages > 0)
  799. __count_memcg_events(memcg, PGPGIN, 1);
  800. else {
  801. __count_memcg_events(memcg, PGPGOUT, 1);
  802. nr_pages = -nr_pages; /* for event */
  803. }
  804. __this_cpu_add(memcg->vmstats_percpu->nr_page_events, nr_pages);
  805. }
  806. static bool mem_cgroup_event_ratelimit(struct mem_cgroup *memcg,
  807. enum mem_cgroup_events_target target)
  808. {
  809. unsigned long val, next;
  810. val = __this_cpu_read(memcg->vmstats_percpu->nr_page_events);
  811. next = __this_cpu_read(memcg->vmstats_percpu->targets[target]);
  812. /* from time_after() in jiffies.h */
  813. if ((long)(next - val) < 0) {
  814. switch (target) {
  815. case MEM_CGROUP_TARGET_THRESH:
  816. next = val + THRESHOLDS_EVENTS_TARGET;
  817. break;
  818. case MEM_CGROUP_TARGET_SOFTLIMIT:
  819. next = val + SOFTLIMIT_EVENTS_TARGET;
  820. break;
  821. default:
  822. break;
  823. }
  824. __this_cpu_write(memcg->vmstats_percpu->targets[target], next);
  825. return true;
  826. }
  827. return false;
  828. }
  829. /*
  830. * Check events in order.
  831. *
  832. */
  833. static void memcg_check_events(struct mem_cgroup *memcg, int nid)
  834. {
  835. if (IS_ENABLED(CONFIG_PREEMPT_RT))
  836. return;
  837. /* threshold event is triggered in finer grain than soft limit */
  838. if (unlikely(mem_cgroup_event_ratelimit(memcg,
  839. MEM_CGROUP_TARGET_THRESH))) {
  840. bool do_softlimit;
  841. do_softlimit = mem_cgroup_event_ratelimit(memcg,
  842. MEM_CGROUP_TARGET_SOFTLIMIT);
  843. mem_cgroup_threshold(memcg);
  844. if (unlikely(do_softlimit))
  845. mem_cgroup_update_tree(memcg, nid);
  846. }
  847. }
  848. struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
  849. {
  850. /*
  851. * mm_update_next_owner() may clear mm->owner to NULL
  852. * if it races with swapoff, page migration, etc.
  853. * So this can be called with p == NULL.
  854. */
  855. if (unlikely(!p))
  856. return NULL;
  857. return mem_cgroup_from_css(task_css(p, memory_cgrp_id));
  858. }
  859. EXPORT_SYMBOL(mem_cgroup_from_task);
  860. static __always_inline struct mem_cgroup *active_memcg(void)
  861. {
  862. if (!in_task())
  863. return this_cpu_read(int_active_memcg);
  864. else
  865. return current->active_memcg;
  866. }
  867. /**
  868. * get_mem_cgroup_from_mm: Obtain a reference on given mm_struct's memcg.
  869. * @mm: mm from which memcg should be extracted. It can be NULL.
  870. *
  871. * Obtain a reference on mm->memcg and returns it if successful. If mm
  872. * is NULL, then the memcg is chosen as follows:
  873. * 1) The active memcg, if set.
  874. * 2) current->mm->memcg, if available
  875. * 3) root memcg
  876. * If mem_cgroup is disabled, NULL is returned.
  877. */
  878. struct mem_cgroup *get_mem_cgroup_from_mm(struct mm_struct *mm)
  879. {
  880. struct mem_cgroup *memcg;
  881. if (mem_cgroup_disabled())
  882. return NULL;
  883. /*
  884. * Page cache insertions can happen without an
  885. * actual mm context, e.g. during disk probing
  886. * on boot, loopback IO, acct() writes etc.
  887. *
  888. * No need to css_get on root memcg as the reference
  889. * counting is disabled on the root level in the
  890. * cgroup core. See CSS_NO_REF.
  891. */
  892. if (unlikely(!mm)) {
  893. memcg = active_memcg();
  894. if (unlikely(memcg)) {
  895. /* remote memcg must hold a ref */
  896. css_get(&memcg->css);
  897. return memcg;
  898. }
  899. mm = current->mm;
  900. if (unlikely(!mm))
  901. return root_mem_cgroup;
  902. }
  903. rcu_read_lock();
  904. do {
  905. memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
  906. if (unlikely(!memcg))
  907. memcg = root_mem_cgroup;
  908. } while (!css_tryget(&memcg->css));
  909. rcu_read_unlock();
  910. return memcg;
  911. }
  912. EXPORT_SYMBOL(get_mem_cgroup_from_mm);
  913. static __always_inline bool memcg_kmem_bypass(void)
  914. {
  915. /* Allow remote memcg charging from any context. */
  916. if (unlikely(active_memcg()))
  917. return false;
  918. /* Memcg to charge can't be determined. */
  919. if (!in_task() || !current->mm || (current->flags & PF_KTHREAD))
  920. return true;
  921. return false;
  922. }
  923. /**
  924. * mem_cgroup_iter - iterate over memory cgroup hierarchy
  925. * @root: hierarchy root
  926. * @prev: previously returned memcg, NULL on first invocation
  927. * @reclaim: cookie for shared reclaim walks, NULL for full walks
  928. *
  929. * Returns references to children of the hierarchy below @root, or
  930. * @root itself, or %NULL after a full round-trip.
  931. *
  932. * Caller must pass the return value in @prev on subsequent
  933. * invocations for reference counting, or use mem_cgroup_iter_break()
  934. * to cancel a hierarchy walk before the round-trip is complete.
  935. *
  936. * Reclaimers can specify a node in @reclaim to divide up the memcgs
  937. * in the hierarchy among all concurrent reclaimers operating on the
  938. * same node.
  939. */
  940. struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
  941. struct mem_cgroup *prev,
  942. struct mem_cgroup_reclaim_cookie *reclaim)
  943. {
  944. struct mem_cgroup_reclaim_iter *iter;
  945. struct cgroup_subsys_state *css = NULL;
  946. struct mem_cgroup *memcg = NULL;
  947. struct mem_cgroup *pos = NULL;
  948. if (mem_cgroup_disabled())
  949. return NULL;
  950. if (!root)
  951. root = root_mem_cgroup;
  952. rcu_read_lock();
  953. if (reclaim) {
  954. struct mem_cgroup_per_node *mz;
  955. mz = root->nodeinfo[reclaim->pgdat->node_id];
  956. iter = &mz->iter;
  957. /*
  958. * On start, join the current reclaim iteration cycle.
  959. * Exit when a concurrent walker completes it.
  960. */
  961. if (!prev)
  962. reclaim->generation = iter->generation;
  963. else if (reclaim->generation != iter->generation)
  964. goto out_unlock;
  965. while (1) {
  966. pos = READ_ONCE(iter->position);
  967. if (!pos || css_tryget(&pos->css))
  968. break;
  969. /*
  970. * css reference reached zero, so iter->position will
  971. * be cleared by ->css_released. However, we should not
  972. * rely on this happening soon, because ->css_released
  973. * is called from a work queue, and by busy-waiting we
  974. * might block it. So we clear iter->position right
  975. * away.
  976. */
  977. (void)cmpxchg(&iter->position, pos, NULL);
  978. }
  979. } else if (prev) {
  980. pos = prev;
  981. }
  982. if (pos)
  983. css = &pos->css;
  984. for (;;) {
  985. css = css_next_descendant_pre(css, &root->css);
  986. if (!css) {
  987. /*
  988. * Reclaimers share the hierarchy walk, and a
  989. * new one might jump in right at the end of
  990. * the hierarchy - make sure they see at least
  991. * one group and restart from the beginning.
  992. */
  993. if (!prev)
  994. continue;
  995. break;
  996. }
  997. /*
  998. * Verify the css and acquire a reference. The root
  999. * is provided by the caller, so we know it's alive
  1000. * and kicking, and don't take an extra reference.
  1001. */
  1002. if (css == &root->css || css_tryget(css)) {
  1003. memcg = mem_cgroup_from_css(css);
  1004. break;
  1005. }
  1006. }
  1007. if (reclaim) {
  1008. /*
  1009. * The position could have already been updated by a competing
  1010. * thread, so check that the value hasn't changed since we read
  1011. * it to avoid reclaiming from the same cgroup twice.
  1012. */
  1013. (void)cmpxchg(&iter->position, pos, memcg);
  1014. if (pos)
  1015. css_put(&pos->css);
  1016. if (!memcg)
  1017. iter->generation++;
  1018. }
  1019. out_unlock:
  1020. rcu_read_unlock();
  1021. if (prev && prev != root)
  1022. css_put(&prev->css);
  1023. return memcg;
  1024. }
  1025. /**
  1026. * mem_cgroup_iter_break - abort a hierarchy walk prematurely
  1027. * @root: hierarchy root
  1028. * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
  1029. */
  1030. void mem_cgroup_iter_break(struct mem_cgroup *root,
  1031. struct mem_cgroup *prev)
  1032. {
  1033. if (!root)
  1034. root = root_mem_cgroup;
  1035. if (prev && prev != root)
  1036. css_put(&prev->css);
  1037. }
  1038. static void __invalidate_reclaim_iterators(struct mem_cgroup *from,
  1039. struct mem_cgroup *dead_memcg)
  1040. {
  1041. struct mem_cgroup_reclaim_iter *iter;
  1042. struct mem_cgroup_per_node *mz;
  1043. int nid;
  1044. for_each_node(nid) {
  1045. mz = from->nodeinfo[nid];
  1046. iter = &mz->iter;
  1047. cmpxchg(&iter->position, dead_memcg, NULL);
  1048. }
  1049. }
  1050. static void invalidate_reclaim_iterators(struct mem_cgroup *dead_memcg)
  1051. {
  1052. struct mem_cgroup *memcg = dead_memcg;
  1053. struct mem_cgroup *last;
  1054. do {
  1055. __invalidate_reclaim_iterators(memcg, dead_memcg);
  1056. last = memcg;
  1057. } while ((memcg = parent_mem_cgroup(memcg)));
  1058. /*
  1059. * When cgroup1 non-hierarchy mode is used,
  1060. * parent_mem_cgroup() does not walk all the way up to the
  1061. * cgroup root (root_mem_cgroup). So we have to handle
  1062. * dead_memcg from cgroup root separately.
  1063. */
  1064. if (last != root_mem_cgroup)
  1065. __invalidate_reclaim_iterators(root_mem_cgroup,
  1066. dead_memcg);
  1067. }
  1068. /**
  1069. * mem_cgroup_scan_tasks - iterate over tasks of a memory cgroup hierarchy
  1070. * @memcg: hierarchy root
  1071. * @fn: function to call for each task
  1072. * @arg: argument passed to @fn
  1073. *
  1074. * This function iterates over tasks attached to @memcg or to any of its
  1075. * descendants and calls @fn for each task. If @fn returns a non-zero
  1076. * value, the function breaks the iteration loop and returns the value.
  1077. * Otherwise, it will iterate over all tasks and return 0.
  1078. *
  1079. * This function must not be called for the root memory cgroup.
  1080. */
  1081. int mem_cgroup_scan_tasks(struct mem_cgroup *memcg,
  1082. int (*fn)(struct task_struct *, void *), void *arg)
  1083. {
  1084. struct mem_cgroup *iter;
  1085. int ret = 0;
  1086. BUG_ON(memcg == root_mem_cgroup);
  1087. for_each_mem_cgroup_tree(iter, memcg) {
  1088. struct css_task_iter it;
  1089. struct task_struct *task;
  1090. css_task_iter_start(&iter->css, CSS_TASK_ITER_PROCS, &it);
  1091. while (!ret && (task = css_task_iter_next(&it)))
  1092. ret = fn(task, arg);
  1093. css_task_iter_end(&it);
  1094. if (ret) {
  1095. mem_cgroup_iter_break(memcg, iter);
  1096. break;
  1097. }
  1098. }
  1099. return ret;
  1100. }
  1101. #ifdef CONFIG_DEBUG_VM
  1102. void lruvec_memcg_debug(struct lruvec *lruvec, struct folio *folio)
  1103. {
  1104. struct mem_cgroup *memcg;
  1105. if (mem_cgroup_disabled())
  1106. return;
  1107. memcg = folio_memcg(folio);
  1108. if (!memcg)
  1109. VM_BUG_ON_FOLIO(lruvec_memcg(lruvec) != root_mem_cgroup, folio);
  1110. else
  1111. VM_BUG_ON_FOLIO(lruvec_memcg(lruvec) != memcg, folio);
  1112. }
  1113. #endif
  1114. /**
  1115. * folio_lruvec_lock - Lock the lruvec for a folio.
  1116. * @folio: Pointer to the folio.
  1117. *
  1118. * These functions are safe to use under any of the following conditions:
  1119. * - folio locked
  1120. * - folio_test_lru false
  1121. * - folio_memcg_lock()
  1122. * - folio frozen (refcount of 0)
  1123. *
  1124. * Return: The lruvec this folio is on with its lock held.
  1125. */
  1126. struct lruvec *folio_lruvec_lock(struct folio *folio)
  1127. {
  1128. struct lruvec *lruvec = folio_lruvec(folio);
  1129. spin_lock(&lruvec->lru_lock);
  1130. lruvec_memcg_debug(lruvec, folio);
  1131. return lruvec;
  1132. }
  1133. /**
  1134. * folio_lruvec_lock_irq - Lock the lruvec for a folio.
  1135. * @folio: Pointer to the folio.
  1136. *
  1137. * These functions are safe to use under any of the following conditions:
  1138. * - folio locked
  1139. * - folio_test_lru false
  1140. * - folio_memcg_lock()
  1141. * - folio frozen (refcount of 0)
  1142. *
  1143. * Return: The lruvec this folio is on with its lock held and interrupts
  1144. * disabled.
  1145. */
  1146. struct lruvec *folio_lruvec_lock_irq(struct folio *folio)
  1147. {
  1148. struct lruvec *lruvec = folio_lruvec(folio);
  1149. spin_lock_irq(&lruvec->lru_lock);
  1150. lruvec_memcg_debug(lruvec, folio);
  1151. return lruvec;
  1152. }
  1153. /**
  1154. * folio_lruvec_lock_irqsave - Lock the lruvec for a folio.
  1155. * @folio: Pointer to the folio.
  1156. * @flags: Pointer to irqsave flags.
  1157. *
  1158. * These functions are safe to use under any of the following conditions:
  1159. * - folio locked
  1160. * - folio_test_lru false
  1161. * - folio_memcg_lock()
  1162. * - folio frozen (refcount of 0)
  1163. *
  1164. * Return: The lruvec this folio is on with its lock held and interrupts
  1165. * disabled.
  1166. */
  1167. struct lruvec *folio_lruvec_lock_irqsave(struct folio *folio,
  1168. unsigned long *flags)
  1169. {
  1170. struct lruvec *lruvec = folio_lruvec(folio);
  1171. spin_lock_irqsave(&lruvec->lru_lock, *flags);
  1172. lruvec_memcg_debug(lruvec, folio);
  1173. return lruvec;
  1174. }
  1175. /**
  1176. * mem_cgroup_update_lru_size - account for adding or removing an lru page
  1177. * @lruvec: mem_cgroup per zone lru vector
  1178. * @lru: index of lru list the page is sitting on
  1179. * @zid: zone id of the accounted pages
  1180. * @nr_pages: positive when adding or negative when removing
  1181. *
  1182. * This function must be called under lru_lock, just before a page is added
  1183. * to or just after a page is removed from an lru list.
  1184. */
  1185. void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
  1186. int zid, int nr_pages)
  1187. {
  1188. struct mem_cgroup_per_node *mz;
  1189. unsigned long *lru_size;
  1190. long size;
  1191. if (mem_cgroup_disabled())
  1192. return;
  1193. mz = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
  1194. lru_size = &mz->lru_zone_size[zid][lru];
  1195. if (nr_pages < 0)
  1196. *lru_size += nr_pages;
  1197. size = *lru_size;
  1198. if (WARN_ONCE(size < 0,
  1199. "%s(%p, %d, %d): lru_size %ld\n",
  1200. __func__, lruvec, lru, nr_pages, size)) {
  1201. VM_BUG_ON(1);
  1202. *lru_size = 0;
  1203. }
  1204. if (nr_pages > 0)
  1205. *lru_size += nr_pages;
  1206. }
  1207. EXPORT_SYMBOL_GPL(mem_cgroup_update_lru_size);
  1208. /**
  1209. * mem_cgroup_margin - calculate chargeable space of a memory cgroup
  1210. * @memcg: the memory cgroup
  1211. *
  1212. * Returns the maximum amount of memory @mem can be charged with, in
  1213. * pages.
  1214. */
  1215. static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
  1216. {
  1217. unsigned long margin = 0;
  1218. unsigned long count;
  1219. unsigned long limit;
  1220. count = page_counter_read(&memcg->memory);
  1221. limit = READ_ONCE(memcg->memory.max);
  1222. if (count < limit)
  1223. margin = limit - count;
  1224. if (do_memsw_account()) {
  1225. count = page_counter_read(&memcg->memsw);
  1226. limit = READ_ONCE(memcg->memsw.max);
  1227. if (count < limit)
  1228. margin = min(margin, limit - count);
  1229. else
  1230. margin = 0;
  1231. }
  1232. return margin;
  1233. }
  1234. /*
  1235. * A routine for checking "mem" is under move_account() or not.
  1236. *
  1237. * Checking a cgroup is mc.from or mc.to or under hierarchy of
  1238. * moving cgroups. This is for waiting at high-memory pressure
  1239. * caused by "move".
  1240. */
  1241. static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
  1242. {
  1243. struct mem_cgroup *from;
  1244. struct mem_cgroup *to;
  1245. bool ret = false;
  1246. /*
  1247. * Unlike task_move routines, we access mc.to, mc.from not under
  1248. * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
  1249. */
  1250. spin_lock(&mc.lock);
  1251. from = mc.from;
  1252. to = mc.to;
  1253. if (!from)
  1254. goto unlock;
  1255. ret = mem_cgroup_is_descendant(from, memcg) ||
  1256. mem_cgroup_is_descendant(to, memcg);
  1257. unlock:
  1258. spin_unlock(&mc.lock);
  1259. return ret;
  1260. }
  1261. static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
  1262. {
  1263. if (mc.moving_task && current != mc.moving_task) {
  1264. if (mem_cgroup_under_move(memcg)) {
  1265. DEFINE_WAIT(wait);
  1266. prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
  1267. /* moving charge context might have finished. */
  1268. if (mc.moving_task)
  1269. schedule();
  1270. finish_wait(&mc.waitq, &wait);
  1271. return true;
  1272. }
  1273. }
  1274. return false;
  1275. }
  1276. struct memory_stat {
  1277. const char *name;
  1278. unsigned int idx;
  1279. };
  1280. static const struct memory_stat memory_stats[] = {
  1281. { "anon", NR_ANON_MAPPED },
  1282. { "file", NR_FILE_PAGES },
  1283. { "kernel", MEMCG_KMEM },
  1284. { "kernel_stack", NR_KERNEL_STACK_KB },
  1285. { "pagetables", NR_PAGETABLE },
  1286. { "sec_pagetables", NR_SECONDARY_PAGETABLE },
  1287. { "percpu", MEMCG_PERCPU_B },
  1288. { "sock", MEMCG_SOCK },
  1289. { "vmalloc", MEMCG_VMALLOC },
  1290. { "shmem", NR_SHMEM },
  1291. #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
  1292. { "zswap", MEMCG_ZSWAP_B },
  1293. { "zswapped", MEMCG_ZSWAPPED },
  1294. #endif
  1295. { "file_mapped", NR_FILE_MAPPED },
  1296. { "file_dirty", NR_FILE_DIRTY },
  1297. { "file_writeback", NR_WRITEBACK },
  1298. #ifdef CONFIG_SWAP
  1299. { "swapcached", NR_SWAPCACHE },
  1300. #endif
  1301. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  1302. { "anon_thp", NR_ANON_THPS },
  1303. { "file_thp", NR_FILE_THPS },
  1304. { "shmem_thp", NR_SHMEM_THPS },
  1305. #endif
  1306. { "inactive_anon", NR_INACTIVE_ANON },
  1307. { "active_anon", NR_ACTIVE_ANON },
  1308. { "inactive_file", NR_INACTIVE_FILE },
  1309. { "active_file", NR_ACTIVE_FILE },
  1310. { "unevictable", NR_UNEVICTABLE },
  1311. { "slab_reclaimable", NR_SLAB_RECLAIMABLE_B },
  1312. { "slab_unreclaimable", NR_SLAB_UNRECLAIMABLE_B },
  1313. /* The memory events */
  1314. { "workingset_refault_anon", WORKINGSET_REFAULT_ANON },
  1315. { "workingset_refault_file", WORKINGSET_REFAULT_FILE },
  1316. { "workingset_activate_anon", WORKINGSET_ACTIVATE_ANON },
  1317. { "workingset_activate_file", WORKINGSET_ACTIVATE_FILE },
  1318. { "workingset_restore_anon", WORKINGSET_RESTORE_ANON },
  1319. { "workingset_restore_file", WORKINGSET_RESTORE_FILE },
  1320. { "workingset_nodereclaim", WORKINGSET_NODERECLAIM },
  1321. };
  1322. /* Translate stat items to the correct unit for memory.stat output */
  1323. static int memcg_page_state_unit(int item)
  1324. {
  1325. switch (item) {
  1326. case MEMCG_PERCPU_B:
  1327. case MEMCG_ZSWAP_B:
  1328. case NR_SLAB_RECLAIMABLE_B:
  1329. case NR_SLAB_UNRECLAIMABLE_B:
  1330. case WORKINGSET_REFAULT_ANON:
  1331. case WORKINGSET_REFAULT_FILE:
  1332. case WORKINGSET_ACTIVATE_ANON:
  1333. case WORKINGSET_ACTIVATE_FILE:
  1334. case WORKINGSET_RESTORE_ANON:
  1335. case WORKINGSET_RESTORE_FILE:
  1336. case WORKINGSET_NODERECLAIM:
  1337. return 1;
  1338. case NR_KERNEL_STACK_KB:
  1339. return SZ_1K;
  1340. default:
  1341. return PAGE_SIZE;
  1342. }
  1343. }
  1344. static inline unsigned long memcg_page_state_output(struct mem_cgroup *memcg,
  1345. int item)
  1346. {
  1347. return memcg_page_state(memcg, item) * memcg_page_state_unit(item);
  1348. }
  1349. static void memory_stat_format(struct mem_cgroup *memcg, char *buf, int bufsize)
  1350. {
  1351. struct seq_buf s;
  1352. int i;
  1353. seq_buf_init(&s, buf, bufsize);
  1354. /*
  1355. * Provide statistics on the state of the memory subsystem as
  1356. * well as cumulative event counters that show past behavior.
  1357. *
  1358. * This list is ordered following a combination of these gradients:
  1359. * 1) generic big picture -> specifics and details
  1360. * 2) reflecting userspace activity -> reflecting kernel heuristics
  1361. *
  1362. * Current memory state:
  1363. */
  1364. mem_cgroup_flush_stats();
  1365. for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
  1366. u64 size;
  1367. size = memcg_page_state_output(memcg, memory_stats[i].idx);
  1368. seq_buf_printf(&s, "%s %llu\n", memory_stats[i].name, size);
  1369. if (unlikely(memory_stats[i].idx == NR_SLAB_UNRECLAIMABLE_B)) {
  1370. size += memcg_page_state_output(memcg,
  1371. NR_SLAB_RECLAIMABLE_B);
  1372. seq_buf_printf(&s, "slab %llu\n", size);
  1373. }
  1374. }
  1375. /* Accumulated memory events */
  1376. seq_buf_printf(&s, "pgscan %lu\n",
  1377. memcg_events(memcg, PGSCAN_KSWAPD) +
  1378. memcg_events(memcg, PGSCAN_DIRECT));
  1379. seq_buf_printf(&s, "pgsteal %lu\n",
  1380. memcg_events(memcg, PGSTEAL_KSWAPD) +
  1381. memcg_events(memcg, PGSTEAL_DIRECT));
  1382. for (i = 0; i < ARRAY_SIZE(memcg_vm_event_stat); i++) {
  1383. if (memcg_vm_event_stat[i] == PGPGIN ||
  1384. memcg_vm_event_stat[i] == PGPGOUT)
  1385. continue;
  1386. seq_buf_printf(&s, "%s %lu\n",
  1387. vm_event_name(memcg_vm_event_stat[i]),
  1388. memcg_events(memcg, memcg_vm_event_stat[i]));
  1389. }
  1390. /* The above should easily fit into one page */
  1391. WARN_ON_ONCE(seq_buf_has_overflowed(&s));
  1392. }
  1393. #define K(x) ((x) << (PAGE_SHIFT-10))
  1394. /**
  1395. * mem_cgroup_print_oom_context: Print OOM information relevant to
  1396. * memory controller.
  1397. * @memcg: The memory cgroup that went over limit
  1398. * @p: Task that is going to be killed
  1399. *
  1400. * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
  1401. * enabled
  1402. */
  1403. void mem_cgroup_print_oom_context(struct mem_cgroup *memcg, struct task_struct *p)
  1404. {
  1405. rcu_read_lock();
  1406. if (memcg) {
  1407. pr_cont(",oom_memcg=");
  1408. pr_cont_cgroup_path(memcg->css.cgroup);
  1409. } else
  1410. pr_cont(",global_oom");
  1411. if (p) {
  1412. pr_cont(",task_memcg=");
  1413. pr_cont_cgroup_path(task_cgroup(p, memory_cgrp_id));
  1414. }
  1415. rcu_read_unlock();
  1416. }
  1417. /**
  1418. * mem_cgroup_print_oom_meminfo: Print OOM memory information relevant to
  1419. * memory controller.
  1420. * @memcg: The memory cgroup that went over limit
  1421. */
  1422. void mem_cgroup_print_oom_meminfo(struct mem_cgroup *memcg)
  1423. {
  1424. /* Use static buffer, for the caller is holding oom_lock. */
  1425. static char buf[PAGE_SIZE];
  1426. lockdep_assert_held(&oom_lock);
  1427. pr_info("memory: usage %llukB, limit %llukB, failcnt %lu\n",
  1428. K((u64)page_counter_read(&memcg->memory)),
  1429. K((u64)READ_ONCE(memcg->memory.max)), memcg->memory.failcnt);
  1430. if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
  1431. pr_info("swap: usage %llukB, limit %llukB, failcnt %lu\n",
  1432. K((u64)page_counter_read(&memcg->swap)),
  1433. K((u64)READ_ONCE(memcg->swap.max)), memcg->swap.failcnt);
  1434. else {
  1435. pr_info("memory+swap: usage %llukB, limit %llukB, failcnt %lu\n",
  1436. K((u64)page_counter_read(&memcg->memsw)),
  1437. K((u64)memcg->memsw.max), memcg->memsw.failcnt);
  1438. pr_info("kmem: usage %llukB, limit %llukB, failcnt %lu\n",
  1439. K((u64)page_counter_read(&memcg->kmem)),
  1440. K((u64)memcg->kmem.max), memcg->kmem.failcnt);
  1441. }
  1442. pr_info("Memory cgroup stats for ");
  1443. pr_cont_cgroup_path(memcg->css.cgroup);
  1444. pr_cont(":");
  1445. memory_stat_format(memcg, buf, sizeof(buf));
  1446. pr_info("%s", buf);
  1447. }
  1448. /*
  1449. * Return the memory (and swap, if configured) limit for a memcg.
  1450. */
  1451. unsigned long mem_cgroup_get_max(struct mem_cgroup *memcg)
  1452. {
  1453. unsigned long max = READ_ONCE(memcg->memory.max);
  1454. if (do_memsw_account()) {
  1455. if (mem_cgroup_swappiness(memcg)) {
  1456. /* Calculate swap excess capacity from memsw limit */
  1457. unsigned long swap = READ_ONCE(memcg->memsw.max) - max;
  1458. max += min(swap, (unsigned long)total_swap_pages);
  1459. }
  1460. } else {
  1461. if (mem_cgroup_swappiness(memcg))
  1462. max += min(READ_ONCE(memcg->swap.max),
  1463. (unsigned long)total_swap_pages);
  1464. }
  1465. return max;
  1466. }
  1467. unsigned long mem_cgroup_size(struct mem_cgroup *memcg)
  1468. {
  1469. return page_counter_read(&memcg->memory);
  1470. }
  1471. static bool mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
  1472. int order)
  1473. {
  1474. struct oom_control oc = {
  1475. .zonelist = NULL,
  1476. .nodemask = NULL,
  1477. .memcg = memcg,
  1478. .gfp_mask = gfp_mask,
  1479. .order = order,
  1480. };
  1481. bool ret = true;
  1482. if (mutex_lock_killable(&oom_lock))
  1483. return true;
  1484. if (mem_cgroup_margin(memcg) >= (1 << order))
  1485. goto unlock;
  1486. /*
  1487. * A few threads which were not waiting at mutex_lock_killable() can
  1488. * fail to bail out. Therefore, check again after holding oom_lock.
  1489. */
  1490. ret = task_is_dying() || out_of_memory(&oc);
  1491. unlock:
  1492. mutex_unlock(&oom_lock);
  1493. return ret;
  1494. }
  1495. static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg,
  1496. pg_data_t *pgdat,
  1497. gfp_t gfp_mask,
  1498. unsigned long *total_scanned)
  1499. {
  1500. struct mem_cgroup *victim = NULL;
  1501. int total = 0;
  1502. int loop = 0;
  1503. unsigned long excess;
  1504. unsigned long nr_scanned;
  1505. struct mem_cgroup_reclaim_cookie reclaim = {
  1506. .pgdat = pgdat,
  1507. };
  1508. excess = soft_limit_excess(root_memcg);
  1509. while (1) {
  1510. victim = mem_cgroup_iter(root_memcg, victim, &reclaim);
  1511. if (!victim) {
  1512. loop++;
  1513. if (loop >= 2) {
  1514. /*
  1515. * If we have not been able to reclaim
  1516. * anything, it might because there are
  1517. * no reclaimable pages under this hierarchy
  1518. */
  1519. if (!total)
  1520. break;
  1521. /*
  1522. * We want to do more targeted reclaim.
  1523. * excess >> 2 is not to excessive so as to
  1524. * reclaim too much, nor too less that we keep
  1525. * coming back to reclaim from this cgroup
  1526. */
  1527. if (total >= (excess >> 2) ||
  1528. (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS))
  1529. break;
  1530. }
  1531. continue;
  1532. }
  1533. total += mem_cgroup_shrink_node(victim, gfp_mask, false,
  1534. pgdat, &nr_scanned);
  1535. *total_scanned += nr_scanned;
  1536. if (!soft_limit_excess(root_memcg))
  1537. break;
  1538. }
  1539. mem_cgroup_iter_break(root_memcg, victim);
  1540. return total;
  1541. }
  1542. #ifdef CONFIG_LOCKDEP
  1543. static struct lockdep_map memcg_oom_lock_dep_map = {
  1544. .name = "memcg_oom_lock",
  1545. };
  1546. #endif
  1547. static DEFINE_SPINLOCK(memcg_oom_lock);
  1548. /*
  1549. * Check OOM-Killer is already running under our hierarchy.
  1550. * If someone is running, return false.
  1551. */
  1552. static bool mem_cgroup_oom_trylock(struct mem_cgroup *memcg)
  1553. {
  1554. struct mem_cgroup *iter, *failed = NULL;
  1555. spin_lock(&memcg_oom_lock);
  1556. for_each_mem_cgroup_tree(iter, memcg) {
  1557. if (iter->oom_lock) {
  1558. /*
  1559. * this subtree of our hierarchy is already locked
  1560. * so we cannot give a lock.
  1561. */
  1562. failed = iter;
  1563. mem_cgroup_iter_break(memcg, iter);
  1564. break;
  1565. } else
  1566. iter->oom_lock = true;
  1567. }
  1568. if (failed) {
  1569. /*
  1570. * OK, we failed to lock the whole subtree so we have
  1571. * to clean up what we set up to the failing subtree
  1572. */
  1573. for_each_mem_cgroup_tree(iter, memcg) {
  1574. if (iter == failed) {
  1575. mem_cgroup_iter_break(memcg, iter);
  1576. break;
  1577. }
  1578. iter->oom_lock = false;
  1579. }
  1580. } else
  1581. mutex_acquire(&memcg_oom_lock_dep_map, 0, 1, _RET_IP_);
  1582. spin_unlock(&memcg_oom_lock);
  1583. return !failed;
  1584. }
  1585. static void mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
  1586. {
  1587. struct mem_cgroup *iter;
  1588. spin_lock(&memcg_oom_lock);
  1589. mutex_release(&memcg_oom_lock_dep_map, _RET_IP_);
  1590. for_each_mem_cgroup_tree(iter, memcg)
  1591. iter->oom_lock = false;
  1592. spin_unlock(&memcg_oom_lock);
  1593. }
  1594. static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
  1595. {
  1596. struct mem_cgroup *iter;
  1597. spin_lock(&memcg_oom_lock);
  1598. for_each_mem_cgroup_tree(iter, memcg)
  1599. iter->under_oom++;
  1600. spin_unlock(&memcg_oom_lock);
  1601. }
  1602. static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
  1603. {
  1604. struct mem_cgroup *iter;
  1605. /*
  1606. * Be careful about under_oom underflows because a child memcg
  1607. * could have been added after mem_cgroup_mark_under_oom.
  1608. */
  1609. spin_lock(&memcg_oom_lock);
  1610. for_each_mem_cgroup_tree(iter, memcg)
  1611. if (iter->under_oom > 0)
  1612. iter->under_oom--;
  1613. spin_unlock(&memcg_oom_lock);
  1614. }
  1615. static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
  1616. struct oom_wait_info {
  1617. struct mem_cgroup *memcg;
  1618. wait_queue_entry_t wait;
  1619. };
  1620. static int memcg_oom_wake_function(wait_queue_entry_t *wait,
  1621. unsigned mode, int sync, void *arg)
  1622. {
  1623. struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg;
  1624. struct mem_cgroup *oom_wait_memcg;
  1625. struct oom_wait_info *oom_wait_info;
  1626. oom_wait_info = container_of(wait, struct oom_wait_info, wait);
  1627. oom_wait_memcg = oom_wait_info->memcg;
  1628. if (!mem_cgroup_is_descendant(wake_memcg, oom_wait_memcg) &&
  1629. !mem_cgroup_is_descendant(oom_wait_memcg, wake_memcg))
  1630. return 0;
  1631. return autoremove_wake_function(wait, mode, sync, arg);
  1632. }
  1633. static void memcg_oom_recover(struct mem_cgroup *memcg)
  1634. {
  1635. /*
  1636. * For the following lockless ->under_oom test, the only required
  1637. * guarantee is that it must see the state asserted by an OOM when
  1638. * this function is called as a result of userland actions
  1639. * triggered by the notification of the OOM. This is trivially
  1640. * achieved by invoking mem_cgroup_mark_under_oom() before
  1641. * triggering notification.
  1642. */
  1643. if (memcg && memcg->under_oom)
  1644. __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
  1645. }
  1646. /*
  1647. * Returns true if successfully killed one or more processes. Though in some
  1648. * corner cases it can return true even without killing any process.
  1649. */
  1650. static bool mem_cgroup_oom(struct mem_cgroup *memcg, gfp_t mask, int order)
  1651. {
  1652. bool locked, ret;
  1653. if (order > PAGE_ALLOC_COSTLY_ORDER)
  1654. return false;
  1655. memcg_memory_event(memcg, MEMCG_OOM);
  1656. /*
  1657. * We are in the middle of the charge context here, so we
  1658. * don't want to block when potentially sitting on a callstack
  1659. * that holds all kinds of filesystem and mm locks.
  1660. *
  1661. * cgroup1 allows disabling the OOM killer and waiting for outside
  1662. * handling until the charge can succeed; remember the context and put
  1663. * the task to sleep at the end of the page fault when all locks are
  1664. * released.
  1665. *
  1666. * On the other hand, in-kernel OOM killer allows for an async victim
  1667. * memory reclaim (oom_reaper) and that means that we are not solely
  1668. * relying on the oom victim to make a forward progress and we can
  1669. * invoke the oom killer here.
  1670. *
  1671. * Please note that mem_cgroup_out_of_memory might fail to find a
  1672. * victim and then we have to bail out from the charge path.
  1673. */
  1674. if (memcg->oom_kill_disable) {
  1675. if (current->in_user_fault) {
  1676. css_get(&memcg->css);
  1677. current->memcg_in_oom = memcg;
  1678. current->memcg_oom_gfp_mask = mask;
  1679. current->memcg_oom_order = order;
  1680. }
  1681. return false;
  1682. }
  1683. mem_cgroup_mark_under_oom(memcg);
  1684. locked = mem_cgroup_oom_trylock(memcg);
  1685. if (locked)
  1686. mem_cgroup_oom_notify(memcg);
  1687. mem_cgroup_unmark_under_oom(memcg);
  1688. ret = mem_cgroup_out_of_memory(memcg, mask, order);
  1689. if (locked)
  1690. mem_cgroup_oom_unlock(memcg);
  1691. return ret;
  1692. }
  1693. /**
  1694. * mem_cgroup_oom_synchronize - complete memcg OOM handling
  1695. * @handle: actually kill/wait or just clean up the OOM state
  1696. *
  1697. * This has to be called at the end of a page fault if the memcg OOM
  1698. * handler was enabled.
  1699. *
  1700. * Memcg supports userspace OOM handling where failed allocations must
  1701. * sleep on a waitqueue until the userspace task resolves the
  1702. * situation. Sleeping directly in the charge context with all kinds
  1703. * of locks held is not a good idea, instead we remember an OOM state
  1704. * in the task and mem_cgroup_oom_synchronize() has to be called at
  1705. * the end of the page fault to complete the OOM handling.
  1706. *
  1707. * Returns %true if an ongoing memcg OOM situation was detected and
  1708. * completed, %false otherwise.
  1709. */
  1710. bool mem_cgroup_oom_synchronize(bool handle)
  1711. {
  1712. struct mem_cgroup *memcg = current->memcg_in_oom;
  1713. struct oom_wait_info owait;
  1714. bool locked;
  1715. /* OOM is global, do not handle */
  1716. if (!memcg)
  1717. return false;
  1718. if (!handle)
  1719. goto cleanup;
  1720. owait.memcg = memcg;
  1721. owait.wait.flags = 0;
  1722. owait.wait.func = memcg_oom_wake_function;
  1723. owait.wait.private = current;
  1724. INIT_LIST_HEAD(&owait.wait.entry);
  1725. prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
  1726. mem_cgroup_mark_under_oom(memcg);
  1727. locked = mem_cgroup_oom_trylock(memcg);
  1728. if (locked)
  1729. mem_cgroup_oom_notify(memcg);
  1730. if (locked && !memcg->oom_kill_disable) {
  1731. mem_cgroup_unmark_under_oom(memcg);
  1732. finish_wait(&memcg_oom_waitq, &owait.wait);
  1733. mem_cgroup_out_of_memory(memcg, current->memcg_oom_gfp_mask,
  1734. current->memcg_oom_order);
  1735. } else {
  1736. schedule();
  1737. mem_cgroup_unmark_under_oom(memcg);
  1738. finish_wait(&memcg_oom_waitq, &owait.wait);
  1739. }
  1740. if (locked) {
  1741. mem_cgroup_oom_unlock(memcg);
  1742. /*
  1743. * There is no guarantee that an OOM-lock contender
  1744. * sees the wakeups triggered by the OOM kill
  1745. * uncharges. Wake any sleepers explicitly.
  1746. */
  1747. memcg_oom_recover(memcg);
  1748. }
  1749. cleanup:
  1750. current->memcg_in_oom = NULL;
  1751. css_put(&memcg->css);
  1752. return true;
  1753. }
  1754. /**
  1755. * mem_cgroup_get_oom_group - get a memory cgroup to clean up after OOM
  1756. * @victim: task to be killed by the OOM killer
  1757. * @oom_domain: memcg in case of memcg OOM, NULL in case of system-wide OOM
  1758. *
  1759. * Returns a pointer to a memory cgroup, which has to be cleaned up
  1760. * by killing all belonging OOM-killable tasks.
  1761. *
  1762. * Caller has to call mem_cgroup_put() on the returned non-NULL memcg.
  1763. */
  1764. struct mem_cgroup *mem_cgroup_get_oom_group(struct task_struct *victim,
  1765. struct mem_cgroup *oom_domain)
  1766. {
  1767. struct mem_cgroup *oom_group = NULL;
  1768. struct mem_cgroup *memcg;
  1769. if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
  1770. return NULL;
  1771. if (!oom_domain)
  1772. oom_domain = root_mem_cgroup;
  1773. rcu_read_lock();
  1774. memcg = mem_cgroup_from_task(victim);
  1775. if (memcg == root_mem_cgroup)
  1776. goto out;
  1777. /*
  1778. * If the victim task has been asynchronously moved to a different
  1779. * memory cgroup, we might end up killing tasks outside oom_domain.
  1780. * In this case it's better to ignore memory.group.oom.
  1781. */
  1782. if (unlikely(!mem_cgroup_is_descendant(memcg, oom_domain)))
  1783. goto out;
  1784. /*
  1785. * Traverse the memory cgroup hierarchy from the victim task's
  1786. * cgroup up to the OOMing cgroup (or root) to find the
  1787. * highest-level memory cgroup with oom.group set.
  1788. */
  1789. for (; memcg; memcg = parent_mem_cgroup(memcg)) {
  1790. if (memcg->oom_group)
  1791. oom_group = memcg;
  1792. if (memcg == oom_domain)
  1793. break;
  1794. }
  1795. if (oom_group)
  1796. css_get(&oom_group->css);
  1797. out:
  1798. rcu_read_unlock();
  1799. return oom_group;
  1800. }
  1801. void mem_cgroup_print_oom_group(struct mem_cgroup *memcg)
  1802. {
  1803. pr_info("Tasks in ");
  1804. pr_cont_cgroup_path(memcg->css.cgroup);
  1805. pr_cont(" are going to be killed due to memory.oom.group set\n");
  1806. }
  1807. /**
  1808. * folio_memcg_lock - Bind a folio to its memcg.
  1809. * @folio: The folio.
  1810. *
  1811. * This function prevents unlocked LRU folios from being moved to
  1812. * another cgroup.
  1813. *
  1814. * It ensures lifetime of the bound memcg. The caller is responsible
  1815. * for the lifetime of the folio.
  1816. */
  1817. void folio_memcg_lock(struct folio *folio)
  1818. {
  1819. struct mem_cgroup *memcg;
  1820. unsigned long flags;
  1821. /*
  1822. * The RCU lock is held throughout the transaction. The fast
  1823. * path can get away without acquiring the memcg->move_lock
  1824. * because page moving starts with an RCU grace period.
  1825. */
  1826. rcu_read_lock();
  1827. if (mem_cgroup_disabled())
  1828. return;
  1829. again:
  1830. memcg = folio_memcg(folio);
  1831. if (unlikely(!memcg))
  1832. return;
  1833. #ifdef CONFIG_PROVE_LOCKING
  1834. local_irq_save(flags);
  1835. might_lock(&memcg->move_lock);
  1836. local_irq_restore(flags);
  1837. #endif
  1838. if (atomic_read(&memcg->moving_account) <= 0)
  1839. return;
  1840. spin_lock_irqsave(&memcg->move_lock, flags);
  1841. if (memcg != folio_memcg(folio)) {
  1842. spin_unlock_irqrestore(&memcg->move_lock, flags);
  1843. goto again;
  1844. }
  1845. /*
  1846. * When charge migration first begins, we can have multiple
  1847. * critical sections holding the fast-path RCU lock and one
  1848. * holding the slowpath move_lock. Track the task who has the
  1849. * move_lock for unlock_page_memcg().
  1850. */
  1851. memcg->move_lock_task = current;
  1852. memcg->move_lock_flags = flags;
  1853. }
  1854. void lock_page_memcg(struct page *page)
  1855. {
  1856. folio_memcg_lock(page_folio(page));
  1857. }
  1858. static void __folio_memcg_unlock(struct mem_cgroup *memcg)
  1859. {
  1860. if (memcg && memcg->move_lock_task == current) {
  1861. unsigned long flags = memcg->move_lock_flags;
  1862. memcg->move_lock_task = NULL;
  1863. memcg->move_lock_flags = 0;
  1864. spin_unlock_irqrestore(&memcg->move_lock, flags);
  1865. }
  1866. rcu_read_unlock();
  1867. }
  1868. /**
  1869. * folio_memcg_unlock - Release the binding between a folio and its memcg.
  1870. * @folio: The folio.
  1871. *
  1872. * This releases the binding created by folio_memcg_lock(). This does
  1873. * not change the accounting of this folio to its memcg, but it does
  1874. * permit others to change it.
  1875. */
  1876. void folio_memcg_unlock(struct folio *folio)
  1877. {
  1878. __folio_memcg_unlock(folio_memcg(folio));
  1879. }
  1880. void unlock_page_memcg(struct page *page)
  1881. {
  1882. folio_memcg_unlock(page_folio(page));
  1883. }
  1884. struct memcg_stock_pcp {
  1885. local_lock_t stock_lock;
  1886. struct mem_cgroup *cached; /* this never be root cgroup */
  1887. unsigned int nr_pages;
  1888. #ifdef CONFIG_MEMCG_KMEM
  1889. struct obj_cgroup *cached_objcg;
  1890. struct pglist_data *cached_pgdat;
  1891. unsigned int nr_bytes;
  1892. int nr_slab_reclaimable_b;
  1893. int nr_slab_unreclaimable_b;
  1894. #endif
  1895. struct work_struct work;
  1896. unsigned long flags;
  1897. #define FLUSHING_CACHED_CHARGE 0
  1898. };
  1899. static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock) = {
  1900. .stock_lock = INIT_LOCAL_LOCK(stock_lock),
  1901. };
  1902. static DEFINE_MUTEX(percpu_charge_mutex);
  1903. #ifdef CONFIG_MEMCG_KMEM
  1904. static struct obj_cgroup *drain_obj_stock(struct memcg_stock_pcp *stock);
  1905. static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
  1906. struct mem_cgroup *root_memcg);
  1907. static void memcg_account_kmem(struct mem_cgroup *memcg, int nr_pages);
  1908. #else
  1909. static inline struct obj_cgroup *drain_obj_stock(struct memcg_stock_pcp *stock)
  1910. {
  1911. return NULL;
  1912. }
  1913. static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
  1914. struct mem_cgroup *root_memcg)
  1915. {
  1916. return false;
  1917. }
  1918. static void memcg_account_kmem(struct mem_cgroup *memcg, int nr_pages)
  1919. {
  1920. }
  1921. #endif
  1922. /**
  1923. * consume_stock: Try to consume stocked charge on this cpu.
  1924. * @memcg: memcg to consume from.
  1925. * @nr_pages: how many pages to charge.
  1926. *
  1927. * The charges will only happen if @memcg matches the current cpu's memcg
  1928. * stock, and at least @nr_pages are available in that stock. Failure to
  1929. * service an allocation will refill the stock.
  1930. *
  1931. * returns true if successful, false otherwise.
  1932. */
  1933. static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
  1934. {
  1935. struct memcg_stock_pcp *stock;
  1936. unsigned long flags;
  1937. bool ret = false;
  1938. if (nr_pages > MEMCG_CHARGE_BATCH)
  1939. return ret;
  1940. local_lock_irqsave(&memcg_stock.stock_lock, flags);
  1941. stock = this_cpu_ptr(&memcg_stock);
  1942. if (memcg == stock->cached && stock->nr_pages >= nr_pages) {
  1943. stock->nr_pages -= nr_pages;
  1944. ret = true;
  1945. }
  1946. local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
  1947. return ret;
  1948. }
  1949. /*
  1950. * Returns stocks cached in percpu and reset cached information.
  1951. */
  1952. static void drain_stock(struct memcg_stock_pcp *stock)
  1953. {
  1954. struct mem_cgroup *old = stock->cached;
  1955. if (!old)
  1956. return;
  1957. if (stock->nr_pages) {
  1958. page_counter_uncharge(&old->memory, stock->nr_pages);
  1959. if (do_memsw_account())
  1960. page_counter_uncharge(&old->memsw, stock->nr_pages);
  1961. stock->nr_pages = 0;
  1962. }
  1963. css_put(&old->css);
  1964. stock->cached = NULL;
  1965. }
  1966. static void drain_local_stock(struct work_struct *dummy)
  1967. {
  1968. struct memcg_stock_pcp *stock;
  1969. struct obj_cgroup *old = NULL;
  1970. unsigned long flags;
  1971. /*
  1972. * The only protection from cpu hotplug (memcg_hotplug_cpu_dead) vs.
  1973. * drain_stock races is that we always operate on local CPU stock
  1974. * here with IRQ disabled
  1975. */
  1976. local_lock_irqsave(&memcg_stock.stock_lock, flags);
  1977. stock = this_cpu_ptr(&memcg_stock);
  1978. old = drain_obj_stock(stock);
  1979. drain_stock(stock);
  1980. clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
  1981. local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
  1982. if (old)
  1983. obj_cgroup_put(old);
  1984. }
  1985. /*
  1986. * Cache charges(val) to local per_cpu area.
  1987. * This will be consumed by consume_stock() function, later.
  1988. */
  1989. static void __refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
  1990. {
  1991. struct memcg_stock_pcp *stock;
  1992. stock = this_cpu_ptr(&memcg_stock);
  1993. if (stock->cached != memcg) { /* reset if necessary */
  1994. drain_stock(stock);
  1995. css_get(&memcg->css);
  1996. stock->cached = memcg;
  1997. }
  1998. stock->nr_pages += nr_pages;
  1999. if (stock->nr_pages > MEMCG_CHARGE_BATCH)
  2000. drain_stock(stock);
  2001. }
  2002. static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
  2003. {
  2004. unsigned long flags;
  2005. local_lock_irqsave(&memcg_stock.stock_lock, flags);
  2006. __refill_stock(memcg, nr_pages);
  2007. local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
  2008. }
  2009. /*
  2010. * Drains all per-CPU charge caches for given root_memcg resp. subtree
  2011. * of the hierarchy under it.
  2012. */
  2013. static void drain_all_stock(struct mem_cgroup *root_memcg)
  2014. {
  2015. int cpu, curcpu;
  2016. /* If someone's already draining, avoid adding running more workers. */
  2017. if (!mutex_trylock(&percpu_charge_mutex))
  2018. return;
  2019. /*
  2020. * Notify other cpus that system-wide "drain" is running
  2021. * We do not care about races with the cpu hotplug because cpu down
  2022. * as well as workers from this path always operate on the local
  2023. * per-cpu data. CPU up doesn't touch memcg_stock at all.
  2024. */
  2025. migrate_disable();
  2026. curcpu = smp_processor_id();
  2027. for_each_online_cpu(cpu) {
  2028. struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
  2029. struct mem_cgroup *memcg;
  2030. bool flush = false;
  2031. rcu_read_lock();
  2032. memcg = stock->cached;
  2033. if (memcg && stock->nr_pages &&
  2034. mem_cgroup_is_descendant(memcg, root_memcg))
  2035. flush = true;
  2036. else if (obj_stock_flush_required(stock, root_memcg))
  2037. flush = true;
  2038. rcu_read_unlock();
  2039. if (flush &&
  2040. !test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
  2041. if (cpu == curcpu)
  2042. drain_local_stock(&stock->work);
  2043. else
  2044. schedule_work_on(cpu, &stock->work);
  2045. }
  2046. }
  2047. migrate_enable();
  2048. mutex_unlock(&percpu_charge_mutex);
  2049. }
  2050. static int memcg_hotplug_cpu_dead(unsigned int cpu)
  2051. {
  2052. struct memcg_stock_pcp *stock;
  2053. stock = &per_cpu(memcg_stock, cpu);
  2054. drain_stock(stock);
  2055. return 0;
  2056. }
  2057. static unsigned long reclaim_high(struct mem_cgroup *memcg,
  2058. unsigned int nr_pages,
  2059. gfp_t gfp_mask)
  2060. {
  2061. unsigned long nr_reclaimed = 0;
  2062. do {
  2063. unsigned long pflags;
  2064. if (page_counter_read(&memcg->memory) <=
  2065. READ_ONCE(memcg->memory.high))
  2066. continue;
  2067. memcg_memory_event(memcg, MEMCG_HIGH);
  2068. psi_memstall_enter(&pflags);
  2069. nr_reclaimed += try_to_free_mem_cgroup_pages(memcg, nr_pages,
  2070. gfp_mask,
  2071. MEMCG_RECLAIM_MAY_SWAP);
  2072. psi_memstall_leave(&pflags);
  2073. } while ((memcg = parent_mem_cgroup(memcg)) &&
  2074. !mem_cgroup_is_root(memcg));
  2075. return nr_reclaimed;
  2076. }
  2077. static void high_work_func(struct work_struct *work)
  2078. {
  2079. struct mem_cgroup *memcg;
  2080. memcg = container_of(work, struct mem_cgroup, high_work);
  2081. reclaim_high(memcg, MEMCG_CHARGE_BATCH, GFP_KERNEL);
  2082. }
  2083. /*
  2084. * Clamp the maximum sleep time per allocation batch to 2 seconds. This is
  2085. * enough to still cause a significant slowdown in most cases, while still
  2086. * allowing diagnostics and tracing to proceed without becoming stuck.
  2087. */
  2088. #define MEMCG_MAX_HIGH_DELAY_JIFFIES (2UL*HZ)
  2089. /*
  2090. * When calculating the delay, we use these either side of the exponentiation to
  2091. * maintain precision and scale to a reasonable number of jiffies (see the table
  2092. * below.
  2093. *
  2094. * - MEMCG_DELAY_PRECISION_SHIFT: Extra precision bits while translating the
  2095. * overage ratio to a delay.
  2096. * - MEMCG_DELAY_SCALING_SHIFT: The number of bits to scale down the
  2097. * proposed penalty in order to reduce to a reasonable number of jiffies, and
  2098. * to produce a reasonable delay curve.
  2099. *
  2100. * MEMCG_DELAY_SCALING_SHIFT just happens to be a number that produces a
  2101. * reasonable delay curve compared to precision-adjusted overage, not
  2102. * penalising heavily at first, but still making sure that growth beyond the
  2103. * limit penalises misbehaviour cgroups by slowing them down exponentially. For
  2104. * example, with a high of 100 megabytes:
  2105. *
  2106. * +-------+------------------------+
  2107. * | usage | time to allocate in ms |
  2108. * +-------+------------------------+
  2109. * | 100M | 0 |
  2110. * | 101M | 6 |
  2111. * | 102M | 25 |
  2112. * | 103M | 57 |
  2113. * | 104M | 102 |
  2114. * | 105M | 159 |
  2115. * | 106M | 230 |
  2116. * | 107M | 313 |
  2117. * | 108M | 409 |
  2118. * | 109M | 518 |
  2119. * | 110M | 639 |
  2120. * | 111M | 774 |
  2121. * | 112M | 921 |
  2122. * | 113M | 1081 |
  2123. * | 114M | 1254 |
  2124. * | 115M | 1439 |
  2125. * | 116M | 1638 |
  2126. * | 117M | 1849 |
  2127. * | 118M | 2000 |
  2128. * | 119M | 2000 |
  2129. * | 120M | 2000 |
  2130. * +-------+------------------------+
  2131. */
  2132. #define MEMCG_DELAY_PRECISION_SHIFT 20
  2133. #define MEMCG_DELAY_SCALING_SHIFT 14
  2134. static u64 calculate_overage(unsigned long usage, unsigned long high)
  2135. {
  2136. u64 overage;
  2137. if (usage <= high)
  2138. return 0;
  2139. /*
  2140. * Prevent division by 0 in overage calculation by acting as if
  2141. * it was a threshold of 1 page
  2142. */
  2143. high = max(high, 1UL);
  2144. overage = usage - high;
  2145. overage <<= MEMCG_DELAY_PRECISION_SHIFT;
  2146. return div64_u64(overage, high);
  2147. }
  2148. static u64 mem_find_max_overage(struct mem_cgroup *memcg)
  2149. {
  2150. u64 overage, max_overage = 0;
  2151. do {
  2152. overage = calculate_overage(page_counter_read(&memcg->memory),
  2153. READ_ONCE(memcg->memory.high));
  2154. max_overage = max(overage, max_overage);
  2155. } while ((memcg = parent_mem_cgroup(memcg)) &&
  2156. !mem_cgroup_is_root(memcg));
  2157. return max_overage;
  2158. }
  2159. static u64 swap_find_max_overage(struct mem_cgroup *memcg)
  2160. {
  2161. u64 overage, max_overage = 0;
  2162. do {
  2163. overage = calculate_overage(page_counter_read(&memcg->swap),
  2164. READ_ONCE(memcg->swap.high));
  2165. if (overage)
  2166. memcg_memory_event(memcg, MEMCG_SWAP_HIGH);
  2167. max_overage = max(overage, max_overage);
  2168. } while ((memcg = parent_mem_cgroup(memcg)) &&
  2169. !mem_cgroup_is_root(memcg));
  2170. return max_overage;
  2171. }
  2172. /*
  2173. * Get the number of jiffies that we should penalise a mischievous cgroup which
  2174. * is exceeding its memory.high by checking both it and its ancestors.
  2175. */
  2176. static unsigned long calculate_high_delay(struct mem_cgroup *memcg,
  2177. unsigned int nr_pages,
  2178. u64 max_overage)
  2179. {
  2180. unsigned long penalty_jiffies;
  2181. if (!max_overage)
  2182. return 0;
  2183. /*
  2184. * We use overage compared to memory.high to calculate the number of
  2185. * jiffies to sleep (penalty_jiffies). Ideally this value should be
  2186. * fairly lenient on small overages, and increasingly harsh when the
  2187. * memcg in question makes it clear that it has no intention of stopping
  2188. * its crazy behaviour, so we exponentially increase the delay based on
  2189. * overage amount.
  2190. */
  2191. penalty_jiffies = max_overage * max_overage * HZ;
  2192. penalty_jiffies >>= MEMCG_DELAY_PRECISION_SHIFT;
  2193. penalty_jiffies >>= MEMCG_DELAY_SCALING_SHIFT;
  2194. /*
  2195. * Factor in the task's own contribution to the overage, such that four
  2196. * N-sized allocations are throttled approximately the same as one
  2197. * 4N-sized allocation.
  2198. *
  2199. * MEMCG_CHARGE_BATCH pages is nominal, so work out how much smaller or
  2200. * larger the current charge patch is than that.
  2201. */
  2202. return penalty_jiffies * nr_pages / MEMCG_CHARGE_BATCH;
  2203. }
  2204. /*
  2205. * Scheduled by try_charge() to be executed from the userland return path
  2206. * and reclaims memory over the high limit.
  2207. */
  2208. void mem_cgroup_handle_over_high(gfp_t gfp_mask)
  2209. {
  2210. unsigned long penalty_jiffies;
  2211. unsigned long pflags;
  2212. unsigned long nr_reclaimed;
  2213. unsigned int nr_pages = current->memcg_nr_pages_over_high;
  2214. int nr_retries = MAX_RECLAIM_RETRIES;
  2215. struct mem_cgroup *memcg;
  2216. bool in_retry = false;
  2217. if (likely(!nr_pages))
  2218. return;
  2219. memcg = get_mem_cgroup_from_mm(current->mm);
  2220. current->memcg_nr_pages_over_high = 0;
  2221. retry_reclaim:
  2222. /*
  2223. * The allocating task should reclaim at least the batch size, but for
  2224. * subsequent retries we only want to do what's necessary to prevent oom
  2225. * or breaching resource isolation.
  2226. *
  2227. * This is distinct from memory.max or page allocator behaviour because
  2228. * memory.high is currently batched, whereas memory.max and the page
  2229. * allocator run every time an allocation is made.
  2230. */
  2231. nr_reclaimed = reclaim_high(memcg,
  2232. in_retry ? SWAP_CLUSTER_MAX : nr_pages,
  2233. gfp_mask);
  2234. /*
  2235. * memory.high is breached and reclaim is unable to keep up. Throttle
  2236. * allocators proactively to slow down excessive growth.
  2237. */
  2238. penalty_jiffies = calculate_high_delay(memcg, nr_pages,
  2239. mem_find_max_overage(memcg));
  2240. penalty_jiffies += calculate_high_delay(memcg, nr_pages,
  2241. swap_find_max_overage(memcg));
  2242. /*
  2243. * Clamp the max delay per usermode return so as to still keep the
  2244. * application moving forwards and also permit diagnostics, albeit
  2245. * extremely slowly.
  2246. */
  2247. penalty_jiffies = min(penalty_jiffies, MEMCG_MAX_HIGH_DELAY_JIFFIES);
  2248. /*
  2249. * Don't sleep if the amount of jiffies this memcg owes us is so low
  2250. * that it's not even worth doing, in an attempt to be nice to those who
  2251. * go only a small amount over their memory.high value and maybe haven't
  2252. * been aggressively reclaimed enough yet.
  2253. */
  2254. if (penalty_jiffies <= HZ / 100)
  2255. goto out;
  2256. /*
  2257. * If reclaim is making forward progress but we're still over
  2258. * memory.high, we want to encourage that rather than doing allocator
  2259. * throttling.
  2260. */
  2261. if (nr_reclaimed || nr_retries--) {
  2262. in_retry = true;
  2263. goto retry_reclaim;
  2264. }
  2265. /*
  2266. * If we exit early, we're guaranteed to die (since
  2267. * schedule_timeout_killable sets TASK_KILLABLE). This means we don't
  2268. * need to account for any ill-begotten jiffies to pay them off later.
  2269. */
  2270. psi_memstall_enter(&pflags);
  2271. schedule_timeout_killable(penalty_jiffies);
  2272. psi_memstall_leave(&pflags);
  2273. out:
  2274. css_put(&memcg->css);
  2275. }
  2276. static int try_charge_memcg(struct mem_cgroup *memcg, gfp_t gfp_mask,
  2277. unsigned int nr_pages)
  2278. {
  2279. unsigned int batch = max(MEMCG_CHARGE_BATCH, nr_pages);
  2280. int nr_retries = MAX_RECLAIM_RETRIES;
  2281. struct mem_cgroup *mem_over_limit;
  2282. struct page_counter *counter;
  2283. unsigned long nr_reclaimed;
  2284. bool passed_oom = false;
  2285. unsigned int reclaim_options = MEMCG_RECLAIM_MAY_SWAP;
  2286. bool drained = false;
  2287. bool raised_max_event = false;
  2288. unsigned long pflags;
  2289. retry:
  2290. if (consume_stock(memcg, nr_pages))
  2291. return 0;
  2292. if (!do_memsw_account() ||
  2293. page_counter_try_charge(&memcg->memsw, batch, &counter)) {
  2294. if (page_counter_try_charge(&memcg->memory, batch, &counter))
  2295. goto done_restock;
  2296. if (do_memsw_account())
  2297. page_counter_uncharge(&memcg->memsw, batch);
  2298. mem_over_limit = mem_cgroup_from_counter(counter, memory);
  2299. } else {
  2300. mem_over_limit = mem_cgroup_from_counter(counter, memsw);
  2301. reclaim_options &= ~MEMCG_RECLAIM_MAY_SWAP;
  2302. }
  2303. if (batch > nr_pages) {
  2304. batch = nr_pages;
  2305. goto retry;
  2306. }
  2307. /*
  2308. * Prevent unbounded recursion when reclaim operations need to
  2309. * allocate memory. This might exceed the limits temporarily,
  2310. * but we prefer facilitating memory reclaim and getting back
  2311. * under the limit over triggering OOM kills in these cases.
  2312. */
  2313. if (unlikely(current->flags & PF_MEMALLOC))
  2314. goto force;
  2315. if (unlikely(task_in_memcg_oom(current)))
  2316. goto nomem;
  2317. if (!gfpflags_allow_blocking(gfp_mask))
  2318. goto nomem;
  2319. memcg_memory_event(mem_over_limit, MEMCG_MAX);
  2320. raised_max_event = true;
  2321. psi_memstall_enter(&pflags);
  2322. nr_reclaimed = try_to_free_mem_cgroup_pages(mem_over_limit, nr_pages,
  2323. gfp_mask, reclaim_options);
  2324. psi_memstall_leave(&pflags);
  2325. if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
  2326. goto retry;
  2327. if (!drained) {
  2328. drain_all_stock(mem_over_limit);
  2329. drained = true;
  2330. goto retry;
  2331. }
  2332. if (gfp_mask & __GFP_NORETRY)
  2333. goto nomem;
  2334. /*
  2335. * Even though the limit is exceeded at this point, reclaim
  2336. * may have been able to free some pages. Retry the charge
  2337. * before killing the task.
  2338. *
  2339. * Only for regular pages, though: huge pages are rather
  2340. * unlikely to succeed so close to the limit, and we fall back
  2341. * to regular pages anyway in case of failure.
  2342. */
  2343. if (nr_reclaimed && nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER))
  2344. goto retry;
  2345. /*
  2346. * At task move, charge accounts can be doubly counted. So, it's
  2347. * better to wait until the end of task_move if something is going on.
  2348. */
  2349. if (mem_cgroup_wait_acct_move(mem_over_limit))
  2350. goto retry;
  2351. if (nr_retries--)
  2352. goto retry;
  2353. if (gfp_mask & __GFP_RETRY_MAYFAIL)
  2354. goto nomem;
  2355. /* Avoid endless loop for tasks bypassed by the oom killer */
  2356. if (passed_oom && task_is_dying())
  2357. goto nomem;
  2358. /*
  2359. * keep retrying as long as the memcg oom killer is able to make
  2360. * a forward progress or bypass the charge if the oom killer
  2361. * couldn't make any progress.
  2362. */
  2363. if (mem_cgroup_oom(mem_over_limit, gfp_mask,
  2364. get_order(nr_pages * PAGE_SIZE))) {
  2365. passed_oom = true;
  2366. nr_retries = MAX_RECLAIM_RETRIES;
  2367. goto retry;
  2368. }
  2369. nomem:
  2370. /*
  2371. * Memcg doesn't have a dedicated reserve for atomic
  2372. * allocations. But like the global atomic pool, we need to
  2373. * put the burden of reclaim on regular allocation requests
  2374. * and let these go through as privileged allocations.
  2375. */
  2376. if (!(gfp_mask & (__GFP_NOFAIL | __GFP_HIGH)))
  2377. return -ENOMEM;
  2378. force:
  2379. /*
  2380. * If the allocation has to be enforced, don't forget to raise
  2381. * a MEMCG_MAX event.
  2382. */
  2383. if (!raised_max_event)
  2384. memcg_memory_event(mem_over_limit, MEMCG_MAX);
  2385. /*
  2386. * The allocation either can't fail or will lead to more memory
  2387. * being freed very soon. Allow memory usage go over the limit
  2388. * temporarily by force charging it.
  2389. */
  2390. page_counter_charge(&memcg->memory, nr_pages);
  2391. if (do_memsw_account())
  2392. page_counter_charge(&memcg->memsw, nr_pages);
  2393. return 0;
  2394. done_restock:
  2395. if (batch > nr_pages)
  2396. refill_stock(memcg, batch - nr_pages);
  2397. /*
  2398. * If the hierarchy is above the normal consumption range, schedule
  2399. * reclaim on returning to userland. We can perform reclaim here
  2400. * if __GFP_RECLAIM but let's always punt for simplicity and so that
  2401. * GFP_KERNEL can consistently be used during reclaim. @memcg is
  2402. * not recorded as it most likely matches current's and won't
  2403. * change in the meantime. As high limit is checked again before
  2404. * reclaim, the cost of mismatch is negligible.
  2405. */
  2406. do {
  2407. bool mem_high, swap_high;
  2408. mem_high = page_counter_read(&memcg->memory) >
  2409. READ_ONCE(memcg->memory.high);
  2410. swap_high = page_counter_read(&memcg->swap) >
  2411. READ_ONCE(memcg->swap.high);
  2412. /* Don't bother a random interrupted task */
  2413. if (!in_task()) {
  2414. if (mem_high) {
  2415. schedule_work(&memcg->high_work);
  2416. break;
  2417. }
  2418. continue;
  2419. }
  2420. if (mem_high || swap_high) {
  2421. /*
  2422. * The allocating tasks in this cgroup will need to do
  2423. * reclaim or be throttled to prevent further growth
  2424. * of the memory or swap footprints.
  2425. *
  2426. * Target some best-effort fairness between the tasks,
  2427. * and distribute reclaim work and delay penalties
  2428. * based on how much each task is actually allocating.
  2429. */
  2430. current->memcg_nr_pages_over_high += batch;
  2431. set_notify_resume(current);
  2432. break;
  2433. }
  2434. } while ((memcg = parent_mem_cgroup(memcg)));
  2435. if (current->memcg_nr_pages_over_high > MEMCG_CHARGE_BATCH &&
  2436. !(current->flags & PF_MEMALLOC) &&
  2437. gfpflags_allow_blocking(gfp_mask)) {
  2438. mem_cgroup_handle_over_high(gfp_mask);
  2439. }
  2440. return 0;
  2441. }
  2442. static inline int try_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
  2443. unsigned int nr_pages)
  2444. {
  2445. if (mem_cgroup_is_root(memcg))
  2446. return 0;
  2447. return try_charge_memcg(memcg, gfp_mask, nr_pages);
  2448. }
  2449. static inline void cancel_charge(struct mem_cgroup *memcg, unsigned int nr_pages)
  2450. {
  2451. if (mem_cgroup_is_root(memcg))
  2452. return;
  2453. page_counter_uncharge(&memcg->memory, nr_pages);
  2454. if (do_memsw_account())
  2455. page_counter_uncharge(&memcg->memsw, nr_pages);
  2456. }
  2457. static void commit_charge(struct folio *folio, struct mem_cgroup *memcg)
  2458. {
  2459. VM_BUG_ON_FOLIO(folio_memcg(folio), folio);
  2460. /*
  2461. * Any of the following ensures page's memcg stability:
  2462. *
  2463. * - the page lock
  2464. * - LRU isolation
  2465. * - lock_page_memcg()
  2466. * - exclusive reference
  2467. * - mem_cgroup_trylock_pages()
  2468. */
  2469. folio->memcg_data = (unsigned long)memcg;
  2470. }
  2471. #ifdef CONFIG_MEMCG_KMEM
  2472. /*
  2473. * The allocated objcg pointers array is not accounted directly.
  2474. * Moreover, it should not come from DMA buffer and is not readily
  2475. * reclaimable. So those GFP bits should be masked off.
  2476. */
  2477. #define OBJCGS_CLEAR_MASK (__GFP_DMA | __GFP_RECLAIMABLE | \
  2478. __GFP_ACCOUNT | __GFP_NOFAIL)
  2479. /*
  2480. * mod_objcg_mlstate() may be called with irq enabled, so
  2481. * mod_memcg_lruvec_state() should be used.
  2482. */
  2483. static inline void mod_objcg_mlstate(struct obj_cgroup *objcg,
  2484. struct pglist_data *pgdat,
  2485. enum node_stat_item idx, int nr)
  2486. {
  2487. struct mem_cgroup *memcg;
  2488. struct lruvec *lruvec;
  2489. rcu_read_lock();
  2490. memcg = obj_cgroup_memcg(objcg);
  2491. lruvec = mem_cgroup_lruvec(memcg, pgdat);
  2492. mod_memcg_lruvec_state(lruvec, idx, nr);
  2493. rcu_read_unlock();
  2494. }
  2495. int memcg_alloc_slab_cgroups(struct slab *slab, struct kmem_cache *s,
  2496. gfp_t gfp, bool new_slab)
  2497. {
  2498. unsigned int objects = objs_per_slab(s, slab);
  2499. unsigned long memcg_data;
  2500. void *vec;
  2501. gfp &= ~OBJCGS_CLEAR_MASK;
  2502. vec = kcalloc_node(objects, sizeof(struct obj_cgroup *), gfp,
  2503. slab_nid(slab));
  2504. if (!vec)
  2505. return -ENOMEM;
  2506. memcg_data = (unsigned long) vec | MEMCG_DATA_OBJCGS;
  2507. if (new_slab) {
  2508. /*
  2509. * If the slab is brand new and nobody can yet access its
  2510. * memcg_data, no synchronization is required and memcg_data can
  2511. * be simply assigned.
  2512. */
  2513. slab->memcg_data = memcg_data;
  2514. } else if (cmpxchg(&slab->memcg_data, 0, memcg_data)) {
  2515. /*
  2516. * If the slab is already in use, somebody can allocate and
  2517. * assign obj_cgroups in parallel. In this case the existing
  2518. * objcg vector should be reused.
  2519. */
  2520. kfree(vec);
  2521. return 0;
  2522. }
  2523. kmemleak_not_leak(vec);
  2524. return 0;
  2525. }
  2526. static __always_inline
  2527. struct mem_cgroup *mem_cgroup_from_obj_folio(struct folio *folio, void *p)
  2528. {
  2529. /*
  2530. * Slab objects are accounted individually, not per-page.
  2531. * Memcg membership data for each individual object is saved in
  2532. * slab->memcg_data.
  2533. */
  2534. if (folio_test_slab(folio)) {
  2535. struct obj_cgroup **objcgs;
  2536. struct slab *slab;
  2537. unsigned int off;
  2538. slab = folio_slab(folio);
  2539. objcgs = slab_objcgs(slab);
  2540. if (!objcgs)
  2541. return NULL;
  2542. off = obj_to_index(slab->slab_cache, slab, p);
  2543. if (objcgs[off])
  2544. return obj_cgroup_memcg(objcgs[off]);
  2545. return NULL;
  2546. }
  2547. /*
  2548. * page_memcg_check() is used here, because in theory we can encounter
  2549. * a folio where the slab flag has been cleared already, but
  2550. * slab->memcg_data has not been freed yet
  2551. * page_memcg_check(page) will guarantee that a proper memory
  2552. * cgroup pointer or NULL will be returned.
  2553. */
  2554. return page_memcg_check(folio_page(folio, 0));
  2555. }
  2556. /*
  2557. * Returns a pointer to the memory cgroup to which the kernel object is charged.
  2558. *
  2559. * A passed kernel object can be a slab object, vmalloc object or a generic
  2560. * kernel page, so different mechanisms for getting the memory cgroup pointer
  2561. * should be used.
  2562. *
  2563. * In certain cases (e.g. kernel stacks or large kmallocs with SLUB) the caller
  2564. * can not know for sure how the kernel object is implemented.
  2565. * mem_cgroup_from_obj() can be safely used in such cases.
  2566. *
  2567. * The caller must ensure the memcg lifetime, e.g. by taking rcu_read_lock(),
  2568. * cgroup_mutex, etc.
  2569. */
  2570. struct mem_cgroup *mem_cgroup_from_obj(void *p)
  2571. {
  2572. struct folio *folio;
  2573. if (mem_cgroup_disabled())
  2574. return NULL;
  2575. if (unlikely(is_vmalloc_addr(p)))
  2576. folio = page_folio(vmalloc_to_page(p));
  2577. else
  2578. folio = virt_to_folio(p);
  2579. return mem_cgroup_from_obj_folio(folio, p);
  2580. }
  2581. /*
  2582. * Returns a pointer to the memory cgroup to which the kernel object is charged.
  2583. * Similar to mem_cgroup_from_obj(), but faster and not suitable for objects,
  2584. * allocated using vmalloc().
  2585. *
  2586. * A passed kernel object must be a slab object or a generic kernel page.
  2587. *
  2588. * The caller must ensure the memcg lifetime, e.g. by taking rcu_read_lock(),
  2589. * cgroup_mutex, etc.
  2590. */
  2591. struct mem_cgroup *mem_cgroup_from_slab_obj(void *p)
  2592. {
  2593. if (mem_cgroup_disabled())
  2594. return NULL;
  2595. return mem_cgroup_from_obj_folio(virt_to_folio(p), p);
  2596. }
  2597. static struct obj_cgroup *__get_obj_cgroup_from_memcg(struct mem_cgroup *memcg)
  2598. {
  2599. struct obj_cgroup *objcg = NULL;
  2600. for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg)) {
  2601. objcg = rcu_dereference(memcg->objcg);
  2602. if (objcg && obj_cgroup_tryget(objcg))
  2603. break;
  2604. objcg = NULL;
  2605. }
  2606. return objcg;
  2607. }
  2608. __always_inline struct obj_cgroup *get_obj_cgroup_from_current(void)
  2609. {
  2610. struct obj_cgroup *objcg = NULL;
  2611. struct mem_cgroup *memcg;
  2612. if (memcg_kmem_bypass())
  2613. return NULL;
  2614. rcu_read_lock();
  2615. if (unlikely(active_memcg()))
  2616. memcg = active_memcg();
  2617. else
  2618. memcg = mem_cgroup_from_task(current);
  2619. objcg = __get_obj_cgroup_from_memcg(memcg);
  2620. rcu_read_unlock();
  2621. return objcg;
  2622. }
  2623. struct obj_cgroup *get_obj_cgroup_from_page(struct page *page)
  2624. {
  2625. struct obj_cgroup *objcg;
  2626. if (!memcg_kmem_enabled())
  2627. return NULL;
  2628. if (PageMemcgKmem(page)) {
  2629. objcg = __folio_objcg(page_folio(page));
  2630. obj_cgroup_get(objcg);
  2631. } else {
  2632. struct mem_cgroup *memcg;
  2633. rcu_read_lock();
  2634. memcg = __folio_memcg(page_folio(page));
  2635. if (memcg)
  2636. objcg = __get_obj_cgroup_from_memcg(memcg);
  2637. else
  2638. objcg = NULL;
  2639. rcu_read_unlock();
  2640. }
  2641. return objcg;
  2642. }
  2643. static void memcg_account_kmem(struct mem_cgroup *memcg, int nr_pages)
  2644. {
  2645. mod_memcg_state(memcg, MEMCG_KMEM, nr_pages);
  2646. if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
  2647. if (nr_pages > 0)
  2648. page_counter_charge(&memcg->kmem, nr_pages);
  2649. else
  2650. page_counter_uncharge(&memcg->kmem, -nr_pages);
  2651. }
  2652. }
  2653. /*
  2654. * obj_cgroup_uncharge_pages: uncharge a number of kernel pages from a objcg
  2655. * @objcg: object cgroup to uncharge
  2656. * @nr_pages: number of pages to uncharge
  2657. */
  2658. static void obj_cgroup_uncharge_pages(struct obj_cgroup *objcg,
  2659. unsigned int nr_pages)
  2660. {
  2661. struct mem_cgroup *memcg;
  2662. memcg = get_mem_cgroup_from_objcg(objcg);
  2663. memcg_account_kmem(memcg, -nr_pages);
  2664. refill_stock(memcg, nr_pages);
  2665. css_put(&memcg->css);
  2666. }
  2667. /*
  2668. * obj_cgroup_charge_pages: charge a number of kernel pages to a objcg
  2669. * @objcg: object cgroup to charge
  2670. * @gfp: reclaim mode
  2671. * @nr_pages: number of pages to charge
  2672. *
  2673. * Returns 0 on success, an error code on failure.
  2674. */
  2675. static int obj_cgroup_charge_pages(struct obj_cgroup *objcg, gfp_t gfp,
  2676. unsigned int nr_pages)
  2677. {
  2678. struct mem_cgroup *memcg;
  2679. int ret;
  2680. memcg = get_mem_cgroup_from_objcg(objcg);
  2681. ret = try_charge_memcg(memcg, gfp, nr_pages);
  2682. if (ret)
  2683. goto out;
  2684. memcg_account_kmem(memcg, nr_pages);
  2685. out:
  2686. css_put(&memcg->css);
  2687. return ret;
  2688. }
  2689. /**
  2690. * __memcg_kmem_charge_page: charge a kmem page to the current memory cgroup
  2691. * @page: page to charge
  2692. * @gfp: reclaim mode
  2693. * @order: allocation order
  2694. *
  2695. * Returns 0 on success, an error code on failure.
  2696. */
  2697. int __memcg_kmem_charge_page(struct page *page, gfp_t gfp, int order)
  2698. {
  2699. struct obj_cgroup *objcg;
  2700. int ret = 0;
  2701. objcg = get_obj_cgroup_from_current();
  2702. if (objcg) {
  2703. ret = obj_cgroup_charge_pages(objcg, gfp, 1 << order);
  2704. if (!ret) {
  2705. page->memcg_data = (unsigned long)objcg |
  2706. MEMCG_DATA_KMEM;
  2707. return 0;
  2708. }
  2709. obj_cgroup_put(objcg);
  2710. }
  2711. return ret;
  2712. }
  2713. /**
  2714. * __memcg_kmem_uncharge_page: uncharge a kmem page
  2715. * @page: page to uncharge
  2716. * @order: allocation order
  2717. */
  2718. void __memcg_kmem_uncharge_page(struct page *page, int order)
  2719. {
  2720. struct folio *folio = page_folio(page);
  2721. struct obj_cgroup *objcg;
  2722. unsigned int nr_pages = 1 << order;
  2723. if (!folio_memcg_kmem(folio))
  2724. return;
  2725. objcg = __folio_objcg(folio);
  2726. obj_cgroup_uncharge_pages(objcg, nr_pages);
  2727. folio->memcg_data = 0;
  2728. obj_cgroup_put(objcg);
  2729. }
  2730. void mod_objcg_state(struct obj_cgroup *objcg, struct pglist_data *pgdat,
  2731. enum node_stat_item idx, int nr)
  2732. {
  2733. struct memcg_stock_pcp *stock;
  2734. struct obj_cgroup *old = NULL;
  2735. unsigned long flags;
  2736. int *bytes;
  2737. local_lock_irqsave(&memcg_stock.stock_lock, flags);
  2738. stock = this_cpu_ptr(&memcg_stock);
  2739. /*
  2740. * Save vmstat data in stock and skip vmstat array update unless
  2741. * accumulating over a page of vmstat data or when pgdat or idx
  2742. * changes.
  2743. */
  2744. if (READ_ONCE(stock->cached_objcg) != objcg) {
  2745. old = drain_obj_stock(stock);
  2746. obj_cgroup_get(objcg);
  2747. stock->nr_bytes = atomic_read(&objcg->nr_charged_bytes)
  2748. ? atomic_xchg(&objcg->nr_charged_bytes, 0) : 0;
  2749. WRITE_ONCE(stock->cached_objcg, objcg);
  2750. stock->cached_pgdat = pgdat;
  2751. } else if (stock->cached_pgdat != pgdat) {
  2752. /* Flush the existing cached vmstat data */
  2753. struct pglist_data *oldpg = stock->cached_pgdat;
  2754. if (stock->nr_slab_reclaimable_b) {
  2755. mod_objcg_mlstate(objcg, oldpg, NR_SLAB_RECLAIMABLE_B,
  2756. stock->nr_slab_reclaimable_b);
  2757. stock->nr_slab_reclaimable_b = 0;
  2758. }
  2759. if (stock->nr_slab_unreclaimable_b) {
  2760. mod_objcg_mlstate(objcg, oldpg, NR_SLAB_UNRECLAIMABLE_B,
  2761. stock->nr_slab_unreclaimable_b);
  2762. stock->nr_slab_unreclaimable_b = 0;
  2763. }
  2764. stock->cached_pgdat = pgdat;
  2765. }
  2766. bytes = (idx == NR_SLAB_RECLAIMABLE_B) ? &stock->nr_slab_reclaimable_b
  2767. : &stock->nr_slab_unreclaimable_b;
  2768. /*
  2769. * Even for large object >= PAGE_SIZE, the vmstat data will still be
  2770. * cached locally at least once before pushing it out.
  2771. */
  2772. if (!*bytes) {
  2773. *bytes = nr;
  2774. nr = 0;
  2775. } else {
  2776. *bytes += nr;
  2777. if (abs(*bytes) > PAGE_SIZE) {
  2778. nr = *bytes;
  2779. *bytes = 0;
  2780. } else {
  2781. nr = 0;
  2782. }
  2783. }
  2784. if (nr)
  2785. mod_objcg_mlstate(objcg, pgdat, idx, nr);
  2786. local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
  2787. if (old)
  2788. obj_cgroup_put(old);
  2789. }
  2790. static bool consume_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes)
  2791. {
  2792. struct memcg_stock_pcp *stock;
  2793. unsigned long flags;
  2794. bool ret = false;
  2795. local_lock_irqsave(&memcg_stock.stock_lock, flags);
  2796. stock = this_cpu_ptr(&memcg_stock);
  2797. if (objcg == READ_ONCE(stock->cached_objcg) && stock->nr_bytes >= nr_bytes) {
  2798. stock->nr_bytes -= nr_bytes;
  2799. ret = true;
  2800. }
  2801. local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
  2802. return ret;
  2803. }
  2804. static struct obj_cgroup *drain_obj_stock(struct memcg_stock_pcp *stock)
  2805. {
  2806. struct obj_cgroup *old = READ_ONCE(stock->cached_objcg);
  2807. if (!old)
  2808. return NULL;
  2809. if (stock->nr_bytes) {
  2810. unsigned int nr_pages = stock->nr_bytes >> PAGE_SHIFT;
  2811. unsigned int nr_bytes = stock->nr_bytes & (PAGE_SIZE - 1);
  2812. if (nr_pages) {
  2813. struct mem_cgroup *memcg;
  2814. memcg = get_mem_cgroup_from_objcg(old);
  2815. memcg_account_kmem(memcg, -nr_pages);
  2816. __refill_stock(memcg, nr_pages);
  2817. css_put(&memcg->css);
  2818. }
  2819. /*
  2820. * The leftover is flushed to the centralized per-memcg value.
  2821. * On the next attempt to refill obj stock it will be moved
  2822. * to a per-cpu stock (probably, on an other CPU), see
  2823. * refill_obj_stock().
  2824. *
  2825. * How often it's flushed is a trade-off between the memory
  2826. * limit enforcement accuracy and potential CPU contention,
  2827. * so it might be changed in the future.
  2828. */
  2829. atomic_add(nr_bytes, &old->nr_charged_bytes);
  2830. stock->nr_bytes = 0;
  2831. }
  2832. /*
  2833. * Flush the vmstat data in current stock
  2834. */
  2835. if (stock->nr_slab_reclaimable_b || stock->nr_slab_unreclaimable_b) {
  2836. if (stock->nr_slab_reclaimable_b) {
  2837. mod_objcg_mlstate(old, stock->cached_pgdat,
  2838. NR_SLAB_RECLAIMABLE_B,
  2839. stock->nr_slab_reclaimable_b);
  2840. stock->nr_slab_reclaimable_b = 0;
  2841. }
  2842. if (stock->nr_slab_unreclaimable_b) {
  2843. mod_objcg_mlstate(old, stock->cached_pgdat,
  2844. NR_SLAB_UNRECLAIMABLE_B,
  2845. stock->nr_slab_unreclaimable_b);
  2846. stock->nr_slab_unreclaimable_b = 0;
  2847. }
  2848. stock->cached_pgdat = NULL;
  2849. }
  2850. WRITE_ONCE(stock->cached_objcg, NULL);
  2851. /*
  2852. * The `old' objects needs to be released by the caller via
  2853. * obj_cgroup_put() outside of memcg_stock_pcp::stock_lock.
  2854. */
  2855. return old;
  2856. }
  2857. static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
  2858. struct mem_cgroup *root_memcg)
  2859. {
  2860. struct obj_cgroup *objcg = READ_ONCE(stock->cached_objcg);
  2861. struct mem_cgroup *memcg;
  2862. if (objcg) {
  2863. memcg = obj_cgroup_memcg(objcg);
  2864. if (memcg && mem_cgroup_is_descendant(memcg, root_memcg))
  2865. return true;
  2866. }
  2867. return false;
  2868. }
  2869. static void refill_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes,
  2870. bool allow_uncharge)
  2871. {
  2872. struct memcg_stock_pcp *stock;
  2873. struct obj_cgroup *old = NULL;
  2874. unsigned long flags;
  2875. unsigned int nr_pages = 0;
  2876. local_lock_irqsave(&memcg_stock.stock_lock, flags);
  2877. stock = this_cpu_ptr(&memcg_stock);
  2878. if (READ_ONCE(stock->cached_objcg) != objcg) { /* reset if necessary */
  2879. old = drain_obj_stock(stock);
  2880. obj_cgroup_get(objcg);
  2881. WRITE_ONCE(stock->cached_objcg, objcg);
  2882. stock->nr_bytes = atomic_read(&objcg->nr_charged_bytes)
  2883. ? atomic_xchg(&objcg->nr_charged_bytes, 0) : 0;
  2884. allow_uncharge = true; /* Allow uncharge when objcg changes */
  2885. }
  2886. stock->nr_bytes += nr_bytes;
  2887. if (allow_uncharge && (stock->nr_bytes > PAGE_SIZE)) {
  2888. nr_pages = stock->nr_bytes >> PAGE_SHIFT;
  2889. stock->nr_bytes &= (PAGE_SIZE - 1);
  2890. }
  2891. local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
  2892. if (old)
  2893. obj_cgroup_put(old);
  2894. if (nr_pages)
  2895. obj_cgroup_uncharge_pages(objcg, nr_pages);
  2896. }
  2897. int obj_cgroup_charge(struct obj_cgroup *objcg, gfp_t gfp, size_t size)
  2898. {
  2899. unsigned int nr_pages, nr_bytes;
  2900. int ret;
  2901. if (consume_obj_stock(objcg, size))
  2902. return 0;
  2903. /*
  2904. * In theory, objcg->nr_charged_bytes can have enough
  2905. * pre-charged bytes to satisfy the allocation. However,
  2906. * flushing objcg->nr_charged_bytes requires two atomic
  2907. * operations, and objcg->nr_charged_bytes can't be big.
  2908. * The shared objcg->nr_charged_bytes can also become a
  2909. * performance bottleneck if all tasks of the same memcg are
  2910. * trying to update it. So it's better to ignore it and try
  2911. * grab some new pages. The stock's nr_bytes will be flushed to
  2912. * objcg->nr_charged_bytes later on when objcg changes.
  2913. *
  2914. * The stock's nr_bytes may contain enough pre-charged bytes
  2915. * to allow one less page from being charged, but we can't rely
  2916. * on the pre-charged bytes not being changed outside of
  2917. * consume_obj_stock() or refill_obj_stock(). So ignore those
  2918. * pre-charged bytes as well when charging pages. To avoid a
  2919. * page uncharge right after a page charge, we set the
  2920. * allow_uncharge flag to false when calling refill_obj_stock()
  2921. * to temporarily allow the pre-charged bytes to exceed the page
  2922. * size limit. The maximum reachable value of the pre-charged
  2923. * bytes is (sizeof(object) + PAGE_SIZE - 2) if there is no data
  2924. * race.
  2925. */
  2926. nr_pages = size >> PAGE_SHIFT;
  2927. nr_bytes = size & (PAGE_SIZE - 1);
  2928. if (nr_bytes)
  2929. nr_pages += 1;
  2930. ret = obj_cgroup_charge_pages(objcg, gfp, nr_pages);
  2931. if (!ret && nr_bytes)
  2932. refill_obj_stock(objcg, PAGE_SIZE - nr_bytes, false);
  2933. return ret;
  2934. }
  2935. void obj_cgroup_uncharge(struct obj_cgroup *objcg, size_t size)
  2936. {
  2937. refill_obj_stock(objcg, size, true);
  2938. }
  2939. #endif /* CONFIG_MEMCG_KMEM */
  2940. /*
  2941. * Because page_memcg(head) is not set on tails, set it now.
  2942. */
  2943. void split_page_memcg(struct page *head, unsigned int nr)
  2944. {
  2945. struct folio *folio = page_folio(head);
  2946. struct mem_cgroup *memcg = folio_memcg(folio);
  2947. int i;
  2948. if (mem_cgroup_disabled() || !memcg)
  2949. return;
  2950. for (i = 1; i < nr; i++)
  2951. folio_page(folio, i)->memcg_data = folio->memcg_data;
  2952. if (folio_memcg_kmem(folio))
  2953. obj_cgroup_get_many(__folio_objcg(folio), nr - 1);
  2954. else
  2955. css_get_many(&memcg->css, nr - 1);
  2956. }
  2957. #ifdef CONFIG_SWAP
  2958. /**
  2959. * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
  2960. * @entry: swap entry to be moved
  2961. * @from: mem_cgroup which the entry is moved from
  2962. * @to: mem_cgroup which the entry is moved to
  2963. *
  2964. * It succeeds only when the swap_cgroup's record for this entry is the same
  2965. * as the mem_cgroup's id of @from.
  2966. *
  2967. * Returns 0 on success, -EINVAL on failure.
  2968. *
  2969. * The caller must have charged to @to, IOW, called page_counter_charge() about
  2970. * both res and memsw, and called css_get().
  2971. */
  2972. static int mem_cgroup_move_swap_account(swp_entry_t entry,
  2973. struct mem_cgroup *from, struct mem_cgroup *to)
  2974. {
  2975. unsigned short old_id, new_id;
  2976. old_id = mem_cgroup_id(from);
  2977. new_id = mem_cgroup_id(to);
  2978. if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
  2979. mod_memcg_state(from, MEMCG_SWAP, -1);
  2980. mod_memcg_state(to, MEMCG_SWAP, 1);
  2981. return 0;
  2982. }
  2983. return -EINVAL;
  2984. }
  2985. #else
  2986. static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
  2987. struct mem_cgroup *from, struct mem_cgroup *to)
  2988. {
  2989. return -EINVAL;
  2990. }
  2991. #endif
  2992. static DEFINE_MUTEX(memcg_max_mutex);
  2993. static int mem_cgroup_resize_max(struct mem_cgroup *memcg,
  2994. unsigned long max, bool memsw)
  2995. {
  2996. bool enlarge = false;
  2997. bool drained = false;
  2998. int ret;
  2999. bool limits_invariant;
  3000. struct page_counter *counter = memsw ? &memcg->memsw : &memcg->memory;
  3001. do {
  3002. if (signal_pending(current)) {
  3003. ret = -EINTR;
  3004. break;
  3005. }
  3006. mutex_lock(&memcg_max_mutex);
  3007. /*
  3008. * Make sure that the new limit (memsw or memory limit) doesn't
  3009. * break our basic invariant rule memory.max <= memsw.max.
  3010. */
  3011. limits_invariant = memsw ? max >= READ_ONCE(memcg->memory.max) :
  3012. max <= memcg->memsw.max;
  3013. if (!limits_invariant) {
  3014. mutex_unlock(&memcg_max_mutex);
  3015. ret = -EINVAL;
  3016. break;
  3017. }
  3018. if (max > counter->max)
  3019. enlarge = true;
  3020. ret = page_counter_set_max(counter, max);
  3021. mutex_unlock(&memcg_max_mutex);
  3022. if (!ret)
  3023. break;
  3024. if (!drained) {
  3025. drain_all_stock(memcg);
  3026. drained = true;
  3027. continue;
  3028. }
  3029. if (!try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL,
  3030. memsw ? 0 : MEMCG_RECLAIM_MAY_SWAP)) {
  3031. ret = -EBUSY;
  3032. break;
  3033. }
  3034. } while (true);
  3035. if (!ret && enlarge)
  3036. memcg_oom_recover(memcg);
  3037. return ret;
  3038. }
  3039. unsigned long mem_cgroup_soft_limit_reclaim(pg_data_t *pgdat, int order,
  3040. gfp_t gfp_mask,
  3041. unsigned long *total_scanned)
  3042. {
  3043. unsigned long nr_reclaimed = 0;
  3044. struct mem_cgroup_per_node *mz, *next_mz = NULL;
  3045. unsigned long reclaimed;
  3046. int loop = 0;
  3047. struct mem_cgroup_tree_per_node *mctz;
  3048. unsigned long excess;
  3049. if (lru_gen_enabled())
  3050. return 0;
  3051. if (order > 0)
  3052. return 0;
  3053. mctz = soft_limit_tree.rb_tree_per_node[pgdat->node_id];
  3054. /*
  3055. * Do not even bother to check the largest node if the root
  3056. * is empty. Do it lockless to prevent lock bouncing. Races
  3057. * are acceptable as soft limit is best effort anyway.
  3058. */
  3059. if (!mctz || RB_EMPTY_ROOT(&mctz->rb_root))
  3060. return 0;
  3061. /*
  3062. * This loop can run a while, specially if mem_cgroup's continuously
  3063. * keep exceeding their soft limit and putting the system under
  3064. * pressure
  3065. */
  3066. do {
  3067. if (next_mz)
  3068. mz = next_mz;
  3069. else
  3070. mz = mem_cgroup_largest_soft_limit_node(mctz);
  3071. if (!mz)
  3072. break;
  3073. reclaimed = mem_cgroup_soft_reclaim(mz->memcg, pgdat,
  3074. gfp_mask, total_scanned);
  3075. nr_reclaimed += reclaimed;
  3076. spin_lock_irq(&mctz->lock);
  3077. /*
  3078. * If we failed to reclaim anything from this memory cgroup
  3079. * it is time to move on to the next cgroup
  3080. */
  3081. next_mz = NULL;
  3082. if (!reclaimed)
  3083. next_mz = __mem_cgroup_largest_soft_limit_node(mctz);
  3084. excess = soft_limit_excess(mz->memcg);
  3085. /*
  3086. * One school of thought says that we should not add
  3087. * back the node to the tree if reclaim returns 0.
  3088. * But our reclaim could return 0, simply because due
  3089. * to priority we are exposing a smaller subset of
  3090. * memory to reclaim from. Consider this as a longer
  3091. * term TODO.
  3092. */
  3093. /* If excess == 0, no tree ops */
  3094. __mem_cgroup_insert_exceeded(mz, mctz, excess);
  3095. spin_unlock_irq(&mctz->lock);
  3096. css_put(&mz->memcg->css);
  3097. loop++;
  3098. /*
  3099. * Could not reclaim anything and there are no more
  3100. * mem cgroups to try or we seem to be looping without
  3101. * reclaiming anything.
  3102. */
  3103. if (!nr_reclaimed &&
  3104. (next_mz == NULL ||
  3105. loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
  3106. break;
  3107. } while (!nr_reclaimed);
  3108. if (next_mz)
  3109. css_put(&next_mz->memcg->css);
  3110. return nr_reclaimed;
  3111. }
  3112. /*
  3113. * Reclaims as many pages from the given memcg as possible.
  3114. *
  3115. * Caller is responsible for holding css reference for memcg.
  3116. */
  3117. static int mem_cgroup_force_empty(struct mem_cgroup *memcg)
  3118. {
  3119. int nr_retries = MAX_RECLAIM_RETRIES;
  3120. /* we call try-to-free pages for make this cgroup empty */
  3121. lru_add_drain_all();
  3122. drain_all_stock(memcg);
  3123. /* try to free all pages in this cgroup */
  3124. while (nr_retries && page_counter_read(&memcg->memory)) {
  3125. if (signal_pending(current))
  3126. return -EINTR;
  3127. if (!try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL,
  3128. MEMCG_RECLAIM_MAY_SWAP))
  3129. nr_retries--;
  3130. }
  3131. return 0;
  3132. }
  3133. static ssize_t mem_cgroup_force_empty_write(struct kernfs_open_file *of,
  3134. char *buf, size_t nbytes,
  3135. loff_t off)
  3136. {
  3137. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  3138. if (mem_cgroup_is_root(memcg))
  3139. return -EINVAL;
  3140. return mem_cgroup_force_empty(memcg) ?: nbytes;
  3141. }
  3142. static u64 mem_cgroup_hierarchy_read(struct cgroup_subsys_state *css,
  3143. struct cftype *cft)
  3144. {
  3145. return 1;
  3146. }
  3147. static int mem_cgroup_hierarchy_write(struct cgroup_subsys_state *css,
  3148. struct cftype *cft, u64 val)
  3149. {
  3150. if (val == 1)
  3151. return 0;
  3152. pr_warn_once("Non-hierarchical mode is deprecated. "
  3153. "Please report your usecase to [email protected] if you "
  3154. "depend on this functionality.\n");
  3155. return -EINVAL;
  3156. }
  3157. static unsigned long mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
  3158. {
  3159. unsigned long val;
  3160. if (mem_cgroup_is_root(memcg)) {
  3161. mem_cgroup_flush_stats();
  3162. val = memcg_page_state(memcg, NR_FILE_PAGES) +
  3163. memcg_page_state(memcg, NR_ANON_MAPPED);
  3164. if (swap)
  3165. val += memcg_page_state(memcg, MEMCG_SWAP);
  3166. } else {
  3167. if (!swap)
  3168. val = page_counter_read(&memcg->memory);
  3169. else
  3170. val = page_counter_read(&memcg->memsw);
  3171. }
  3172. return val;
  3173. }
  3174. enum {
  3175. RES_USAGE,
  3176. RES_LIMIT,
  3177. RES_MAX_USAGE,
  3178. RES_FAILCNT,
  3179. RES_SOFT_LIMIT,
  3180. };
  3181. static u64 mem_cgroup_read_u64(struct cgroup_subsys_state *css,
  3182. struct cftype *cft)
  3183. {
  3184. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3185. struct page_counter *counter;
  3186. switch (MEMFILE_TYPE(cft->private)) {
  3187. case _MEM:
  3188. counter = &memcg->memory;
  3189. break;
  3190. case _MEMSWAP:
  3191. counter = &memcg->memsw;
  3192. break;
  3193. case _KMEM:
  3194. counter = &memcg->kmem;
  3195. break;
  3196. case _TCP:
  3197. counter = &memcg->tcpmem;
  3198. break;
  3199. default:
  3200. BUG();
  3201. }
  3202. switch (MEMFILE_ATTR(cft->private)) {
  3203. case RES_USAGE:
  3204. if (counter == &memcg->memory)
  3205. return (u64)mem_cgroup_usage(memcg, false) * PAGE_SIZE;
  3206. if (counter == &memcg->memsw)
  3207. return (u64)mem_cgroup_usage(memcg, true) * PAGE_SIZE;
  3208. return (u64)page_counter_read(counter) * PAGE_SIZE;
  3209. case RES_LIMIT:
  3210. return (u64)counter->max * PAGE_SIZE;
  3211. case RES_MAX_USAGE:
  3212. return (u64)counter->watermark * PAGE_SIZE;
  3213. case RES_FAILCNT:
  3214. return counter->failcnt;
  3215. case RES_SOFT_LIMIT:
  3216. return (u64)memcg->soft_limit * PAGE_SIZE;
  3217. default:
  3218. BUG();
  3219. }
  3220. }
  3221. #ifdef CONFIG_MEMCG_KMEM
  3222. static int memcg_online_kmem(struct mem_cgroup *memcg)
  3223. {
  3224. struct obj_cgroup *objcg;
  3225. if (mem_cgroup_kmem_disabled())
  3226. return 0;
  3227. if (unlikely(mem_cgroup_is_root(memcg)))
  3228. return 0;
  3229. objcg = obj_cgroup_alloc();
  3230. if (!objcg)
  3231. return -ENOMEM;
  3232. objcg->memcg = memcg;
  3233. rcu_assign_pointer(memcg->objcg, objcg);
  3234. static_branch_enable(&memcg_kmem_enabled_key);
  3235. memcg->kmemcg_id = memcg->id.id;
  3236. return 0;
  3237. }
  3238. static void memcg_offline_kmem(struct mem_cgroup *memcg)
  3239. {
  3240. struct mem_cgroup *parent;
  3241. if (mem_cgroup_kmem_disabled())
  3242. return;
  3243. if (unlikely(mem_cgroup_is_root(memcg)))
  3244. return;
  3245. parent = parent_mem_cgroup(memcg);
  3246. if (!parent)
  3247. parent = root_mem_cgroup;
  3248. memcg_reparent_objcgs(memcg, parent);
  3249. /*
  3250. * After we have finished memcg_reparent_objcgs(), all list_lrus
  3251. * corresponding to this cgroup are guaranteed to remain empty.
  3252. * The ordering is imposed by list_lru_node->lock taken by
  3253. * memcg_reparent_list_lrus().
  3254. */
  3255. memcg_reparent_list_lrus(memcg, parent);
  3256. }
  3257. #else
  3258. static int memcg_online_kmem(struct mem_cgroup *memcg)
  3259. {
  3260. return 0;
  3261. }
  3262. static void memcg_offline_kmem(struct mem_cgroup *memcg)
  3263. {
  3264. }
  3265. #endif /* CONFIG_MEMCG_KMEM */
  3266. static int memcg_update_tcp_max(struct mem_cgroup *memcg, unsigned long max)
  3267. {
  3268. int ret;
  3269. mutex_lock(&memcg_max_mutex);
  3270. ret = page_counter_set_max(&memcg->tcpmem, max);
  3271. if (ret)
  3272. goto out;
  3273. if (!memcg->tcpmem_active) {
  3274. /*
  3275. * The active flag needs to be written after the static_key
  3276. * update. This is what guarantees that the socket activation
  3277. * function is the last one to run. See mem_cgroup_sk_alloc()
  3278. * for details, and note that we don't mark any socket as
  3279. * belonging to this memcg until that flag is up.
  3280. *
  3281. * We need to do this, because static_keys will span multiple
  3282. * sites, but we can't control their order. If we mark a socket
  3283. * as accounted, but the accounting functions are not patched in
  3284. * yet, we'll lose accounting.
  3285. *
  3286. * We never race with the readers in mem_cgroup_sk_alloc(),
  3287. * because when this value change, the code to process it is not
  3288. * patched in yet.
  3289. */
  3290. static_branch_inc(&memcg_sockets_enabled_key);
  3291. memcg->tcpmem_active = true;
  3292. }
  3293. out:
  3294. mutex_unlock(&memcg_max_mutex);
  3295. return ret;
  3296. }
  3297. /*
  3298. * The user of this function is...
  3299. * RES_LIMIT.
  3300. */
  3301. static ssize_t mem_cgroup_write(struct kernfs_open_file *of,
  3302. char *buf, size_t nbytes, loff_t off)
  3303. {
  3304. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  3305. unsigned long nr_pages;
  3306. int ret;
  3307. buf = strstrip(buf);
  3308. ret = page_counter_memparse(buf, "-1", &nr_pages);
  3309. if (ret)
  3310. return ret;
  3311. switch (MEMFILE_ATTR(of_cft(of)->private)) {
  3312. case RES_LIMIT:
  3313. if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
  3314. ret = -EINVAL;
  3315. break;
  3316. }
  3317. switch (MEMFILE_TYPE(of_cft(of)->private)) {
  3318. case _MEM:
  3319. ret = mem_cgroup_resize_max(memcg, nr_pages, false);
  3320. break;
  3321. case _MEMSWAP:
  3322. ret = mem_cgroup_resize_max(memcg, nr_pages, true);
  3323. break;
  3324. case _KMEM:
  3325. pr_warn_once("kmem.limit_in_bytes is deprecated and will be removed. "
  3326. "Writing any value to this file has no effect. "
  3327. "Please report your usecase to [email protected] if you "
  3328. "depend on this functionality.\n");
  3329. ret = 0;
  3330. break;
  3331. case _TCP:
  3332. ret = memcg_update_tcp_max(memcg, nr_pages);
  3333. break;
  3334. }
  3335. break;
  3336. case RES_SOFT_LIMIT:
  3337. if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
  3338. ret = -EOPNOTSUPP;
  3339. } else {
  3340. memcg->soft_limit = nr_pages;
  3341. ret = 0;
  3342. }
  3343. break;
  3344. }
  3345. return ret ?: nbytes;
  3346. }
  3347. static ssize_t mem_cgroup_reset(struct kernfs_open_file *of, char *buf,
  3348. size_t nbytes, loff_t off)
  3349. {
  3350. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  3351. struct page_counter *counter;
  3352. switch (MEMFILE_TYPE(of_cft(of)->private)) {
  3353. case _MEM:
  3354. counter = &memcg->memory;
  3355. break;
  3356. case _MEMSWAP:
  3357. counter = &memcg->memsw;
  3358. break;
  3359. case _KMEM:
  3360. counter = &memcg->kmem;
  3361. break;
  3362. case _TCP:
  3363. counter = &memcg->tcpmem;
  3364. break;
  3365. default:
  3366. BUG();
  3367. }
  3368. switch (MEMFILE_ATTR(of_cft(of)->private)) {
  3369. case RES_MAX_USAGE:
  3370. page_counter_reset_watermark(counter);
  3371. break;
  3372. case RES_FAILCNT:
  3373. counter->failcnt = 0;
  3374. break;
  3375. default:
  3376. BUG();
  3377. }
  3378. return nbytes;
  3379. }
  3380. static u64 mem_cgroup_move_charge_read(struct cgroup_subsys_state *css,
  3381. struct cftype *cft)
  3382. {
  3383. return mem_cgroup_from_css(css)->move_charge_at_immigrate;
  3384. }
  3385. #ifdef CONFIG_MMU
  3386. static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
  3387. struct cftype *cft, u64 val)
  3388. {
  3389. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3390. pr_warn_once("Cgroup memory moving (move_charge_at_immigrate) is deprecated. "
  3391. "Please report your usecase to [email protected] if you "
  3392. "depend on this functionality.\n");
  3393. if (val & ~MOVE_MASK)
  3394. return -EINVAL;
  3395. /*
  3396. * No kind of locking is needed in here, because ->can_attach() will
  3397. * check this value once in the beginning of the process, and then carry
  3398. * on with stale data. This means that changes to this value will only
  3399. * affect task migrations starting after the change.
  3400. */
  3401. memcg->move_charge_at_immigrate = val;
  3402. return 0;
  3403. }
  3404. #else
  3405. static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
  3406. struct cftype *cft, u64 val)
  3407. {
  3408. return -ENOSYS;
  3409. }
  3410. #endif
  3411. #ifdef CONFIG_NUMA
  3412. #define LRU_ALL_FILE (BIT(LRU_INACTIVE_FILE) | BIT(LRU_ACTIVE_FILE))
  3413. #define LRU_ALL_ANON (BIT(LRU_INACTIVE_ANON) | BIT(LRU_ACTIVE_ANON))
  3414. #define LRU_ALL ((1 << NR_LRU_LISTS) - 1)
  3415. static unsigned long mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
  3416. int nid, unsigned int lru_mask, bool tree)
  3417. {
  3418. struct lruvec *lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
  3419. unsigned long nr = 0;
  3420. enum lru_list lru;
  3421. VM_BUG_ON((unsigned)nid >= nr_node_ids);
  3422. for_each_lru(lru) {
  3423. if (!(BIT(lru) & lru_mask))
  3424. continue;
  3425. if (tree)
  3426. nr += lruvec_page_state(lruvec, NR_LRU_BASE + lru);
  3427. else
  3428. nr += lruvec_page_state_local(lruvec, NR_LRU_BASE + lru);
  3429. }
  3430. return nr;
  3431. }
  3432. static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
  3433. unsigned int lru_mask,
  3434. bool tree)
  3435. {
  3436. unsigned long nr = 0;
  3437. enum lru_list lru;
  3438. for_each_lru(lru) {
  3439. if (!(BIT(lru) & lru_mask))
  3440. continue;
  3441. if (tree)
  3442. nr += memcg_page_state(memcg, NR_LRU_BASE + lru);
  3443. else
  3444. nr += memcg_page_state_local(memcg, NR_LRU_BASE + lru);
  3445. }
  3446. return nr;
  3447. }
  3448. static int memcg_numa_stat_show(struct seq_file *m, void *v)
  3449. {
  3450. struct numa_stat {
  3451. const char *name;
  3452. unsigned int lru_mask;
  3453. };
  3454. static const struct numa_stat stats[] = {
  3455. { "total", LRU_ALL },
  3456. { "file", LRU_ALL_FILE },
  3457. { "anon", LRU_ALL_ANON },
  3458. { "unevictable", BIT(LRU_UNEVICTABLE) },
  3459. };
  3460. const struct numa_stat *stat;
  3461. int nid;
  3462. struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
  3463. mem_cgroup_flush_stats();
  3464. for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
  3465. seq_printf(m, "%s=%lu", stat->name,
  3466. mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
  3467. false));
  3468. for_each_node_state(nid, N_MEMORY)
  3469. seq_printf(m, " N%d=%lu", nid,
  3470. mem_cgroup_node_nr_lru_pages(memcg, nid,
  3471. stat->lru_mask, false));
  3472. seq_putc(m, '\n');
  3473. }
  3474. for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
  3475. seq_printf(m, "hierarchical_%s=%lu", stat->name,
  3476. mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
  3477. true));
  3478. for_each_node_state(nid, N_MEMORY)
  3479. seq_printf(m, " N%d=%lu", nid,
  3480. mem_cgroup_node_nr_lru_pages(memcg, nid,
  3481. stat->lru_mask, true));
  3482. seq_putc(m, '\n');
  3483. }
  3484. return 0;
  3485. }
  3486. #endif /* CONFIG_NUMA */
  3487. static const unsigned int memcg1_stats[] = {
  3488. NR_FILE_PAGES,
  3489. NR_ANON_MAPPED,
  3490. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  3491. NR_ANON_THPS,
  3492. #endif
  3493. NR_SHMEM,
  3494. NR_FILE_MAPPED,
  3495. NR_FILE_DIRTY,
  3496. NR_WRITEBACK,
  3497. WORKINGSET_REFAULT_ANON,
  3498. WORKINGSET_REFAULT_FILE,
  3499. MEMCG_SWAP,
  3500. };
  3501. static const char *const memcg1_stat_names[] = {
  3502. "cache",
  3503. "rss",
  3504. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  3505. "rss_huge",
  3506. #endif
  3507. "shmem",
  3508. "mapped_file",
  3509. "dirty",
  3510. "writeback",
  3511. "workingset_refault_anon",
  3512. "workingset_refault_file",
  3513. "swap",
  3514. };
  3515. /* Universal VM events cgroup1 shows, original sort order */
  3516. static const unsigned int memcg1_events[] = {
  3517. PGPGIN,
  3518. PGPGOUT,
  3519. PGFAULT,
  3520. PGMAJFAULT,
  3521. };
  3522. static int memcg_stat_show(struct seq_file *m, void *v)
  3523. {
  3524. struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
  3525. unsigned long memory, memsw;
  3526. struct mem_cgroup *mi;
  3527. unsigned int i;
  3528. BUILD_BUG_ON(ARRAY_SIZE(memcg1_stat_names) != ARRAY_SIZE(memcg1_stats));
  3529. mem_cgroup_flush_stats();
  3530. for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
  3531. unsigned long nr;
  3532. if (memcg1_stats[i] == MEMCG_SWAP && !do_memsw_account())
  3533. continue;
  3534. nr = memcg_page_state_local(memcg, memcg1_stats[i]);
  3535. seq_printf(m, "%s %lu\n", memcg1_stat_names[i],
  3536. nr * memcg_page_state_unit(memcg1_stats[i]));
  3537. }
  3538. for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
  3539. seq_printf(m, "%s %lu\n", vm_event_name(memcg1_events[i]),
  3540. memcg_events_local(memcg, memcg1_events[i]));
  3541. for (i = 0; i < NR_LRU_LISTS; i++)
  3542. seq_printf(m, "%s %lu\n", lru_list_name(i),
  3543. memcg_page_state_local(memcg, NR_LRU_BASE + i) *
  3544. PAGE_SIZE);
  3545. /* Hierarchical information */
  3546. memory = memsw = PAGE_COUNTER_MAX;
  3547. for (mi = memcg; mi; mi = parent_mem_cgroup(mi)) {
  3548. memory = min(memory, READ_ONCE(mi->memory.max));
  3549. memsw = min(memsw, READ_ONCE(mi->memsw.max));
  3550. }
  3551. seq_printf(m, "hierarchical_memory_limit %llu\n",
  3552. (u64)memory * PAGE_SIZE);
  3553. if (do_memsw_account())
  3554. seq_printf(m, "hierarchical_memsw_limit %llu\n",
  3555. (u64)memsw * PAGE_SIZE);
  3556. for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
  3557. unsigned long nr;
  3558. if (memcg1_stats[i] == MEMCG_SWAP && !do_memsw_account())
  3559. continue;
  3560. nr = memcg_page_state(memcg, memcg1_stats[i]);
  3561. seq_printf(m, "total_%s %llu\n", memcg1_stat_names[i],
  3562. (u64)nr * memcg_page_state_unit(memcg1_stats[i]));
  3563. }
  3564. for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
  3565. seq_printf(m, "total_%s %llu\n",
  3566. vm_event_name(memcg1_events[i]),
  3567. (u64)memcg_events(memcg, memcg1_events[i]));
  3568. for (i = 0; i < NR_LRU_LISTS; i++)
  3569. seq_printf(m, "total_%s %llu\n", lru_list_name(i),
  3570. (u64)memcg_page_state(memcg, NR_LRU_BASE + i) *
  3571. PAGE_SIZE);
  3572. #ifdef CONFIG_DEBUG_VM
  3573. {
  3574. pg_data_t *pgdat;
  3575. struct mem_cgroup_per_node *mz;
  3576. unsigned long anon_cost = 0;
  3577. unsigned long file_cost = 0;
  3578. for_each_online_pgdat(pgdat) {
  3579. mz = memcg->nodeinfo[pgdat->node_id];
  3580. anon_cost += mz->lruvec.anon_cost;
  3581. file_cost += mz->lruvec.file_cost;
  3582. }
  3583. seq_printf(m, "anon_cost %lu\n", anon_cost);
  3584. seq_printf(m, "file_cost %lu\n", file_cost);
  3585. }
  3586. #endif
  3587. return 0;
  3588. }
  3589. static u64 mem_cgroup_swappiness_read(struct cgroup_subsys_state *css,
  3590. struct cftype *cft)
  3591. {
  3592. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3593. return mem_cgroup_swappiness(memcg);
  3594. }
  3595. static int mem_cgroup_swappiness_write(struct cgroup_subsys_state *css,
  3596. struct cftype *cft, u64 val)
  3597. {
  3598. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3599. if (val > 200)
  3600. return -EINVAL;
  3601. if (!mem_cgroup_is_root(memcg))
  3602. memcg->swappiness = val;
  3603. else
  3604. vm_swappiness = val;
  3605. return 0;
  3606. }
  3607. static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
  3608. {
  3609. struct mem_cgroup_threshold_ary *t;
  3610. unsigned long usage;
  3611. int i;
  3612. rcu_read_lock();
  3613. if (!swap)
  3614. t = rcu_dereference(memcg->thresholds.primary);
  3615. else
  3616. t = rcu_dereference(memcg->memsw_thresholds.primary);
  3617. if (!t)
  3618. goto unlock;
  3619. usage = mem_cgroup_usage(memcg, swap);
  3620. /*
  3621. * current_threshold points to threshold just below or equal to usage.
  3622. * If it's not true, a threshold was crossed after last
  3623. * call of __mem_cgroup_threshold().
  3624. */
  3625. i = t->current_threshold;
  3626. /*
  3627. * Iterate backward over array of thresholds starting from
  3628. * current_threshold and check if a threshold is crossed.
  3629. * If none of thresholds below usage is crossed, we read
  3630. * only one element of the array here.
  3631. */
  3632. for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
  3633. eventfd_signal(t->entries[i].eventfd, 1);
  3634. /* i = current_threshold + 1 */
  3635. i++;
  3636. /*
  3637. * Iterate forward over array of thresholds starting from
  3638. * current_threshold+1 and check if a threshold is crossed.
  3639. * If none of thresholds above usage is crossed, we read
  3640. * only one element of the array here.
  3641. */
  3642. for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
  3643. eventfd_signal(t->entries[i].eventfd, 1);
  3644. /* Update current_threshold */
  3645. t->current_threshold = i - 1;
  3646. unlock:
  3647. rcu_read_unlock();
  3648. }
  3649. static void mem_cgroup_threshold(struct mem_cgroup *memcg)
  3650. {
  3651. while (memcg) {
  3652. __mem_cgroup_threshold(memcg, false);
  3653. if (do_memsw_account())
  3654. __mem_cgroup_threshold(memcg, true);
  3655. memcg = parent_mem_cgroup(memcg);
  3656. }
  3657. }
  3658. static int compare_thresholds(const void *a, const void *b)
  3659. {
  3660. const struct mem_cgroup_threshold *_a = a;
  3661. const struct mem_cgroup_threshold *_b = b;
  3662. if (_a->threshold > _b->threshold)
  3663. return 1;
  3664. if (_a->threshold < _b->threshold)
  3665. return -1;
  3666. return 0;
  3667. }
  3668. static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
  3669. {
  3670. struct mem_cgroup_eventfd_list *ev;
  3671. spin_lock(&memcg_oom_lock);
  3672. list_for_each_entry(ev, &memcg->oom_notify, list)
  3673. eventfd_signal(ev->eventfd, 1);
  3674. spin_unlock(&memcg_oom_lock);
  3675. return 0;
  3676. }
  3677. static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
  3678. {
  3679. struct mem_cgroup *iter;
  3680. for_each_mem_cgroup_tree(iter, memcg)
  3681. mem_cgroup_oom_notify_cb(iter);
  3682. }
  3683. static int __mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
  3684. struct eventfd_ctx *eventfd, const char *args, enum res_type type)
  3685. {
  3686. struct mem_cgroup_thresholds *thresholds;
  3687. struct mem_cgroup_threshold_ary *new;
  3688. unsigned long threshold;
  3689. unsigned long usage;
  3690. int i, size, ret;
  3691. ret = page_counter_memparse(args, "-1", &threshold);
  3692. if (ret)
  3693. return ret;
  3694. mutex_lock(&memcg->thresholds_lock);
  3695. if (type == _MEM) {
  3696. thresholds = &memcg->thresholds;
  3697. usage = mem_cgroup_usage(memcg, false);
  3698. } else if (type == _MEMSWAP) {
  3699. thresholds = &memcg->memsw_thresholds;
  3700. usage = mem_cgroup_usage(memcg, true);
  3701. } else
  3702. BUG();
  3703. /* Check if a threshold crossed before adding a new one */
  3704. if (thresholds->primary)
  3705. __mem_cgroup_threshold(memcg, type == _MEMSWAP);
  3706. size = thresholds->primary ? thresholds->primary->size + 1 : 1;
  3707. /* Allocate memory for new array of thresholds */
  3708. new = kmalloc(struct_size(new, entries, size), GFP_KERNEL);
  3709. if (!new) {
  3710. ret = -ENOMEM;
  3711. goto unlock;
  3712. }
  3713. new->size = size;
  3714. /* Copy thresholds (if any) to new array */
  3715. if (thresholds->primary)
  3716. memcpy(new->entries, thresholds->primary->entries,
  3717. flex_array_size(new, entries, size - 1));
  3718. /* Add new threshold */
  3719. new->entries[size - 1].eventfd = eventfd;
  3720. new->entries[size - 1].threshold = threshold;
  3721. /* Sort thresholds. Registering of new threshold isn't time-critical */
  3722. sort(new->entries, size, sizeof(*new->entries),
  3723. compare_thresholds, NULL);
  3724. /* Find current threshold */
  3725. new->current_threshold = -1;
  3726. for (i = 0; i < size; i++) {
  3727. if (new->entries[i].threshold <= usage) {
  3728. /*
  3729. * new->current_threshold will not be used until
  3730. * rcu_assign_pointer(), so it's safe to increment
  3731. * it here.
  3732. */
  3733. ++new->current_threshold;
  3734. } else
  3735. break;
  3736. }
  3737. /* Free old spare buffer and save old primary buffer as spare */
  3738. kfree(thresholds->spare);
  3739. thresholds->spare = thresholds->primary;
  3740. rcu_assign_pointer(thresholds->primary, new);
  3741. /* To be sure that nobody uses thresholds */
  3742. synchronize_rcu();
  3743. unlock:
  3744. mutex_unlock(&memcg->thresholds_lock);
  3745. return ret;
  3746. }
  3747. static int mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
  3748. struct eventfd_ctx *eventfd, const char *args)
  3749. {
  3750. return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEM);
  3751. }
  3752. static int memsw_cgroup_usage_register_event(struct mem_cgroup *memcg,
  3753. struct eventfd_ctx *eventfd, const char *args)
  3754. {
  3755. return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEMSWAP);
  3756. }
  3757. static void __mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
  3758. struct eventfd_ctx *eventfd, enum res_type type)
  3759. {
  3760. struct mem_cgroup_thresholds *thresholds;
  3761. struct mem_cgroup_threshold_ary *new;
  3762. unsigned long usage;
  3763. int i, j, size, entries;
  3764. mutex_lock(&memcg->thresholds_lock);
  3765. if (type == _MEM) {
  3766. thresholds = &memcg->thresholds;
  3767. usage = mem_cgroup_usage(memcg, false);
  3768. } else if (type == _MEMSWAP) {
  3769. thresholds = &memcg->memsw_thresholds;
  3770. usage = mem_cgroup_usage(memcg, true);
  3771. } else
  3772. BUG();
  3773. if (!thresholds->primary)
  3774. goto unlock;
  3775. /* Check if a threshold crossed before removing */
  3776. __mem_cgroup_threshold(memcg, type == _MEMSWAP);
  3777. /* Calculate new number of threshold */
  3778. size = entries = 0;
  3779. for (i = 0; i < thresholds->primary->size; i++) {
  3780. if (thresholds->primary->entries[i].eventfd != eventfd)
  3781. size++;
  3782. else
  3783. entries++;
  3784. }
  3785. new = thresholds->spare;
  3786. /* If no items related to eventfd have been cleared, nothing to do */
  3787. if (!entries)
  3788. goto unlock;
  3789. /* Set thresholds array to NULL if we don't have thresholds */
  3790. if (!size) {
  3791. kfree(new);
  3792. new = NULL;
  3793. goto swap_buffers;
  3794. }
  3795. new->size = size;
  3796. /* Copy thresholds and find current threshold */
  3797. new->current_threshold = -1;
  3798. for (i = 0, j = 0; i < thresholds->primary->size; i++) {
  3799. if (thresholds->primary->entries[i].eventfd == eventfd)
  3800. continue;
  3801. new->entries[j] = thresholds->primary->entries[i];
  3802. if (new->entries[j].threshold <= usage) {
  3803. /*
  3804. * new->current_threshold will not be used
  3805. * until rcu_assign_pointer(), so it's safe to increment
  3806. * it here.
  3807. */
  3808. ++new->current_threshold;
  3809. }
  3810. j++;
  3811. }
  3812. swap_buffers:
  3813. /* Swap primary and spare array */
  3814. thresholds->spare = thresholds->primary;
  3815. rcu_assign_pointer(thresholds->primary, new);
  3816. /* To be sure that nobody uses thresholds */
  3817. synchronize_rcu();
  3818. /* If all events are unregistered, free the spare array */
  3819. if (!new) {
  3820. kfree(thresholds->spare);
  3821. thresholds->spare = NULL;
  3822. }
  3823. unlock:
  3824. mutex_unlock(&memcg->thresholds_lock);
  3825. }
  3826. static void mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
  3827. struct eventfd_ctx *eventfd)
  3828. {
  3829. return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEM);
  3830. }
  3831. static void memsw_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
  3832. struct eventfd_ctx *eventfd)
  3833. {
  3834. return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEMSWAP);
  3835. }
  3836. static int mem_cgroup_oom_register_event(struct mem_cgroup *memcg,
  3837. struct eventfd_ctx *eventfd, const char *args)
  3838. {
  3839. struct mem_cgroup_eventfd_list *event;
  3840. event = kmalloc(sizeof(*event), GFP_KERNEL);
  3841. if (!event)
  3842. return -ENOMEM;
  3843. spin_lock(&memcg_oom_lock);
  3844. event->eventfd = eventfd;
  3845. list_add(&event->list, &memcg->oom_notify);
  3846. /* already in OOM ? */
  3847. if (memcg->under_oom)
  3848. eventfd_signal(eventfd, 1);
  3849. spin_unlock(&memcg_oom_lock);
  3850. return 0;
  3851. }
  3852. static void mem_cgroup_oom_unregister_event(struct mem_cgroup *memcg,
  3853. struct eventfd_ctx *eventfd)
  3854. {
  3855. struct mem_cgroup_eventfd_list *ev, *tmp;
  3856. spin_lock(&memcg_oom_lock);
  3857. list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
  3858. if (ev->eventfd == eventfd) {
  3859. list_del(&ev->list);
  3860. kfree(ev);
  3861. }
  3862. }
  3863. spin_unlock(&memcg_oom_lock);
  3864. }
  3865. static int mem_cgroup_oom_control_read(struct seq_file *sf, void *v)
  3866. {
  3867. struct mem_cgroup *memcg = mem_cgroup_from_seq(sf);
  3868. seq_printf(sf, "oom_kill_disable %d\n", memcg->oom_kill_disable);
  3869. seq_printf(sf, "under_oom %d\n", (bool)memcg->under_oom);
  3870. seq_printf(sf, "oom_kill %lu\n",
  3871. atomic_long_read(&memcg->memory_events[MEMCG_OOM_KILL]));
  3872. return 0;
  3873. }
  3874. static int mem_cgroup_oom_control_write(struct cgroup_subsys_state *css,
  3875. struct cftype *cft, u64 val)
  3876. {
  3877. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3878. /* cannot set to root cgroup and only 0 and 1 are allowed */
  3879. if (mem_cgroup_is_root(memcg) || !((val == 0) || (val == 1)))
  3880. return -EINVAL;
  3881. memcg->oom_kill_disable = val;
  3882. if (!val)
  3883. memcg_oom_recover(memcg);
  3884. return 0;
  3885. }
  3886. #ifdef CONFIG_CGROUP_WRITEBACK
  3887. #include <trace/events/writeback.h>
  3888. static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
  3889. {
  3890. return wb_domain_init(&memcg->cgwb_domain, gfp);
  3891. }
  3892. static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
  3893. {
  3894. wb_domain_exit(&memcg->cgwb_domain);
  3895. }
  3896. static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
  3897. {
  3898. wb_domain_size_changed(&memcg->cgwb_domain);
  3899. }
  3900. struct wb_domain *mem_cgroup_wb_domain(struct bdi_writeback *wb)
  3901. {
  3902. struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
  3903. if (!memcg->css.parent)
  3904. return NULL;
  3905. return &memcg->cgwb_domain;
  3906. }
  3907. /**
  3908. * mem_cgroup_wb_stats - retrieve writeback related stats from its memcg
  3909. * @wb: bdi_writeback in question
  3910. * @pfilepages: out parameter for number of file pages
  3911. * @pheadroom: out parameter for number of allocatable pages according to memcg
  3912. * @pdirty: out parameter for number of dirty pages
  3913. * @pwriteback: out parameter for number of pages under writeback
  3914. *
  3915. * Determine the numbers of file, headroom, dirty, and writeback pages in
  3916. * @wb's memcg. File, dirty and writeback are self-explanatory. Headroom
  3917. * is a bit more involved.
  3918. *
  3919. * A memcg's headroom is "min(max, high) - used". In the hierarchy, the
  3920. * headroom is calculated as the lowest headroom of itself and the
  3921. * ancestors. Note that this doesn't consider the actual amount of
  3922. * available memory in the system. The caller should further cap
  3923. * *@pheadroom accordingly.
  3924. */
  3925. void mem_cgroup_wb_stats(struct bdi_writeback *wb, unsigned long *pfilepages,
  3926. unsigned long *pheadroom, unsigned long *pdirty,
  3927. unsigned long *pwriteback)
  3928. {
  3929. struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
  3930. struct mem_cgroup *parent;
  3931. mem_cgroup_flush_stats();
  3932. *pdirty = memcg_page_state(memcg, NR_FILE_DIRTY);
  3933. *pwriteback = memcg_page_state(memcg, NR_WRITEBACK);
  3934. *pfilepages = memcg_page_state(memcg, NR_INACTIVE_FILE) +
  3935. memcg_page_state(memcg, NR_ACTIVE_FILE);
  3936. *pheadroom = PAGE_COUNTER_MAX;
  3937. while ((parent = parent_mem_cgroup(memcg))) {
  3938. unsigned long ceiling = min(READ_ONCE(memcg->memory.max),
  3939. READ_ONCE(memcg->memory.high));
  3940. unsigned long used = page_counter_read(&memcg->memory);
  3941. *pheadroom = min(*pheadroom, ceiling - min(ceiling, used));
  3942. memcg = parent;
  3943. }
  3944. }
  3945. /*
  3946. * Foreign dirty flushing
  3947. *
  3948. * There's an inherent mismatch between memcg and writeback. The former
  3949. * tracks ownership per-page while the latter per-inode. This was a
  3950. * deliberate design decision because honoring per-page ownership in the
  3951. * writeback path is complicated, may lead to higher CPU and IO overheads
  3952. * and deemed unnecessary given that write-sharing an inode across
  3953. * different cgroups isn't a common use-case.
  3954. *
  3955. * Combined with inode majority-writer ownership switching, this works well
  3956. * enough in most cases but there are some pathological cases. For
  3957. * example, let's say there are two cgroups A and B which keep writing to
  3958. * different but confined parts of the same inode. B owns the inode and
  3959. * A's memory is limited far below B's. A's dirty ratio can rise enough to
  3960. * trigger balance_dirty_pages() sleeps but B's can be low enough to avoid
  3961. * triggering background writeback. A will be slowed down without a way to
  3962. * make writeback of the dirty pages happen.
  3963. *
  3964. * Conditions like the above can lead to a cgroup getting repeatedly and
  3965. * severely throttled after making some progress after each
  3966. * dirty_expire_interval while the underlying IO device is almost
  3967. * completely idle.
  3968. *
  3969. * Solving this problem completely requires matching the ownership tracking
  3970. * granularities between memcg and writeback in either direction. However,
  3971. * the more egregious behaviors can be avoided by simply remembering the
  3972. * most recent foreign dirtying events and initiating remote flushes on
  3973. * them when local writeback isn't enough to keep the memory clean enough.
  3974. *
  3975. * The following two functions implement such mechanism. When a foreign
  3976. * page - a page whose memcg and writeback ownerships don't match - is
  3977. * dirtied, mem_cgroup_track_foreign_dirty() records the inode owning
  3978. * bdi_writeback on the page owning memcg. When balance_dirty_pages()
  3979. * decides that the memcg needs to sleep due to high dirty ratio, it calls
  3980. * mem_cgroup_flush_foreign() which queues writeback on the recorded
  3981. * foreign bdi_writebacks which haven't expired. Both the numbers of
  3982. * recorded bdi_writebacks and concurrent in-flight foreign writebacks are
  3983. * limited to MEMCG_CGWB_FRN_CNT.
  3984. *
  3985. * The mechanism only remembers IDs and doesn't hold any object references.
  3986. * As being wrong occasionally doesn't matter, updates and accesses to the
  3987. * records are lockless and racy.
  3988. */
  3989. void mem_cgroup_track_foreign_dirty_slowpath(struct folio *folio,
  3990. struct bdi_writeback *wb)
  3991. {
  3992. struct mem_cgroup *memcg = folio_memcg(folio);
  3993. struct memcg_cgwb_frn *frn;
  3994. u64 now = get_jiffies_64();
  3995. u64 oldest_at = now;
  3996. int oldest = -1;
  3997. int i;
  3998. trace_track_foreign_dirty(folio, wb);
  3999. /*
  4000. * Pick the slot to use. If there is already a slot for @wb, keep
  4001. * using it. If not replace the oldest one which isn't being
  4002. * written out.
  4003. */
  4004. for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
  4005. frn = &memcg->cgwb_frn[i];
  4006. if (frn->bdi_id == wb->bdi->id &&
  4007. frn->memcg_id == wb->memcg_css->id)
  4008. break;
  4009. if (time_before64(frn->at, oldest_at) &&
  4010. atomic_read(&frn->done.cnt) == 1) {
  4011. oldest = i;
  4012. oldest_at = frn->at;
  4013. }
  4014. }
  4015. if (i < MEMCG_CGWB_FRN_CNT) {
  4016. /*
  4017. * Re-using an existing one. Update timestamp lazily to
  4018. * avoid making the cacheline hot. We want them to be
  4019. * reasonably up-to-date and significantly shorter than
  4020. * dirty_expire_interval as that's what expires the record.
  4021. * Use the shorter of 1s and dirty_expire_interval / 8.
  4022. */
  4023. unsigned long update_intv =
  4024. min_t(unsigned long, HZ,
  4025. msecs_to_jiffies(dirty_expire_interval * 10) / 8);
  4026. if (time_before64(frn->at, now - update_intv))
  4027. frn->at = now;
  4028. } else if (oldest >= 0) {
  4029. /* replace the oldest free one */
  4030. frn = &memcg->cgwb_frn[oldest];
  4031. frn->bdi_id = wb->bdi->id;
  4032. frn->memcg_id = wb->memcg_css->id;
  4033. frn->at = now;
  4034. }
  4035. }
  4036. /* issue foreign writeback flushes for recorded foreign dirtying events */
  4037. void mem_cgroup_flush_foreign(struct bdi_writeback *wb)
  4038. {
  4039. struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
  4040. unsigned long intv = msecs_to_jiffies(dirty_expire_interval * 10);
  4041. u64 now = jiffies_64;
  4042. int i;
  4043. for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
  4044. struct memcg_cgwb_frn *frn = &memcg->cgwb_frn[i];
  4045. /*
  4046. * If the record is older than dirty_expire_interval,
  4047. * writeback on it has already started. No need to kick it
  4048. * off again. Also, don't start a new one if there's
  4049. * already one in flight.
  4050. */
  4051. if (time_after64(frn->at, now - intv) &&
  4052. atomic_read(&frn->done.cnt) == 1) {
  4053. frn->at = 0;
  4054. trace_flush_foreign(wb, frn->bdi_id, frn->memcg_id);
  4055. cgroup_writeback_by_id(frn->bdi_id, frn->memcg_id,
  4056. WB_REASON_FOREIGN_FLUSH,
  4057. &frn->done);
  4058. }
  4059. }
  4060. }
  4061. #else /* CONFIG_CGROUP_WRITEBACK */
  4062. static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
  4063. {
  4064. return 0;
  4065. }
  4066. static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
  4067. {
  4068. }
  4069. static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
  4070. {
  4071. }
  4072. #endif /* CONFIG_CGROUP_WRITEBACK */
  4073. /*
  4074. * DO NOT USE IN NEW FILES.
  4075. *
  4076. * "cgroup.event_control" implementation.
  4077. *
  4078. * This is way over-engineered. It tries to support fully configurable
  4079. * events for each user. Such level of flexibility is completely
  4080. * unnecessary especially in the light of the planned unified hierarchy.
  4081. *
  4082. * Please deprecate this and replace with something simpler if at all
  4083. * possible.
  4084. */
  4085. /*
  4086. * Unregister event and free resources.
  4087. *
  4088. * Gets called from workqueue.
  4089. */
  4090. static void memcg_event_remove(struct work_struct *work)
  4091. {
  4092. struct mem_cgroup_event *event =
  4093. container_of(work, struct mem_cgroup_event, remove);
  4094. struct mem_cgroup *memcg = event->memcg;
  4095. remove_wait_queue(event->wqh, &event->wait);
  4096. event->unregister_event(memcg, event->eventfd);
  4097. /* Notify userspace the event is going away. */
  4098. eventfd_signal(event->eventfd, 1);
  4099. eventfd_ctx_put(event->eventfd);
  4100. kfree(event);
  4101. css_put(&memcg->css);
  4102. }
  4103. /*
  4104. * Gets called on EPOLLHUP on eventfd when user closes it.
  4105. *
  4106. * Called with wqh->lock held and interrupts disabled.
  4107. */
  4108. static int memcg_event_wake(wait_queue_entry_t *wait, unsigned mode,
  4109. int sync, void *key)
  4110. {
  4111. struct mem_cgroup_event *event =
  4112. container_of(wait, struct mem_cgroup_event, wait);
  4113. struct mem_cgroup *memcg = event->memcg;
  4114. __poll_t flags = key_to_poll(key);
  4115. if (flags & EPOLLHUP) {
  4116. /*
  4117. * If the event has been detached at cgroup removal, we
  4118. * can simply return knowing the other side will cleanup
  4119. * for us.
  4120. *
  4121. * We can't race against event freeing since the other
  4122. * side will require wqh->lock via remove_wait_queue(),
  4123. * which we hold.
  4124. */
  4125. spin_lock(&memcg->event_list_lock);
  4126. if (!list_empty(&event->list)) {
  4127. list_del_init(&event->list);
  4128. /*
  4129. * We are in atomic context, but cgroup_event_remove()
  4130. * may sleep, so we have to call it in workqueue.
  4131. */
  4132. schedule_work(&event->remove);
  4133. }
  4134. spin_unlock(&memcg->event_list_lock);
  4135. }
  4136. return 0;
  4137. }
  4138. static void memcg_event_ptable_queue_proc(struct file *file,
  4139. wait_queue_head_t *wqh, poll_table *pt)
  4140. {
  4141. struct mem_cgroup_event *event =
  4142. container_of(pt, struct mem_cgroup_event, pt);
  4143. event->wqh = wqh;
  4144. add_wait_queue(wqh, &event->wait);
  4145. }
  4146. /*
  4147. * DO NOT USE IN NEW FILES.
  4148. *
  4149. * Parse input and register new cgroup event handler.
  4150. *
  4151. * Input must be in format '<event_fd> <control_fd> <args>'.
  4152. * Interpretation of args is defined by control file implementation.
  4153. */
  4154. static ssize_t memcg_write_event_control(struct kernfs_open_file *of,
  4155. char *buf, size_t nbytes, loff_t off)
  4156. {
  4157. struct cgroup_subsys_state *css = of_css(of);
  4158. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  4159. struct mem_cgroup_event *event;
  4160. struct cgroup_subsys_state *cfile_css;
  4161. unsigned int efd, cfd;
  4162. struct fd efile;
  4163. struct fd cfile;
  4164. struct dentry *cdentry;
  4165. const char *name;
  4166. char *endp;
  4167. int ret;
  4168. if (IS_ENABLED(CONFIG_PREEMPT_RT))
  4169. return -EOPNOTSUPP;
  4170. buf = strstrip(buf);
  4171. efd = simple_strtoul(buf, &endp, 10);
  4172. if (*endp != ' ')
  4173. return -EINVAL;
  4174. buf = endp + 1;
  4175. cfd = simple_strtoul(buf, &endp, 10);
  4176. if ((*endp != ' ') && (*endp != '\0'))
  4177. return -EINVAL;
  4178. buf = endp + 1;
  4179. event = kzalloc(sizeof(*event), GFP_KERNEL);
  4180. if (!event)
  4181. return -ENOMEM;
  4182. event->memcg = memcg;
  4183. INIT_LIST_HEAD(&event->list);
  4184. init_poll_funcptr(&event->pt, memcg_event_ptable_queue_proc);
  4185. init_waitqueue_func_entry(&event->wait, memcg_event_wake);
  4186. INIT_WORK(&event->remove, memcg_event_remove);
  4187. efile = fdget(efd);
  4188. if (!efile.file) {
  4189. ret = -EBADF;
  4190. goto out_kfree;
  4191. }
  4192. event->eventfd = eventfd_ctx_fileget(efile.file);
  4193. if (IS_ERR(event->eventfd)) {
  4194. ret = PTR_ERR(event->eventfd);
  4195. goto out_put_efile;
  4196. }
  4197. cfile = fdget(cfd);
  4198. if (!cfile.file) {
  4199. ret = -EBADF;
  4200. goto out_put_eventfd;
  4201. }
  4202. /* the process need read permission on control file */
  4203. /* AV: shouldn't we check that it's been opened for read instead? */
  4204. ret = file_permission(cfile.file, MAY_READ);
  4205. if (ret < 0)
  4206. goto out_put_cfile;
  4207. /*
  4208. * The control file must be a regular cgroup1 file. As a regular cgroup
  4209. * file can't be renamed, it's safe to access its name afterwards.
  4210. */
  4211. cdentry = cfile.file->f_path.dentry;
  4212. if (cdentry->d_sb->s_type != &cgroup_fs_type || !d_is_reg(cdentry)) {
  4213. ret = -EINVAL;
  4214. goto out_put_cfile;
  4215. }
  4216. /*
  4217. * Determine the event callbacks and set them in @event. This used
  4218. * to be done via struct cftype but cgroup core no longer knows
  4219. * about these events. The following is crude but the whole thing
  4220. * is for compatibility anyway.
  4221. *
  4222. * DO NOT ADD NEW FILES.
  4223. */
  4224. name = cdentry->d_name.name;
  4225. if (!strcmp(name, "memory.usage_in_bytes")) {
  4226. event->register_event = mem_cgroup_usage_register_event;
  4227. event->unregister_event = mem_cgroup_usage_unregister_event;
  4228. } else if (!strcmp(name, "memory.oom_control")) {
  4229. event->register_event = mem_cgroup_oom_register_event;
  4230. event->unregister_event = mem_cgroup_oom_unregister_event;
  4231. } else if (!strcmp(name, "memory.pressure_level")) {
  4232. event->register_event = vmpressure_register_event;
  4233. event->unregister_event = vmpressure_unregister_event;
  4234. } else if (!strcmp(name, "memory.memsw.usage_in_bytes")) {
  4235. event->register_event = memsw_cgroup_usage_register_event;
  4236. event->unregister_event = memsw_cgroup_usage_unregister_event;
  4237. } else {
  4238. ret = -EINVAL;
  4239. goto out_put_cfile;
  4240. }
  4241. /*
  4242. * Verify @cfile should belong to @css. Also, remaining events are
  4243. * automatically removed on cgroup destruction but the removal is
  4244. * asynchronous, so take an extra ref on @css.
  4245. */
  4246. cfile_css = css_tryget_online_from_dir(cdentry->d_parent,
  4247. &memory_cgrp_subsys);
  4248. ret = -EINVAL;
  4249. if (IS_ERR(cfile_css))
  4250. goto out_put_cfile;
  4251. if (cfile_css != css) {
  4252. css_put(cfile_css);
  4253. goto out_put_cfile;
  4254. }
  4255. ret = event->register_event(memcg, event->eventfd, buf);
  4256. if (ret)
  4257. goto out_put_css;
  4258. vfs_poll(efile.file, &event->pt);
  4259. spin_lock_irq(&memcg->event_list_lock);
  4260. list_add(&event->list, &memcg->event_list);
  4261. spin_unlock_irq(&memcg->event_list_lock);
  4262. fdput(cfile);
  4263. fdput(efile);
  4264. return nbytes;
  4265. out_put_css:
  4266. css_put(css);
  4267. out_put_cfile:
  4268. fdput(cfile);
  4269. out_put_eventfd:
  4270. eventfd_ctx_put(event->eventfd);
  4271. out_put_efile:
  4272. fdput(efile);
  4273. out_kfree:
  4274. kfree(event);
  4275. return ret;
  4276. }
  4277. #if defined(CONFIG_MEMCG_KMEM) && (defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG))
  4278. static int mem_cgroup_slab_show(struct seq_file *m, void *p)
  4279. {
  4280. /*
  4281. * Deprecated.
  4282. * Please, take a look at tools/cgroup/memcg_slabinfo.py .
  4283. */
  4284. return 0;
  4285. }
  4286. #endif
  4287. static struct cftype mem_cgroup_legacy_files[] = {
  4288. {
  4289. .name = "usage_in_bytes",
  4290. .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
  4291. .read_u64 = mem_cgroup_read_u64,
  4292. },
  4293. {
  4294. .name = "max_usage_in_bytes",
  4295. .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
  4296. .write = mem_cgroup_reset,
  4297. .read_u64 = mem_cgroup_read_u64,
  4298. },
  4299. {
  4300. .name = "limit_in_bytes",
  4301. .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
  4302. .write = mem_cgroup_write,
  4303. .read_u64 = mem_cgroup_read_u64,
  4304. },
  4305. {
  4306. .name = "soft_limit_in_bytes",
  4307. .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
  4308. .write = mem_cgroup_write,
  4309. .read_u64 = mem_cgroup_read_u64,
  4310. },
  4311. {
  4312. .name = "failcnt",
  4313. .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
  4314. .write = mem_cgroup_reset,
  4315. .read_u64 = mem_cgroup_read_u64,
  4316. },
  4317. {
  4318. .name = "stat",
  4319. .seq_show = memcg_stat_show,
  4320. },
  4321. {
  4322. .name = "force_empty",
  4323. .write = mem_cgroup_force_empty_write,
  4324. },
  4325. {
  4326. .name = "use_hierarchy",
  4327. .write_u64 = mem_cgroup_hierarchy_write,
  4328. .read_u64 = mem_cgroup_hierarchy_read,
  4329. },
  4330. {
  4331. .name = "cgroup.event_control", /* XXX: for compat */
  4332. .write = memcg_write_event_control,
  4333. .flags = CFTYPE_NO_PREFIX | CFTYPE_WORLD_WRITABLE,
  4334. },
  4335. {
  4336. .name = "swappiness",
  4337. .read_u64 = mem_cgroup_swappiness_read,
  4338. .write_u64 = mem_cgroup_swappiness_write,
  4339. },
  4340. {
  4341. .name = "move_charge_at_immigrate",
  4342. .read_u64 = mem_cgroup_move_charge_read,
  4343. .write_u64 = mem_cgroup_move_charge_write,
  4344. },
  4345. {
  4346. .name = "oom_control",
  4347. .seq_show = mem_cgroup_oom_control_read,
  4348. .write_u64 = mem_cgroup_oom_control_write,
  4349. },
  4350. {
  4351. .name = "pressure_level",
  4352. },
  4353. #ifdef CONFIG_NUMA
  4354. {
  4355. .name = "numa_stat",
  4356. .seq_show = memcg_numa_stat_show,
  4357. },
  4358. #endif
  4359. {
  4360. .name = "kmem.limit_in_bytes",
  4361. .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
  4362. .write = mem_cgroup_write,
  4363. .read_u64 = mem_cgroup_read_u64,
  4364. },
  4365. {
  4366. .name = "kmem.usage_in_bytes",
  4367. .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
  4368. .read_u64 = mem_cgroup_read_u64,
  4369. },
  4370. {
  4371. .name = "kmem.failcnt",
  4372. .private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
  4373. .write = mem_cgroup_reset,
  4374. .read_u64 = mem_cgroup_read_u64,
  4375. },
  4376. {
  4377. .name = "kmem.max_usage_in_bytes",
  4378. .private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
  4379. .write = mem_cgroup_reset,
  4380. .read_u64 = mem_cgroup_read_u64,
  4381. },
  4382. #if defined(CONFIG_MEMCG_KMEM) && \
  4383. (defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG))
  4384. {
  4385. .name = "kmem.slabinfo",
  4386. .seq_show = mem_cgroup_slab_show,
  4387. },
  4388. #endif
  4389. {
  4390. .name = "kmem.tcp.limit_in_bytes",
  4391. .private = MEMFILE_PRIVATE(_TCP, RES_LIMIT),
  4392. .write = mem_cgroup_write,
  4393. .read_u64 = mem_cgroup_read_u64,
  4394. },
  4395. {
  4396. .name = "kmem.tcp.usage_in_bytes",
  4397. .private = MEMFILE_PRIVATE(_TCP, RES_USAGE),
  4398. .read_u64 = mem_cgroup_read_u64,
  4399. },
  4400. {
  4401. .name = "kmem.tcp.failcnt",
  4402. .private = MEMFILE_PRIVATE(_TCP, RES_FAILCNT),
  4403. .write = mem_cgroup_reset,
  4404. .read_u64 = mem_cgroup_read_u64,
  4405. },
  4406. {
  4407. .name = "kmem.tcp.max_usage_in_bytes",
  4408. .private = MEMFILE_PRIVATE(_TCP, RES_MAX_USAGE),
  4409. .write = mem_cgroup_reset,
  4410. .read_u64 = mem_cgroup_read_u64,
  4411. },
  4412. { }, /* terminate */
  4413. };
  4414. /*
  4415. * Private memory cgroup IDR
  4416. *
  4417. * Swap-out records and page cache shadow entries need to store memcg
  4418. * references in constrained space, so we maintain an ID space that is
  4419. * limited to 16 bit (MEM_CGROUP_ID_MAX), limiting the total number of
  4420. * memory-controlled cgroups to 64k.
  4421. *
  4422. * However, there usually are many references to the offline CSS after
  4423. * the cgroup has been destroyed, such as page cache or reclaimable
  4424. * slab objects, that don't need to hang on to the ID. We want to keep
  4425. * those dead CSS from occupying IDs, or we might quickly exhaust the
  4426. * relatively small ID space and prevent the creation of new cgroups
  4427. * even when there are much fewer than 64k cgroups - possibly none.
  4428. *
  4429. * Maintain a private 16-bit ID space for memcg, and allow the ID to
  4430. * be freed and recycled when it's no longer needed, which is usually
  4431. * when the CSS is offlined.
  4432. *
  4433. * The only exception to that are records of swapped out tmpfs/shmem
  4434. * pages that need to be attributed to live ancestors on swapin. But
  4435. * those references are manageable from userspace.
  4436. */
  4437. static DEFINE_IDR(mem_cgroup_idr);
  4438. static void mem_cgroup_id_remove(struct mem_cgroup *memcg)
  4439. {
  4440. if (memcg->id.id > 0) {
  4441. trace_android_vh_mem_cgroup_id_remove(memcg);
  4442. idr_remove(&mem_cgroup_idr, memcg->id.id);
  4443. memcg->id.id = 0;
  4444. }
  4445. }
  4446. static void __maybe_unused mem_cgroup_id_get_many(struct mem_cgroup *memcg,
  4447. unsigned int n)
  4448. {
  4449. refcount_add(n, &memcg->id.ref);
  4450. }
  4451. static void mem_cgroup_id_put_many(struct mem_cgroup *memcg, unsigned int n)
  4452. {
  4453. if (refcount_sub_and_test(n, &memcg->id.ref)) {
  4454. mem_cgroup_id_remove(memcg);
  4455. /* Memcg ID pins CSS */
  4456. css_put(&memcg->css);
  4457. }
  4458. }
  4459. static inline void mem_cgroup_id_put(struct mem_cgroup *memcg)
  4460. {
  4461. mem_cgroup_id_put_many(memcg, 1);
  4462. }
  4463. /**
  4464. * mem_cgroup_from_id - look up a memcg from a memcg id
  4465. * @id: the memcg id to look up
  4466. *
  4467. * Caller must hold rcu_read_lock().
  4468. */
  4469. struct mem_cgroup *mem_cgroup_from_id(unsigned short id)
  4470. {
  4471. WARN_ON_ONCE(!rcu_read_lock_held());
  4472. return idr_find(&mem_cgroup_idr, id);
  4473. }
  4474. EXPORT_SYMBOL_GPL(mem_cgroup_from_id);
  4475. #ifdef CONFIG_SHRINKER_DEBUG
  4476. struct mem_cgroup *mem_cgroup_get_from_ino(unsigned long ino)
  4477. {
  4478. struct cgroup *cgrp;
  4479. struct cgroup_subsys_state *css;
  4480. struct mem_cgroup *memcg;
  4481. cgrp = cgroup_get_from_id(ino);
  4482. if (IS_ERR(cgrp))
  4483. return ERR_CAST(cgrp);
  4484. css = cgroup_get_e_css(cgrp, &memory_cgrp_subsys);
  4485. if (css)
  4486. memcg = container_of(css, struct mem_cgroup, css);
  4487. else
  4488. memcg = ERR_PTR(-ENOENT);
  4489. cgroup_put(cgrp);
  4490. return memcg;
  4491. }
  4492. #endif
  4493. static int alloc_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
  4494. {
  4495. struct mem_cgroup_per_node *pn;
  4496. pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, node);
  4497. if (!pn)
  4498. return 1;
  4499. pn->lruvec_stats_percpu = alloc_percpu_gfp(struct lruvec_stats_percpu,
  4500. GFP_KERNEL_ACCOUNT);
  4501. if (!pn->lruvec_stats_percpu) {
  4502. kfree(pn);
  4503. return 1;
  4504. }
  4505. lruvec_init(&pn->lruvec);
  4506. pn->memcg = memcg;
  4507. memcg->nodeinfo[node] = pn;
  4508. return 0;
  4509. }
  4510. static void free_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
  4511. {
  4512. struct mem_cgroup_per_node *pn = memcg->nodeinfo[node];
  4513. if (!pn)
  4514. return;
  4515. free_percpu(pn->lruvec_stats_percpu);
  4516. kfree(pn);
  4517. }
  4518. static void __mem_cgroup_free(struct mem_cgroup *memcg)
  4519. {
  4520. int node;
  4521. trace_android_vh_mem_cgroup_free(memcg);
  4522. for_each_node(node)
  4523. free_mem_cgroup_per_node_info(memcg, node);
  4524. kfree(memcg->vmstats);
  4525. free_percpu(memcg->vmstats_percpu);
  4526. kfree(memcg);
  4527. }
  4528. static void mem_cgroup_free(struct mem_cgroup *memcg)
  4529. {
  4530. lru_gen_exit_memcg(memcg);
  4531. memcg_wb_domain_exit(memcg);
  4532. __mem_cgroup_free(memcg);
  4533. }
  4534. static struct mem_cgroup *mem_cgroup_alloc(void)
  4535. {
  4536. struct mem_cgroup *memcg;
  4537. int node;
  4538. int __maybe_unused i;
  4539. long error = -ENOMEM;
  4540. memcg = kzalloc(struct_size(memcg, nodeinfo, nr_node_ids), GFP_KERNEL);
  4541. if (!memcg)
  4542. return ERR_PTR(error);
  4543. memcg->id.id = idr_alloc(&mem_cgroup_idr, NULL,
  4544. 1, MEM_CGROUP_ID_MAX + 1, GFP_KERNEL);
  4545. if (memcg->id.id < 0) {
  4546. error = memcg->id.id;
  4547. goto fail;
  4548. }
  4549. memcg->vmstats = kzalloc(sizeof(struct memcg_vmstats), GFP_KERNEL);
  4550. if (!memcg->vmstats)
  4551. goto fail;
  4552. memcg->vmstats_percpu = alloc_percpu_gfp(struct memcg_vmstats_percpu,
  4553. GFP_KERNEL_ACCOUNT);
  4554. if (!memcg->vmstats_percpu)
  4555. goto fail;
  4556. for_each_node(node)
  4557. if (alloc_mem_cgroup_per_node_info(memcg, node))
  4558. goto fail;
  4559. if (memcg_wb_domain_init(memcg, GFP_KERNEL))
  4560. goto fail;
  4561. INIT_WORK(&memcg->high_work, high_work_func);
  4562. INIT_LIST_HEAD(&memcg->oom_notify);
  4563. mutex_init(&memcg->thresholds_lock);
  4564. spin_lock_init(&memcg->move_lock);
  4565. vmpressure_init(&memcg->vmpressure);
  4566. INIT_LIST_HEAD(&memcg->event_list);
  4567. spin_lock_init(&memcg->event_list_lock);
  4568. memcg->socket_pressure = jiffies;
  4569. #ifdef CONFIG_MEMCG_KMEM
  4570. memcg->kmemcg_id = -1;
  4571. INIT_LIST_HEAD(&memcg->objcg_list);
  4572. #endif
  4573. #ifdef CONFIG_CGROUP_WRITEBACK
  4574. INIT_LIST_HEAD(&memcg->cgwb_list);
  4575. for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
  4576. memcg->cgwb_frn[i].done =
  4577. __WB_COMPLETION_INIT(&memcg_cgwb_frn_waitq);
  4578. #endif
  4579. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  4580. spin_lock_init(&memcg->deferred_split_queue.split_queue_lock);
  4581. INIT_LIST_HEAD(&memcg->deferred_split_queue.split_queue);
  4582. memcg->deferred_split_queue.split_queue_len = 0;
  4583. #endif
  4584. idr_replace(&mem_cgroup_idr, memcg, memcg->id.id);
  4585. lru_gen_init_memcg(memcg);
  4586. trace_android_vh_mem_cgroup_alloc(memcg);
  4587. return memcg;
  4588. fail:
  4589. mem_cgroup_id_remove(memcg);
  4590. __mem_cgroup_free(memcg);
  4591. return ERR_PTR(error);
  4592. }
  4593. static struct cgroup_subsys_state * __ref
  4594. mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
  4595. {
  4596. struct mem_cgroup *parent = mem_cgroup_from_css(parent_css);
  4597. struct mem_cgroup *memcg, *old_memcg;
  4598. old_memcg = set_active_memcg(parent);
  4599. memcg = mem_cgroup_alloc();
  4600. set_active_memcg(old_memcg);
  4601. if (IS_ERR(memcg))
  4602. return ERR_CAST(memcg);
  4603. page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
  4604. memcg->soft_limit = PAGE_COUNTER_MAX;
  4605. #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
  4606. memcg->zswap_max = PAGE_COUNTER_MAX;
  4607. #endif
  4608. page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
  4609. if (parent) {
  4610. memcg->swappiness = mem_cgroup_swappiness(parent);
  4611. memcg->oom_kill_disable = parent->oom_kill_disable;
  4612. page_counter_init(&memcg->memory, &parent->memory);
  4613. page_counter_init(&memcg->swap, &parent->swap);
  4614. page_counter_init(&memcg->kmem, &parent->kmem);
  4615. page_counter_init(&memcg->tcpmem, &parent->tcpmem);
  4616. } else {
  4617. init_memcg_events();
  4618. page_counter_init(&memcg->memory, NULL);
  4619. page_counter_init(&memcg->swap, NULL);
  4620. page_counter_init(&memcg->kmem, NULL);
  4621. page_counter_init(&memcg->tcpmem, NULL);
  4622. root_mem_cgroup = memcg;
  4623. return &memcg->css;
  4624. }
  4625. if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
  4626. static_branch_inc(&memcg_sockets_enabled_key);
  4627. return &memcg->css;
  4628. }
  4629. static int mem_cgroup_css_online(struct cgroup_subsys_state *css)
  4630. {
  4631. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  4632. if (memcg_online_kmem(memcg))
  4633. goto remove_id;
  4634. /*
  4635. * A memcg must be visible for expand_shrinker_info()
  4636. * by the time the maps are allocated. So, we allocate maps
  4637. * here, when for_each_mem_cgroup() can't skip it.
  4638. */
  4639. if (alloc_shrinker_info(memcg))
  4640. goto offline_kmem;
  4641. /* Online state pins memcg ID, memcg ID pins CSS */
  4642. refcount_set(&memcg->id.ref, 1);
  4643. css_get(css);
  4644. if (unlikely(mem_cgroup_is_root(memcg)) && !mem_cgroup_disabled())
  4645. queue_delayed_work(system_unbound_wq, &stats_flush_dwork,
  4646. 2UL*HZ);
  4647. lru_gen_online_memcg(memcg);
  4648. trace_android_vh_mem_cgroup_css_online(css, memcg);
  4649. return 0;
  4650. offline_kmem:
  4651. memcg_offline_kmem(memcg);
  4652. remove_id:
  4653. mem_cgroup_id_remove(memcg);
  4654. return -ENOMEM;
  4655. }
  4656. static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
  4657. {
  4658. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  4659. struct mem_cgroup_event *event, *tmp;
  4660. trace_android_vh_mem_cgroup_css_offline(css, memcg);
  4661. /*
  4662. * Unregister events and notify userspace.
  4663. * Notify userspace about cgroup removing only after rmdir of cgroup
  4664. * directory to avoid race between userspace and kernelspace.
  4665. */
  4666. spin_lock_irq(&memcg->event_list_lock);
  4667. list_for_each_entry_safe(event, tmp, &memcg->event_list, list) {
  4668. list_del_init(&event->list);
  4669. schedule_work(&event->remove);
  4670. }
  4671. spin_unlock_irq(&memcg->event_list_lock);
  4672. page_counter_set_min(&memcg->memory, 0);
  4673. page_counter_set_low(&memcg->memory, 0);
  4674. memcg_offline_kmem(memcg);
  4675. reparent_shrinker_deferred(memcg);
  4676. wb_memcg_offline(memcg);
  4677. lru_gen_offline_memcg(memcg);
  4678. drain_all_stock(memcg);
  4679. mem_cgroup_id_put(memcg);
  4680. }
  4681. static void mem_cgroup_css_released(struct cgroup_subsys_state *css)
  4682. {
  4683. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  4684. invalidate_reclaim_iterators(memcg);
  4685. lru_gen_release_memcg(memcg);
  4686. }
  4687. static void mem_cgroup_css_free(struct cgroup_subsys_state *css)
  4688. {
  4689. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  4690. int __maybe_unused i;
  4691. #ifdef CONFIG_CGROUP_WRITEBACK
  4692. for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
  4693. wb_wait_for_completion(&memcg->cgwb_frn[i].done);
  4694. #endif
  4695. if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
  4696. static_branch_dec(&memcg_sockets_enabled_key);
  4697. if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && memcg->tcpmem_active)
  4698. static_branch_dec(&memcg_sockets_enabled_key);
  4699. vmpressure_cleanup(&memcg->vmpressure);
  4700. cancel_work_sync(&memcg->high_work);
  4701. mem_cgroup_remove_from_trees(memcg);
  4702. free_shrinker_info(memcg);
  4703. mem_cgroup_free(memcg);
  4704. }
  4705. /**
  4706. * mem_cgroup_css_reset - reset the states of a mem_cgroup
  4707. * @css: the target css
  4708. *
  4709. * Reset the states of the mem_cgroup associated with @css. This is
  4710. * invoked when the userland requests disabling on the default hierarchy
  4711. * but the memcg is pinned through dependency. The memcg should stop
  4712. * applying policies and should revert to the vanilla state as it may be
  4713. * made visible again.
  4714. *
  4715. * The current implementation only resets the essential configurations.
  4716. * This needs to be expanded to cover all the visible parts.
  4717. */
  4718. static void mem_cgroup_css_reset(struct cgroup_subsys_state *css)
  4719. {
  4720. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  4721. page_counter_set_max(&memcg->memory, PAGE_COUNTER_MAX);
  4722. page_counter_set_max(&memcg->swap, PAGE_COUNTER_MAX);
  4723. page_counter_set_max(&memcg->kmem, PAGE_COUNTER_MAX);
  4724. page_counter_set_max(&memcg->tcpmem, PAGE_COUNTER_MAX);
  4725. page_counter_set_min(&memcg->memory, 0);
  4726. page_counter_set_low(&memcg->memory, 0);
  4727. page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
  4728. memcg->soft_limit = PAGE_COUNTER_MAX;
  4729. page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
  4730. memcg_wb_domain_size_changed(memcg);
  4731. }
  4732. static void mem_cgroup_css_rstat_flush(struct cgroup_subsys_state *css, int cpu)
  4733. {
  4734. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  4735. struct mem_cgroup *parent = parent_mem_cgroup(memcg);
  4736. struct memcg_vmstats_percpu *statc;
  4737. long delta, v;
  4738. int i, nid;
  4739. statc = per_cpu_ptr(memcg->vmstats_percpu, cpu);
  4740. for (i = 0; i < MEMCG_NR_STAT; i++) {
  4741. /*
  4742. * Collect the aggregated propagation counts of groups
  4743. * below us. We're in a per-cpu loop here and this is
  4744. * a global counter, so the first cycle will get them.
  4745. */
  4746. delta = memcg->vmstats->state_pending[i];
  4747. if (delta)
  4748. memcg->vmstats->state_pending[i] = 0;
  4749. /* Add CPU changes on this level since the last flush */
  4750. v = READ_ONCE(statc->state[i]);
  4751. if (v != statc->state_prev[i]) {
  4752. delta += v - statc->state_prev[i];
  4753. statc->state_prev[i] = v;
  4754. }
  4755. if (!delta)
  4756. continue;
  4757. /* Aggregate counts on this level and propagate upwards */
  4758. memcg->vmstats->state[i] += delta;
  4759. if (parent)
  4760. parent->vmstats->state_pending[i] += delta;
  4761. }
  4762. for (i = 0; i < NR_MEMCG_EVENTS; i++) {
  4763. delta = memcg->vmstats->events_pending[i];
  4764. if (delta)
  4765. memcg->vmstats->events_pending[i] = 0;
  4766. v = READ_ONCE(statc->events[i]);
  4767. if (v != statc->events_prev[i]) {
  4768. delta += v - statc->events_prev[i];
  4769. statc->events_prev[i] = v;
  4770. }
  4771. if (!delta)
  4772. continue;
  4773. memcg->vmstats->events[i] += delta;
  4774. if (parent)
  4775. parent->vmstats->events_pending[i] += delta;
  4776. }
  4777. for_each_node_state(nid, N_MEMORY) {
  4778. struct mem_cgroup_per_node *pn = memcg->nodeinfo[nid];
  4779. struct mem_cgroup_per_node *ppn = NULL;
  4780. struct lruvec_stats_percpu *lstatc;
  4781. if (parent)
  4782. ppn = parent->nodeinfo[nid];
  4783. lstatc = per_cpu_ptr(pn->lruvec_stats_percpu, cpu);
  4784. for (i = 0; i < NR_VM_NODE_STAT_ITEMS; i++) {
  4785. delta = pn->lruvec_stats.state_pending[i];
  4786. if (delta)
  4787. pn->lruvec_stats.state_pending[i] = 0;
  4788. v = READ_ONCE(lstatc->state[i]);
  4789. if (v != lstatc->state_prev[i]) {
  4790. delta += v - lstatc->state_prev[i];
  4791. lstatc->state_prev[i] = v;
  4792. }
  4793. if (!delta)
  4794. continue;
  4795. pn->lruvec_stats.state[i] += delta;
  4796. if (ppn)
  4797. ppn->lruvec_stats.state_pending[i] += delta;
  4798. }
  4799. }
  4800. }
  4801. #ifdef CONFIG_MMU
  4802. /* Handlers for move charge at task migration. */
  4803. static int mem_cgroup_do_precharge(unsigned long count)
  4804. {
  4805. int ret;
  4806. /* Try a single bulk charge without reclaim first, kswapd may wake */
  4807. ret = try_charge(mc.to, GFP_KERNEL & ~__GFP_DIRECT_RECLAIM, count);
  4808. if (!ret) {
  4809. mc.precharge += count;
  4810. return ret;
  4811. }
  4812. /* Try charges one by one with reclaim, but do not retry */
  4813. while (count--) {
  4814. ret = try_charge(mc.to, GFP_KERNEL | __GFP_NORETRY, 1);
  4815. if (ret)
  4816. return ret;
  4817. mc.precharge++;
  4818. cond_resched();
  4819. }
  4820. return 0;
  4821. }
  4822. union mc_target {
  4823. struct page *page;
  4824. swp_entry_t ent;
  4825. };
  4826. enum mc_target_type {
  4827. MC_TARGET_NONE = 0,
  4828. MC_TARGET_PAGE,
  4829. MC_TARGET_SWAP,
  4830. MC_TARGET_DEVICE,
  4831. };
  4832. static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
  4833. unsigned long addr, pte_t ptent)
  4834. {
  4835. struct page *page = vm_normal_page(vma, addr, ptent);
  4836. if (!page || !page_mapped(page))
  4837. return NULL;
  4838. if (PageAnon(page)) {
  4839. if (!(mc.flags & MOVE_ANON))
  4840. return NULL;
  4841. } else {
  4842. if (!(mc.flags & MOVE_FILE))
  4843. return NULL;
  4844. }
  4845. if (!get_page_unless_zero(page))
  4846. return NULL;
  4847. return page;
  4848. }
  4849. #if defined(CONFIG_SWAP) || defined(CONFIG_DEVICE_PRIVATE)
  4850. static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
  4851. pte_t ptent, swp_entry_t *entry)
  4852. {
  4853. struct page *page = NULL;
  4854. swp_entry_t ent = pte_to_swp_entry(ptent);
  4855. if (!(mc.flags & MOVE_ANON))
  4856. return NULL;
  4857. /*
  4858. * Handle device private pages that are not accessible by the CPU, but
  4859. * stored as special swap entries in the page table.
  4860. */
  4861. if (is_device_private_entry(ent)) {
  4862. page = pfn_swap_entry_to_page(ent);
  4863. if (!get_page_unless_zero(page))
  4864. return NULL;
  4865. return page;
  4866. }
  4867. if (non_swap_entry(ent))
  4868. return NULL;
  4869. /*
  4870. * Because swap_cache_get_folio() updates some statistics counter,
  4871. * we call find_get_page() with swapper_space directly.
  4872. */
  4873. page = find_get_page(swap_address_space(ent), swp_offset(ent));
  4874. entry->val = ent.val;
  4875. return page;
  4876. }
  4877. #else
  4878. static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
  4879. pte_t ptent, swp_entry_t *entry)
  4880. {
  4881. return NULL;
  4882. }
  4883. #endif
  4884. static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
  4885. unsigned long addr, pte_t ptent)
  4886. {
  4887. if (!vma->vm_file) /* anonymous vma */
  4888. return NULL;
  4889. if (!(mc.flags & MOVE_FILE))
  4890. return NULL;
  4891. /* page is moved even if it's not RSS of this task(page-faulted). */
  4892. /* shmem/tmpfs may report page out on swap: account for that too. */
  4893. return find_get_incore_page(vma->vm_file->f_mapping,
  4894. linear_page_index(vma, addr));
  4895. }
  4896. /**
  4897. * mem_cgroup_move_account - move account of the page
  4898. * @page: the page
  4899. * @compound: charge the page as compound or small page
  4900. * @from: mem_cgroup which the page is moved from.
  4901. * @to: mem_cgroup which the page is moved to. @from != @to.
  4902. *
  4903. * The caller must make sure the page is not on LRU (isolate_page() is useful.)
  4904. *
  4905. * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
  4906. * from old cgroup.
  4907. */
  4908. static int mem_cgroup_move_account(struct page *page,
  4909. bool compound,
  4910. struct mem_cgroup *from,
  4911. struct mem_cgroup *to)
  4912. {
  4913. struct folio *folio = page_folio(page);
  4914. struct lruvec *from_vec, *to_vec;
  4915. struct pglist_data *pgdat;
  4916. unsigned int nr_pages = compound ? folio_nr_pages(folio) : 1;
  4917. int nid, ret;
  4918. VM_BUG_ON(from == to);
  4919. VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
  4920. VM_BUG_ON(compound && !folio_test_large(folio));
  4921. /*
  4922. * Prevent mem_cgroup_migrate() from looking at
  4923. * page's memory cgroup of its source page while we change it.
  4924. */
  4925. ret = -EBUSY;
  4926. if (!folio_trylock(folio))
  4927. goto out;
  4928. ret = -EINVAL;
  4929. if (folio_memcg(folio) != from)
  4930. goto out_unlock;
  4931. pgdat = folio_pgdat(folio);
  4932. from_vec = mem_cgroup_lruvec(from, pgdat);
  4933. to_vec = mem_cgroup_lruvec(to, pgdat);
  4934. folio_memcg_lock(folio);
  4935. if (folio_test_anon(folio)) {
  4936. if (folio_mapped(folio)) {
  4937. __mod_lruvec_state(from_vec, NR_ANON_MAPPED, -nr_pages);
  4938. __mod_lruvec_state(to_vec, NR_ANON_MAPPED, nr_pages);
  4939. if (folio_test_transhuge(folio)) {
  4940. __mod_lruvec_state(from_vec, NR_ANON_THPS,
  4941. -nr_pages);
  4942. __mod_lruvec_state(to_vec, NR_ANON_THPS,
  4943. nr_pages);
  4944. }
  4945. }
  4946. } else {
  4947. __mod_lruvec_state(from_vec, NR_FILE_PAGES, -nr_pages);
  4948. __mod_lruvec_state(to_vec, NR_FILE_PAGES, nr_pages);
  4949. if (folio_test_swapbacked(folio)) {
  4950. __mod_lruvec_state(from_vec, NR_SHMEM, -nr_pages);
  4951. __mod_lruvec_state(to_vec, NR_SHMEM, nr_pages);
  4952. }
  4953. if (folio_mapped(folio)) {
  4954. __mod_lruvec_state(from_vec, NR_FILE_MAPPED, -nr_pages);
  4955. __mod_lruvec_state(to_vec, NR_FILE_MAPPED, nr_pages);
  4956. }
  4957. if (folio_test_dirty(folio)) {
  4958. struct address_space *mapping = folio_mapping(folio);
  4959. if (mapping_can_writeback(mapping)) {
  4960. __mod_lruvec_state(from_vec, NR_FILE_DIRTY,
  4961. -nr_pages);
  4962. __mod_lruvec_state(to_vec, NR_FILE_DIRTY,
  4963. nr_pages);
  4964. }
  4965. }
  4966. }
  4967. if (folio_test_writeback(folio)) {
  4968. __mod_lruvec_state(from_vec, NR_WRITEBACK, -nr_pages);
  4969. __mod_lruvec_state(to_vec, NR_WRITEBACK, nr_pages);
  4970. }
  4971. /*
  4972. * All state has been migrated, let's switch to the new memcg.
  4973. *
  4974. * It is safe to change page's memcg here because the page
  4975. * is referenced, charged, isolated, and locked: we can't race
  4976. * with (un)charging, migration, LRU putback, or anything else
  4977. * that would rely on a stable page's memory cgroup.
  4978. *
  4979. * Note that lock_page_memcg is a memcg lock, not a page lock,
  4980. * to save space. As soon as we switch page's memory cgroup to a
  4981. * new memcg that isn't locked, the above state can change
  4982. * concurrently again. Make sure we're truly done with it.
  4983. */
  4984. smp_mb();
  4985. css_get(&to->css);
  4986. css_put(&from->css);
  4987. folio->memcg_data = (unsigned long)to;
  4988. __folio_memcg_unlock(from);
  4989. ret = 0;
  4990. nid = folio_nid(folio);
  4991. local_irq_disable();
  4992. mem_cgroup_charge_statistics(to, nr_pages);
  4993. memcg_check_events(to, nid);
  4994. mem_cgroup_charge_statistics(from, -nr_pages);
  4995. memcg_check_events(from, nid);
  4996. local_irq_enable();
  4997. out_unlock:
  4998. folio_unlock(folio);
  4999. out:
  5000. return ret;
  5001. }
  5002. /**
  5003. * get_mctgt_type - get target type of moving charge
  5004. * @vma: the vma the pte to be checked belongs
  5005. * @addr: the address corresponding to the pte to be checked
  5006. * @ptent: the pte to be checked
  5007. * @target: the pointer the target page or swap ent will be stored(can be NULL)
  5008. *
  5009. * Returns
  5010. * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
  5011. * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
  5012. * move charge. if @target is not NULL, the page is stored in target->page
  5013. * with extra refcnt got(Callers should handle it).
  5014. * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
  5015. * target for charge migration. if @target is not NULL, the entry is stored
  5016. * in target->ent.
  5017. * 3(MC_TARGET_DEVICE): like MC_TARGET_PAGE but page is device memory and
  5018. * thus not on the lru.
  5019. * For now we such page is charge like a regular page would be as for all
  5020. * intent and purposes it is just special memory taking the place of a
  5021. * regular page.
  5022. *
  5023. * See Documentations/vm/hmm.txt and include/linux/hmm.h
  5024. *
  5025. * Called with pte lock held.
  5026. */
  5027. static enum mc_target_type get_mctgt_type(struct vm_area_struct *vma,
  5028. unsigned long addr, pte_t ptent, union mc_target *target)
  5029. {
  5030. struct page *page = NULL;
  5031. enum mc_target_type ret = MC_TARGET_NONE;
  5032. swp_entry_t ent = { .val = 0 };
  5033. if (pte_present(ptent))
  5034. page = mc_handle_present_pte(vma, addr, ptent);
  5035. else if (pte_none_mostly(ptent))
  5036. /*
  5037. * PTE markers should be treated as a none pte here, separated
  5038. * from other swap handling below.
  5039. */
  5040. page = mc_handle_file_pte(vma, addr, ptent);
  5041. else if (is_swap_pte(ptent))
  5042. page = mc_handle_swap_pte(vma, ptent, &ent);
  5043. if (!page && !ent.val)
  5044. return ret;
  5045. if (page) {
  5046. /*
  5047. * Do only loose check w/o serialization.
  5048. * mem_cgroup_move_account() checks the page is valid or
  5049. * not under LRU exclusion.
  5050. */
  5051. if (page_memcg(page) == mc.from) {
  5052. ret = MC_TARGET_PAGE;
  5053. if (is_device_private_page(page) ||
  5054. is_device_coherent_page(page))
  5055. ret = MC_TARGET_DEVICE;
  5056. if (target)
  5057. target->page = page;
  5058. }
  5059. if (!ret || !target)
  5060. put_page(page);
  5061. }
  5062. /*
  5063. * There is a swap entry and a page doesn't exist or isn't charged.
  5064. * But we cannot move a tail-page in a THP.
  5065. */
  5066. if (ent.val && !ret && (!page || !PageTransCompound(page)) &&
  5067. mem_cgroup_id(mc.from) == lookup_swap_cgroup_id(ent)) {
  5068. ret = MC_TARGET_SWAP;
  5069. if (target)
  5070. target->ent = ent;
  5071. }
  5072. return ret;
  5073. }
  5074. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  5075. /*
  5076. * We don't consider PMD mapped swapping or file mapped pages because THP does
  5077. * not support them for now.
  5078. * Caller should make sure that pmd_trans_huge(pmd) is true.
  5079. */
  5080. static enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
  5081. unsigned long addr, pmd_t pmd, union mc_target *target)
  5082. {
  5083. struct page *page = NULL;
  5084. enum mc_target_type ret = MC_TARGET_NONE;
  5085. if (unlikely(is_swap_pmd(pmd))) {
  5086. VM_BUG_ON(thp_migration_supported() &&
  5087. !is_pmd_migration_entry(pmd));
  5088. return ret;
  5089. }
  5090. page = pmd_page(pmd);
  5091. VM_BUG_ON_PAGE(!page || !PageHead(page), page);
  5092. if (!(mc.flags & MOVE_ANON))
  5093. return ret;
  5094. if (page_memcg(page) == mc.from) {
  5095. ret = MC_TARGET_PAGE;
  5096. if (target) {
  5097. get_page(page);
  5098. target->page = page;
  5099. }
  5100. }
  5101. return ret;
  5102. }
  5103. #else
  5104. static inline enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
  5105. unsigned long addr, pmd_t pmd, union mc_target *target)
  5106. {
  5107. return MC_TARGET_NONE;
  5108. }
  5109. #endif
  5110. static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
  5111. unsigned long addr, unsigned long end,
  5112. struct mm_walk *walk)
  5113. {
  5114. struct vm_area_struct *vma = walk->vma;
  5115. pte_t *pte;
  5116. spinlock_t *ptl;
  5117. ptl = pmd_trans_huge_lock(pmd, vma);
  5118. if (ptl) {
  5119. /*
  5120. * Note their can not be MC_TARGET_DEVICE for now as we do not
  5121. * support transparent huge page with MEMORY_DEVICE_PRIVATE but
  5122. * this might change.
  5123. */
  5124. if (get_mctgt_type_thp(vma, addr, *pmd, NULL) == MC_TARGET_PAGE)
  5125. mc.precharge += HPAGE_PMD_NR;
  5126. spin_unlock(ptl);
  5127. return 0;
  5128. }
  5129. if (pmd_trans_unstable(pmd))
  5130. return 0;
  5131. pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
  5132. for (; addr != end; pte++, addr += PAGE_SIZE)
  5133. if (get_mctgt_type(vma, addr, *pte, NULL))
  5134. mc.precharge++; /* increment precharge temporarily */
  5135. pte_unmap_unlock(pte - 1, ptl);
  5136. cond_resched();
  5137. return 0;
  5138. }
  5139. static const struct mm_walk_ops precharge_walk_ops = {
  5140. .pmd_entry = mem_cgroup_count_precharge_pte_range,
  5141. .walk_lock = PGWALK_RDLOCK,
  5142. };
  5143. static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
  5144. {
  5145. unsigned long precharge;
  5146. mmap_read_lock(mm);
  5147. walk_page_range(mm, 0, ULONG_MAX, &precharge_walk_ops, NULL);
  5148. mmap_read_unlock(mm);
  5149. precharge = mc.precharge;
  5150. mc.precharge = 0;
  5151. return precharge;
  5152. }
  5153. static int mem_cgroup_precharge_mc(struct mm_struct *mm)
  5154. {
  5155. unsigned long precharge = mem_cgroup_count_precharge(mm);
  5156. VM_BUG_ON(mc.moving_task);
  5157. mc.moving_task = current;
  5158. return mem_cgroup_do_precharge(precharge);
  5159. }
  5160. /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
  5161. static void __mem_cgroup_clear_mc(void)
  5162. {
  5163. struct mem_cgroup *from = mc.from;
  5164. struct mem_cgroup *to = mc.to;
  5165. /* we must uncharge all the leftover precharges from mc.to */
  5166. if (mc.precharge) {
  5167. cancel_charge(mc.to, mc.precharge);
  5168. mc.precharge = 0;
  5169. }
  5170. /*
  5171. * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
  5172. * we must uncharge here.
  5173. */
  5174. if (mc.moved_charge) {
  5175. cancel_charge(mc.from, mc.moved_charge);
  5176. mc.moved_charge = 0;
  5177. }
  5178. /* we must fixup refcnts and charges */
  5179. if (mc.moved_swap) {
  5180. /* uncharge swap account from the old cgroup */
  5181. if (!mem_cgroup_is_root(mc.from))
  5182. page_counter_uncharge(&mc.from->memsw, mc.moved_swap);
  5183. mem_cgroup_id_put_many(mc.from, mc.moved_swap);
  5184. /*
  5185. * we charged both to->memory and to->memsw, so we
  5186. * should uncharge to->memory.
  5187. */
  5188. if (!mem_cgroup_is_root(mc.to))
  5189. page_counter_uncharge(&mc.to->memory, mc.moved_swap);
  5190. mc.moved_swap = 0;
  5191. }
  5192. memcg_oom_recover(from);
  5193. memcg_oom_recover(to);
  5194. wake_up_all(&mc.waitq);
  5195. }
  5196. static void mem_cgroup_clear_mc(void)
  5197. {
  5198. struct mm_struct *mm = mc.mm;
  5199. /*
  5200. * we must clear moving_task before waking up waiters at the end of
  5201. * task migration.
  5202. */
  5203. mc.moving_task = NULL;
  5204. __mem_cgroup_clear_mc();
  5205. spin_lock(&mc.lock);
  5206. mc.from = NULL;
  5207. mc.to = NULL;
  5208. mc.mm = NULL;
  5209. spin_unlock(&mc.lock);
  5210. mmput(mm);
  5211. }
  5212. static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
  5213. {
  5214. struct cgroup_subsys_state *css;
  5215. struct mem_cgroup *memcg = NULL; /* unneeded init to make gcc happy */
  5216. struct mem_cgroup *from;
  5217. struct task_struct *leader, *p;
  5218. struct mm_struct *mm;
  5219. unsigned long move_flags;
  5220. int ret = 0;
  5221. /* charge immigration isn't supported on the default hierarchy */
  5222. if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
  5223. return 0;
  5224. /*
  5225. * Multi-process migrations only happen on the default hierarchy
  5226. * where charge immigration is not used. Perform charge
  5227. * immigration if @tset contains a leader and whine if there are
  5228. * multiple.
  5229. */
  5230. p = NULL;
  5231. cgroup_taskset_for_each_leader(leader, css, tset) {
  5232. WARN_ON_ONCE(p);
  5233. p = leader;
  5234. memcg = mem_cgroup_from_css(css);
  5235. }
  5236. if (!p)
  5237. return 0;
  5238. /*
  5239. * We are now committed to this value whatever it is. Changes in this
  5240. * tunable will only affect upcoming migrations, not the current one.
  5241. * So we need to save it, and keep it going.
  5242. */
  5243. move_flags = READ_ONCE(memcg->move_charge_at_immigrate);
  5244. if (!move_flags)
  5245. return 0;
  5246. from = mem_cgroup_from_task(p);
  5247. VM_BUG_ON(from == memcg);
  5248. mm = get_task_mm(p);
  5249. if (!mm)
  5250. return 0;
  5251. /* We move charges only when we move a owner of the mm */
  5252. if (mm->owner == p) {
  5253. VM_BUG_ON(mc.from);
  5254. VM_BUG_ON(mc.to);
  5255. VM_BUG_ON(mc.precharge);
  5256. VM_BUG_ON(mc.moved_charge);
  5257. VM_BUG_ON(mc.moved_swap);
  5258. spin_lock(&mc.lock);
  5259. mc.mm = mm;
  5260. mc.from = from;
  5261. mc.to = memcg;
  5262. mc.flags = move_flags;
  5263. spin_unlock(&mc.lock);
  5264. /* We set mc.moving_task later */
  5265. ret = mem_cgroup_precharge_mc(mm);
  5266. if (ret)
  5267. mem_cgroup_clear_mc();
  5268. } else {
  5269. mmput(mm);
  5270. }
  5271. return ret;
  5272. }
  5273. static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
  5274. {
  5275. if (mc.to)
  5276. mem_cgroup_clear_mc();
  5277. }
  5278. static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
  5279. unsigned long addr, unsigned long end,
  5280. struct mm_walk *walk)
  5281. {
  5282. int ret = 0;
  5283. struct vm_area_struct *vma = walk->vma;
  5284. pte_t *pte;
  5285. spinlock_t *ptl;
  5286. enum mc_target_type target_type;
  5287. union mc_target target;
  5288. struct page *page;
  5289. ptl = pmd_trans_huge_lock(pmd, vma);
  5290. if (ptl) {
  5291. if (mc.precharge < HPAGE_PMD_NR) {
  5292. spin_unlock(ptl);
  5293. return 0;
  5294. }
  5295. target_type = get_mctgt_type_thp(vma, addr, *pmd, &target);
  5296. if (target_type == MC_TARGET_PAGE) {
  5297. page = target.page;
  5298. if (!isolate_lru_page(page)) {
  5299. if (!mem_cgroup_move_account(page, true,
  5300. mc.from, mc.to)) {
  5301. mc.precharge -= HPAGE_PMD_NR;
  5302. mc.moved_charge += HPAGE_PMD_NR;
  5303. }
  5304. putback_lru_page(page);
  5305. }
  5306. put_page(page);
  5307. } else if (target_type == MC_TARGET_DEVICE) {
  5308. page = target.page;
  5309. if (!mem_cgroup_move_account(page, true,
  5310. mc.from, mc.to)) {
  5311. mc.precharge -= HPAGE_PMD_NR;
  5312. mc.moved_charge += HPAGE_PMD_NR;
  5313. }
  5314. put_page(page);
  5315. }
  5316. spin_unlock(ptl);
  5317. return 0;
  5318. }
  5319. if (pmd_trans_unstable(pmd))
  5320. return 0;
  5321. retry:
  5322. pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
  5323. for (; addr != end; addr += PAGE_SIZE) {
  5324. pte_t ptent = *(pte++);
  5325. bool device = false;
  5326. swp_entry_t ent;
  5327. if (!mc.precharge)
  5328. break;
  5329. switch (get_mctgt_type(vma, addr, ptent, &target)) {
  5330. case MC_TARGET_DEVICE:
  5331. device = true;
  5332. fallthrough;
  5333. case MC_TARGET_PAGE:
  5334. page = target.page;
  5335. /*
  5336. * We can have a part of the split pmd here. Moving it
  5337. * can be done but it would be too convoluted so simply
  5338. * ignore such a partial THP and keep it in original
  5339. * memcg. There should be somebody mapping the head.
  5340. */
  5341. if (PageTransCompound(page))
  5342. goto put;
  5343. if (!device && isolate_lru_page(page))
  5344. goto put;
  5345. if (!mem_cgroup_move_account(page, false,
  5346. mc.from, mc.to)) {
  5347. mc.precharge--;
  5348. /* we uncharge from mc.from later. */
  5349. mc.moved_charge++;
  5350. }
  5351. if (!device)
  5352. putback_lru_page(page);
  5353. put: /* get_mctgt_type() gets the page */
  5354. put_page(page);
  5355. break;
  5356. case MC_TARGET_SWAP:
  5357. ent = target.ent;
  5358. if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to)) {
  5359. mc.precharge--;
  5360. mem_cgroup_id_get_many(mc.to, 1);
  5361. /* we fixup other refcnts and charges later. */
  5362. mc.moved_swap++;
  5363. }
  5364. break;
  5365. default:
  5366. break;
  5367. }
  5368. }
  5369. pte_unmap_unlock(pte - 1, ptl);
  5370. cond_resched();
  5371. if (addr != end) {
  5372. /*
  5373. * We have consumed all precharges we got in can_attach().
  5374. * We try charge one by one, but don't do any additional
  5375. * charges to mc.to if we have failed in charge once in attach()
  5376. * phase.
  5377. */
  5378. ret = mem_cgroup_do_precharge(1);
  5379. if (!ret)
  5380. goto retry;
  5381. }
  5382. return ret;
  5383. }
  5384. static const struct mm_walk_ops charge_walk_ops = {
  5385. .pmd_entry = mem_cgroup_move_charge_pte_range,
  5386. .walk_lock = PGWALK_RDLOCK,
  5387. };
  5388. static void mem_cgroup_move_charge(void)
  5389. {
  5390. lru_add_drain_all();
  5391. /*
  5392. * Signal lock_page_memcg() to take the memcg's move_lock
  5393. * while we're moving its pages to another memcg. Then wait
  5394. * for already started RCU-only updates to finish.
  5395. */
  5396. atomic_inc(&mc.from->moving_account);
  5397. synchronize_rcu();
  5398. retry:
  5399. if (unlikely(!mmap_read_trylock(mc.mm))) {
  5400. /*
  5401. * Someone who are holding the mmap_lock might be waiting in
  5402. * waitq. So we cancel all extra charges, wake up all waiters,
  5403. * and retry. Because we cancel precharges, we might not be able
  5404. * to move enough charges, but moving charge is a best-effort
  5405. * feature anyway, so it wouldn't be a big problem.
  5406. */
  5407. __mem_cgroup_clear_mc();
  5408. cond_resched();
  5409. goto retry;
  5410. }
  5411. /*
  5412. * When we have consumed all precharges and failed in doing
  5413. * additional charge, the page walk just aborts.
  5414. */
  5415. walk_page_range(mc.mm, 0, ULONG_MAX, &charge_walk_ops, NULL);
  5416. mmap_read_unlock(mc.mm);
  5417. atomic_dec(&mc.from->moving_account);
  5418. }
  5419. static void mem_cgroup_move_task(void)
  5420. {
  5421. if (mc.to) {
  5422. mem_cgroup_move_charge();
  5423. mem_cgroup_clear_mc();
  5424. }
  5425. }
  5426. #else /* !CONFIG_MMU */
  5427. static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
  5428. {
  5429. return 0;
  5430. }
  5431. static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
  5432. {
  5433. }
  5434. static void mem_cgroup_move_task(void)
  5435. {
  5436. }
  5437. #endif
  5438. #ifdef CONFIG_LRU_GEN
  5439. static void mem_cgroup_attach(struct cgroup_taskset *tset)
  5440. {
  5441. struct task_struct *task;
  5442. struct cgroup_subsys_state *css;
  5443. /* find the first leader if there is any */
  5444. cgroup_taskset_for_each_leader(task, css, tset)
  5445. break;
  5446. if (!task)
  5447. return;
  5448. task_lock(task);
  5449. if (task->mm && READ_ONCE(task->mm->owner) == task)
  5450. lru_gen_migrate_mm(task->mm);
  5451. task_unlock(task);
  5452. }
  5453. #else
  5454. static void mem_cgroup_attach(struct cgroup_taskset *tset)
  5455. {
  5456. }
  5457. #endif /* CONFIG_LRU_GEN */
  5458. static int seq_puts_memcg_tunable(struct seq_file *m, unsigned long value)
  5459. {
  5460. if (value == PAGE_COUNTER_MAX)
  5461. seq_puts(m, "max\n");
  5462. else
  5463. seq_printf(m, "%llu\n", (u64)value * PAGE_SIZE);
  5464. return 0;
  5465. }
  5466. static u64 memory_current_read(struct cgroup_subsys_state *css,
  5467. struct cftype *cft)
  5468. {
  5469. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  5470. return (u64)page_counter_read(&memcg->memory) * PAGE_SIZE;
  5471. }
  5472. static u64 memory_peak_read(struct cgroup_subsys_state *css,
  5473. struct cftype *cft)
  5474. {
  5475. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  5476. return (u64)memcg->memory.watermark * PAGE_SIZE;
  5477. }
  5478. static int memory_min_show(struct seq_file *m, void *v)
  5479. {
  5480. return seq_puts_memcg_tunable(m,
  5481. READ_ONCE(mem_cgroup_from_seq(m)->memory.min));
  5482. }
  5483. static ssize_t memory_min_write(struct kernfs_open_file *of,
  5484. char *buf, size_t nbytes, loff_t off)
  5485. {
  5486. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  5487. unsigned long min;
  5488. int err;
  5489. buf = strstrip(buf);
  5490. err = page_counter_memparse(buf, "max", &min);
  5491. if (err)
  5492. return err;
  5493. page_counter_set_min(&memcg->memory, min);
  5494. return nbytes;
  5495. }
  5496. static int memory_low_show(struct seq_file *m, void *v)
  5497. {
  5498. return seq_puts_memcg_tunable(m,
  5499. READ_ONCE(mem_cgroup_from_seq(m)->memory.low));
  5500. }
  5501. static ssize_t memory_low_write(struct kernfs_open_file *of,
  5502. char *buf, size_t nbytes, loff_t off)
  5503. {
  5504. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  5505. unsigned long low;
  5506. int err;
  5507. buf = strstrip(buf);
  5508. err = page_counter_memparse(buf, "max", &low);
  5509. if (err)
  5510. return err;
  5511. page_counter_set_low(&memcg->memory, low);
  5512. return nbytes;
  5513. }
  5514. static int memory_high_show(struct seq_file *m, void *v)
  5515. {
  5516. return seq_puts_memcg_tunable(m,
  5517. READ_ONCE(mem_cgroup_from_seq(m)->memory.high));
  5518. }
  5519. static ssize_t memory_high_write(struct kernfs_open_file *of,
  5520. char *buf, size_t nbytes, loff_t off)
  5521. {
  5522. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  5523. unsigned int nr_retries = MAX_RECLAIM_RETRIES;
  5524. bool drained = false;
  5525. unsigned long high;
  5526. int err;
  5527. buf = strstrip(buf);
  5528. err = page_counter_memparse(buf, "max", &high);
  5529. if (err)
  5530. return err;
  5531. page_counter_set_high(&memcg->memory, high);
  5532. for (;;) {
  5533. unsigned long nr_pages = page_counter_read(&memcg->memory);
  5534. unsigned long reclaimed;
  5535. if (nr_pages <= high)
  5536. break;
  5537. if (signal_pending(current))
  5538. break;
  5539. if (!drained) {
  5540. drain_all_stock(memcg);
  5541. drained = true;
  5542. continue;
  5543. }
  5544. reclaimed = try_to_free_mem_cgroup_pages(memcg, nr_pages - high,
  5545. GFP_KERNEL, MEMCG_RECLAIM_MAY_SWAP);
  5546. if (!reclaimed && !nr_retries--)
  5547. break;
  5548. }
  5549. memcg_wb_domain_size_changed(memcg);
  5550. return nbytes;
  5551. }
  5552. static int memory_max_show(struct seq_file *m, void *v)
  5553. {
  5554. return seq_puts_memcg_tunable(m,
  5555. READ_ONCE(mem_cgroup_from_seq(m)->memory.max));
  5556. }
  5557. static ssize_t memory_max_write(struct kernfs_open_file *of,
  5558. char *buf, size_t nbytes, loff_t off)
  5559. {
  5560. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  5561. unsigned int nr_reclaims = MAX_RECLAIM_RETRIES;
  5562. bool drained = false;
  5563. unsigned long max;
  5564. int err;
  5565. buf = strstrip(buf);
  5566. err = page_counter_memparse(buf, "max", &max);
  5567. if (err)
  5568. return err;
  5569. xchg(&memcg->memory.max, max);
  5570. for (;;) {
  5571. unsigned long nr_pages = page_counter_read(&memcg->memory);
  5572. if (nr_pages <= max)
  5573. break;
  5574. if (signal_pending(current))
  5575. break;
  5576. if (!drained) {
  5577. drain_all_stock(memcg);
  5578. drained = true;
  5579. continue;
  5580. }
  5581. if (nr_reclaims) {
  5582. if (!try_to_free_mem_cgroup_pages(memcg, nr_pages - max,
  5583. GFP_KERNEL, MEMCG_RECLAIM_MAY_SWAP))
  5584. nr_reclaims--;
  5585. continue;
  5586. }
  5587. memcg_memory_event(memcg, MEMCG_OOM);
  5588. if (!mem_cgroup_out_of_memory(memcg, GFP_KERNEL, 0))
  5589. break;
  5590. }
  5591. memcg_wb_domain_size_changed(memcg);
  5592. return nbytes;
  5593. }
  5594. static void __memory_events_show(struct seq_file *m, atomic_long_t *events)
  5595. {
  5596. seq_printf(m, "low %lu\n", atomic_long_read(&events[MEMCG_LOW]));
  5597. seq_printf(m, "high %lu\n", atomic_long_read(&events[MEMCG_HIGH]));
  5598. seq_printf(m, "max %lu\n", atomic_long_read(&events[MEMCG_MAX]));
  5599. seq_printf(m, "oom %lu\n", atomic_long_read(&events[MEMCG_OOM]));
  5600. seq_printf(m, "oom_kill %lu\n",
  5601. atomic_long_read(&events[MEMCG_OOM_KILL]));
  5602. seq_printf(m, "oom_group_kill %lu\n",
  5603. atomic_long_read(&events[MEMCG_OOM_GROUP_KILL]));
  5604. }
  5605. static int memory_events_show(struct seq_file *m, void *v)
  5606. {
  5607. struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
  5608. __memory_events_show(m, memcg->memory_events);
  5609. return 0;
  5610. }
  5611. static int memory_events_local_show(struct seq_file *m, void *v)
  5612. {
  5613. struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
  5614. __memory_events_show(m, memcg->memory_events_local);
  5615. return 0;
  5616. }
  5617. static int memory_stat_show(struct seq_file *m, void *v)
  5618. {
  5619. struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
  5620. char *buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
  5621. if (!buf)
  5622. return -ENOMEM;
  5623. memory_stat_format(memcg, buf, PAGE_SIZE);
  5624. seq_puts(m, buf);
  5625. kfree(buf);
  5626. return 0;
  5627. }
  5628. #ifdef CONFIG_NUMA
  5629. static inline unsigned long lruvec_page_state_output(struct lruvec *lruvec,
  5630. int item)
  5631. {
  5632. return lruvec_page_state(lruvec, item) * memcg_page_state_unit(item);
  5633. }
  5634. static int memory_numa_stat_show(struct seq_file *m, void *v)
  5635. {
  5636. int i;
  5637. struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
  5638. mem_cgroup_flush_stats();
  5639. for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
  5640. int nid;
  5641. if (memory_stats[i].idx >= NR_VM_NODE_STAT_ITEMS)
  5642. continue;
  5643. seq_printf(m, "%s", memory_stats[i].name);
  5644. for_each_node_state(nid, N_MEMORY) {
  5645. u64 size;
  5646. struct lruvec *lruvec;
  5647. lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
  5648. size = lruvec_page_state_output(lruvec,
  5649. memory_stats[i].idx);
  5650. seq_printf(m, " N%d=%llu", nid, size);
  5651. }
  5652. seq_putc(m, '\n');
  5653. }
  5654. return 0;
  5655. }
  5656. #endif
  5657. static int memory_oom_group_show(struct seq_file *m, void *v)
  5658. {
  5659. struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
  5660. seq_printf(m, "%d\n", memcg->oom_group);
  5661. return 0;
  5662. }
  5663. static ssize_t memory_oom_group_write(struct kernfs_open_file *of,
  5664. char *buf, size_t nbytes, loff_t off)
  5665. {
  5666. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  5667. int ret, oom_group;
  5668. buf = strstrip(buf);
  5669. if (!buf)
  5670. return -EINVAL;
  5671. ret = kstrtoint(buf, 0, &oom_group);
  5672. if (ret)
  5673. return ret;
  5674. if (oom_group != 0 && oom_group != 1)
  5675. return -EINVAL;
  5676. memcg->oom_group = oom_group;
  5677. return nbytes;
  5678. }
  5679. static ssize_t memory_reclaim(struct kernfs_open_file *of, char *buf,
  5680. size_t nbytes, loff_t off)
  5681. {
  5682. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  5683. unsigned int nr_retries = MAX_RECLAIM_RETRIES;
  5684. unsigned long nr_to_reclaim, nr_reclaimed = 0;
  5685. unsigned int reclaim_options;
  5686. int err;
  5687. buf = strstrip(buf);
  5688. err = page_counter_memparse(buf, "", &nr_to_reclaim);
  5689. if (err)
  5690. return err;
  5691. reclaim_options = MEMCG_RECLAIM_MAY_SWAP | MEMCG_RECLAIM_PROACTIVE;
  5692. while (nr_reclaimed < nr_to_reclaim) {
  5693. unsigned long reclaimed;
  5694. if (signal_pending(current))
  5695. return -EINTR;
  5696. /*
  5697. * This is the final attempt, drain percpu lru caches in the
  5698. * hope of introducing more evictable pages for
  5699. * try_to_free_mem_cgroup_pages().
  5700. */
  5701. if (!nr_retries)
  5702. lru_add_drain_all();
  5703. reclaimed = try_to_free_mem_cgroup_pages(memcg,
  5704. nr_to_reclaim - nr_reclaimed,
  5705. GFP_KERNEL, reclaim_options);
  5706. if (!reclaimed && !nr_retries--)
  5707. return -EAGAIN;
  5708. nr_reclaimed += reclaimed;
  5709. }
  5710. return nbytes;
  5711. }
  5712. static struct cftype memory_files[] = {
  5713. {
  5714. .name = "current",
  5715. .flags = CFTYPE_NOT_ON_ROOT,
  5716. .read_u64 = memory_current_read,
  5717. },
  5718. {
  5719. .name = "peak",
  5720. .flags = CFTYPE_NOT_ON_ROOT,
  5721. .read_u64 = memory_peak_read,
  5722. },
  5723. {
  5724. .name = "min",
  5725. .flags = CFTYPE_NOT_ON_ROOT,
  5726. .seq_show = memory_min_show,
  5727. .write = memory_min_write,
  5728. },
  5729. {
  5730. .name = "low",
  5731. .flags = CFTYPE_NOT_ON_ROOT,
  5732. .seq_show = memory_low_show,
  5733. .write = memory_low_write,
  5734. },
  5735. {
  5736. .name = "high",
  5737. .flags = CFTYPE_NOT_ON_ROOT,
  5738. .seq_show = memory_high_show,
  5739. .write = memory_high_write,
  5740. },
  5741. {
  5742. .name = "max",
  5743. .flags = CFTYPE_NOT_ON_ROOT,
  5744. .seq_show = memory_max_show,
  5745. .write = memory_max_write,
  5746. },
  5747. {
  5748. .name = "events",
  5749. .flags = CFTYPE_NOT_ON_ROOT,
  5750. .file_offset = offsetof(struct mem_cgroup, events_file),
  5751. .seq_show = memory_events_show,
  5752. },
  5753. {
  5754. .name = "events.local",
  5755. .flags = CFTYPE_NOT_ON_ROOT,
  5756. .file_offset = offsetof(struct mem_cgroup, events_local_file),
  5757. .seq_show = memory_events_local_show,
  5758. },
  5759. {
  5760. .name = "stat",
  5761. .seq_show = memory_stat_show,
  5762. },
  5763. #ifdef CONFIG_NUMA
  5764. {
  5765. .name = "numa_stat",
  5766. .seq_show = memory_numa_stat_show,
  5767. },
  5768. #endif
  5769. {
  5770. .name = "oom.group",
  5771. .flags = CFTYPE_NOT_ON_ROOT | CFTYPE_NS_DELEGATABLE,
  5772. .seq_show = memory_oom_group_show,
  5773. .write = memory_oom_group_write,
  5774. },
  5775. {
  5776. .name = "reclaim",
  5777. .flags = CFTYPE_NS_DELEGATABLE,
  5778. .write = memory_reclaim,
  5779. },
  5780. { } /* terminate */
  5781. };
  5782. struct cgroup_subsys memory_cgrp_subsys = {
  5783. .css_alloc = mem_cgroup_css_alloc,
  5784. .css_online = mem_cgroup_css_online,
  5785. .css_offline = mem_cgroup_css_offline,
  5786. .css_released = mem_cgroup_css_released,
  5787. .css_free = mem_cgroup_css_free,
  5788. .css_reset = mem_cgroup_css_reset,
  5789. .css_rstat_flush = mem_cgroup_css_rstat_flush,
  5790. .can_attach = mem_cgroup_can_attach,
  5791. .attach = mem_cgroup_attach,
  5792. .cancel_attach = mem_cgroup_cancel_attach,
  5793. .post_attach = mem_cgroup_move_task,
  5794. .dfl_cftypes = memory_files,
  5795. .legacy_cftypes = mem_cgroup_legacy_files,
  5796. .early_init = 0,
  5797. };
  5798. /*
  5799. * This function calculates an individual cgroup's effective
  5800. * protection which is derived from its own memory.min/low, its
  5801. * parent's and siblings' settings, as well as the actual memory
  5802. * distribution in the tree.
  5803. *
  5804. * The following rules apply to the effective protection values:
  5805. *
  5806. * 1. At the first level of reclaim, effective protection is equal to
  5807. * the declared protection in memory.min and memory.low.
  5808. *
  5809. * 2. To enable safe delegation of the protection configuration, at
  5810. * subsequent levels the effective protection is capped to the
  5811. * parent's effective protection.
  5812. *
  5813. * 3. To make complex and dynamic subtrees easier to configure, the
  5814. * user is allowed to overcommit the declared protection at a given
  5815. * level. If that is the case, the parent's effective protection is
  5816. * distributed to the children in proportion to how much protection
  5817. * they have declared and how much of it they are utilizing.
  5818. *
  5819. * This makes distribution proportional, but also work-conserving:
  5820. * if one cgroup claims much more protection than it uses memory,
  5821. * the unused remainder is available to its siblings.
  5822. *
  5823. * 4. Conversely, when the declared protection is undercommitted at a
  5824. * given level, the distribution of the larger parental protection
  5825. * budget is NOT proportional. A cgroup's protection from a sibling
  5826. * is capped to its own memory.min/low setting.
  5827. *
  5828. * 5. However, to allow protecting recursive subtrees from each other
  5829. * without having to declare each individual cgroup's fixed share
  5830. * of the ancestor's claim to protection, any unutilized -
  5831. * "floating" - protection from up the tree is distributed in
  5832. * proportion to each cgroup's *usage*. This makes the protection
  5833. * neutral wrt sibling cgroups and lets them compete freely over
  5834. * the shared parental protection budget, but it protects the
  5835. * subtree as a whole from neighboring subtrees.
  5836. *
  5837. * Note that 4. and 5. are not in conflict: 4. is about protecting
  5838. * against immediate siblings whereas 5. is about protecting against
  5839. * neighboring subtrees.
  5840. */
  5841. static unsigned long effective_protection(unsigned long usage,
  5842. unsigned long parent_usage,
  5843. unsigned long setting,
  5844. unsigned long parent_effective,
  5845. unsigned long siblings_protected)
  5846. {
  5847. unsigned long protected;
  5848. unsigned long ep;
  5849. protected = min(usage, setting);
  5850. /*
  5851. * If all cgroups at this level combined claim and use more
  5852. * protection then what the parent affords them, distribute
  5853. * shares in proportion to utilization.
  5854. *
  5855. * We are using actual utilization rather than the statically
  5856. * claimed protection in order to be work-conserving: claimed
  5857. * but unused protection is available to siblings that would
  5858. * otherwise get a smaller chunk than what they claimed.
  5859. */
  5860. if (siblings_protected > parent_effective)
  5861. return protected * parent_effective / siblings_protected;
  5862. /*
  5863. * Ok, utilized protection of all children is within what the
  5864. * parent affords them, so we know whatever this child claims
  5865. * and utilizes is effectively protected.
  5866. *
  5867. * If there is unprotected usage beyond this value, reclaim
  5868. * will apply pressure in proportion to that amount.
  5869. *
  5870. * If there is unutilized protection, the cgroup will be fully
  5871. * shielded from reclaim, but we do return a smaller value for
  5872. * protection than what the group could enjoy in theory. This
  5873. * is okay. With the overcommit distribution above, effective
  5874. * protection is always dependent on how memory is actually
  5875. * consumed among the siblings anyway.
  5876. */
  5877. ep = protected;
  5878. /*
  5879. * If the children aren't claiming (all of) the protection
  5880. * afforded to them by the parent, distribute the remainder in
  5881. * proportion to the (unprotected) memory of each cgroup. That
  5882. * way, cgroups that aren't explicitly prioritized wrt each
  5883. * other compete freely over the allowance, but they are
  5884. * collectively protected from neighboring trees.
  5885. *
  5886. * We're using unprotected memory for the weight so that if
  5887. * some cgroups DO claim explicit protection, we don't protect
  5888. * the same bytes twice.
  5889. *
  5890. * Check both usage and parent_usage against the respective
  5891. * protected values. One should imply the other, but they
  5892. * aren't read atomically - make sure the division is sane.
  5893. */
  5894. if (!(cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_RECURSIVE_PROT))
  5895. return ep;
  5896. if (parent_effective > siblings_protected &&
  5897. parent_usage > siblings_protected &&
  5898. usage > protected) {
  5899. unsigned long unclaimed;
  5900. unclaimed = parent_effective - siblings_protected;
  5901. unclaimed *= usage - protected;
  5902. unclaimed /= parent_usage - siblings_protected;
  5903. ep += unclaimed;
  5904. }
  5905. return ep;
  5906. }
  5907. /**
  5908. * mem_cgroup_calculate_protection - check if memory consumption is in the normal range
  5909. * @root: the top ancestor of the sub-tree being checked
  5910. * @memcg: the memory cgroup to check
  5911. *
  5912. * WARNING: This function is not stateless! It can only be used as part
  5913. * of a top-down tree iteration, not for isolated queries.
  5914. */
  5915. void mem_cgroup_calculate_protection(struct mem_cgroup *root,
  5916. struct mem_cgroup *memcg)
  5917. {
  5918. unsigned long usage, parent_usage;
  5919. struct mem_cgroup *parent;
  5920. if (mem_cgroup_disabled())
  5921. return;
  5922. if (!root)
  5923. root = root_mem_cgroup;
  5924. /*
  5925. * Effective values of the reclaim targets are ignored so they
  5926. * can be stale. Have a look at mem_cgroup_protection for more
  5927. * details.
  5928. * TODO: calculation should be more robust so that we do not need
  5929. * that special casing.
  5930. */
  5931. if (memcg == root)
  5932. return;
  5933. usage = page_counter_read(&memcg->memory);
  5934. if (!usage)
  5935. return;
  5936. parent = parent_mem_cgroup(memcg);
  5937. if (parent == root) {
  5938. memcg->memory.emin = READ_ONCE(memcg->memory.min);
  5939. memcg->memory.elow = READ_ONCE(memcg->memory.low);
  5940. return;
  5941. }
  5942. parent_usage = page_counter_read(&parent->memory);
  5943. WRITE_ONCE(memcg->memory.emin, effective_protection(usage, parent_usage,
  5944. READ_ONCE(memcg->memory.min),
  5945. READ_ONCE(parent->memory.emin),
  5946. atomic_long_read(&parent->memory.children_min_usage)));
  5947. WRITE_ONCE(memcg->memory.elow, effective_protection(usage, parent_usage,
  5948. READ_ONCE(memcg->memory.low),
  5949. READ_ONCE(parent->memory.elow),
  5950. atomic_long_read(&parent->memory.children_low_usage)));
  5951. }
  5952. static int charge_memcg(struct folio *folio, struct mem_cgroup *memcg,
  5953. gfp_t gfp)
  5954. {
  5955. long nr_pages = folio_nr_pages(folio);
  5956. int ret;
  5957. ret = try_charge(memcg, gfp, nr_pages);
  5958. if (ret)
  5959. goto out;
  5960. css_get(&memcg->css);
  5961. commit_charge(folio, memcg);
  5962. local_irq_disable();
  5963. mem_cgroup_charge_statistics(memcg, nr_pages);
  5964. memcg_check_events(memcg, folio_nid(folio));
  5965. local_irq_enable();
  5966. out:
  5967. return ret;
  5968. }
  5969. int __mem_cgroup_charge(struct folio *folio, struct mm_struct *mm, gfp_t gfp)
  5970. {
  5971. struct mem_cgroup *memcg;
  5972. int ret;
  5973. memcg = get_mem_cgroup_from_mm(mm);
  5974. ret = charge_memcg(folio, memcg, gfp);
  5975. css_put(&memcg->css);
  5976. return ret;
  5977. }
  5978. /**
  5979. * mem_cgroup_swapin_charge_folio - Charge a newly allocated folio for swapin.
  5980. * @folio: folio to charge.
  5981. * @mm: mm context of the victim
  5982. * @gfp: reclaim mode
  5983. * @entry: swap entry for which the folio is allocated
  5984. *
  5985. * This function charges a folio allocated for swapin. Please call this before
  5986. * adding the folio to the swapcache.
  5987. *
  5988. * Returns 0 on success. Otherwise, an error code is returned.
  5989. */
  5990. int mem_cgroup_swapin_charge_folio(struct folio *folio, struct mm_struct *mm,
  5991. gfp_t gfp, swp_entry_t entry)
  5992. {
  5993. struct mem_cgroup *memcg;
  5994. unsigned short id;
  5995. int ret;
  5996. if (mem_cgroup_disabled())
  5997. return 0;
  5998. id = lookup_swap_cgroup_id(entry);
  5999. rcu_read_lock();
  6000. memcg = mem_cgroup_from_id(id);
  6001. if (!memcg || !css_tryget_online(&memcg->css))
  6002. memcg = get_mem_cgroup_from_mm(mm);
  6003. rcu_read_unlock();
  6004. ret = charge_memcg(folio, memcg, gfp);
  6005. css_put(&memcg->css);
  6006. return ret;
  6007. }
  6008. /*
  6009. * mem_cgroup_swapin_uncharge_swap - uncharge swap slot
  6010. * @entry: swap entry for which the page is charged
  6011. *
  6012. * Call this function after successfully adding the charged page to swapcache.
  6013. *
  6014. * Note: This function assumes the page for which swap slot is being uncharged
  6015. * is order 0 page.
  6016. */
  6017. void mem_cgroup_swapin_uncharge_swap(swp_entry_t entry)
  6018. {
  6019. /*
  6020. * Cgroup1's unified memory+swap counter has been charged with the
  6021. * new swapcache page, finish the transfer by uncharging the swap
  6022. * slot. The swap slot would also get uncharged when it dies, but
  6023. * it can stick around indefinitely and we'd count the page twice
  6024. * the entire time.
  6025. *
  6026. * Cgroup2 has separate resource counters for memory and swap,
  6027. * so this is a non-issue here. Memory and swap charge lifetimes
  6028. * correspond 1:1 to page and swap slot lifetimes: we charge the
  6029. * page to memory here, and uncharge swap when the slot is freed.
  6030. */
  6031. if (!mem_cgroup_disabled() && do_memsw_account()) {
  6032. /*
  6033. * The swap entry might not get freed for a long time,
  6034. * let's not wait for it. The page already received a
  6035. * memory+swap charge, drop the swap entry duplicate.
  6036. */
  6037. mem_cgroup_uncharge_swap(entry, 1);
  6038. }
  6039. }
  6040. struct uncharge_gather {
  6041. struct mem_cgroup *memcg;
  6042. unsigned long nr_memory;
  6043. unsigned long pgpgout;
  6044. unsigned long nr_kmem;
  6045. int nid;
  6046. };
  6047. static inline void uncharge_gather_clear(struct uncharge_gather *ug)
  6048. {
  6049. memset(ug, 0, sizeof(*ug));
  6050. }
  6051. static void uncharge_batch(const struct uncharge_gather *ug)
  6052. {
  6053. unsigned long flags;
  6054. if (ug->nr_memory) {
  6055. page_counter_uncharge(&ug->memcg->memory, ug->nr_memory);
  6056. if (do_memsw_account())
  6057. page_counter_uncharge(&ug->memcg->memsw, ug->nr_memory);
  6058. if (ug->nr_kmem)
  6059. memcg_account_kmem(ug->memcg, -ug->nr_kmem);
  6060. memcg_oom_recover(ug->memcg);
  6061. }
  6062. local_irq_save(flags);
  6063. __count_memcg_events(ug->memcg, PGPGOUT, ug->pgpgout);
  6064. __this_cpu_add(ug->memcg->vmstats_percpu->nr_page_events, ug->nr_memory);
  6065. memcg_check_events(ug->memcg, ug->nid);
  6066. local_irq_restore(flags);
  6067. /* drop reference from uncharge_folio */
  6068. css_put(&ug->memcg->css);
  6069. }
  6070. static void uncharge_folio(struct folio *folio, struct uncharge_gather *ug)
  6071. {
  6072. long nr_pages;
  6073. struct mem_cgroup *memcg;
  6074. struct obj_cgroup *objcg;
  6075. VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
  6076. /*
  6077. * Nobody should be changing or seriously looking at
  6078. * folio memcg or objcg at this point, we have fully
  6079. * exclusive access to the folio.
  6080. */
  6081. if (folio_memcg_kmem(folio)) {
  6082. objcg = __folio_objcg(folio);
  6083. /*
  6084. * This get matches the put at the end of the function and
  6085. * kmem pages do not hold memcg references anymore.
  6086. */
  6087. memcg = get_mem_cgroup_from_objcg(objcg);
  6088. } else {
  6089. memcg = __folio_memcg(folio);
  6090. }
  6091. if (!memcg)
  6092. return;
  6093. if (ug->memcg != memcg) {
  6094. if (ug->memcg) {
  6095. uncharge_batch(ug);
  6096. uncharge_gather_clear(ug);
  6097. }
  6098. ug->memcg = memcg;
  6099. ug->nid = folio_nid(folio);
  6100. /* pairs with css_put in uncharge_batch */
  6101. css_get(&memcg->css);
  6102. }
  6103. nr_pages = folio_nr_pages(folio);
  6104. if (folio_memcg_kmem(folio)) {
  6105. ug->nr_memory += nr_pages;
  6106. ug->nr_kmem += nr_pages;
  6107. folio->memcg_data = 0;
  6108. obj_cgroup_put(objcg);
  6109. } else {
  6110. /* LRU pages aren't accounted at the root level */
  6111. if (!mem_cgroup_is_root(memcg))
  6112. ug->nr_memory += nr_pages;
  6113. ug->pgpgout++;
  6114. folio->memcg_data = 0;
  6115. }
  6116. css_put(&memcg->css);
  6117. }
  6118. void __mem_cgroup_uncharge(struct folio *folio)
  6119. {
  6120. struct uncharge_gather ug;
  6121. /* Don't touch folio->lru of any random page, pre-check: */
  6122. if (!folio_memcg(folio))
  6123. return;
  6124. uncharge_gather_clear(&ug);
  6125. uncharge_folio(folio, &ug);
  6126. uncharge_batch(&ug);
  6127. }
  6128. /**
  6129. * __mem_cgroup_uncharge_list - uncharge a list of page
  6130. * @page_list: list of pages to uncharge
  6131. *
  6132. * Uncharge a list of pages previously charged with
  6133. * __mem_cgroup_charge().
  6134. */
  6135. void __mem_cgroup_uncharge_list(struct list_head *page_list)
  6136. {
  6137. struct uncharge_gather ug;
  6138. struct folio *folio;
  6139. uncharge_gather_clear(&ug);
  6140. list_for_each_entry(folio, page_list, lru)
  6141. uncharge_folio(folio, &ug);
  6142. if (ug.memcg)
  6143. uncharge_batch(&ug);
  6144. }
  6145. /**
  6146. * mem_cgroup_migrate - Charge a folio's replacement.
  6147. * @old: Currently circulating folio.
  6148. * @new: Replacement folio.
  6149. *
  6150. * Charge @new as a replacement folio for @old. @old will
  6151. * be uncharged upon free.
  6152. *
  6153. * Both folios must be locked, @new->mapping must be set up.
  6154. */
  6155. void mem_cgroup_migrate(struct folio *old, struct folio *new)
  6156. {
  6157. struct mem_cgroup *memcg;
  6158. long nr_pages = folio_nr_pages(new);
  6159. unsigned long flags;
  6160. VM_BUG_ON_FOLIO(!folio_test_locked(old), old);
  6161. VM_BUG_ON_FOLIO(!folio_test_locked(new), new);
  6162. VM_BUG_ON_FOLIO(folio_test_anon(old) != folio_test_anon(new), new);
  6163. VM_BUG_ON_FOLIO(folio_nr_pages(old) != nr_pages, new);
  6164. if (mem_cgroup_disabled())
  6165. return;
  6166. /* Page cache replacement: new folio already charged? */
  6167. if (folio_memcg(new))
  6168. return;
  6169. memcg = folio_memcg(old);
  6170. VM_WARN_ON_ONCE_FOLIO(!memcg, old);
  6171. if (!memcg)
  6172. return;
  6173. /* Force-charge the new page. The old one will be freed soon */
  6174. if (!mem_cgroup_is_root(memcg)) {
  6175. page_counter_charge(&memcg->memory, nr_pages);
  6176. if (do_memsw_account())
  6177. page_counter_charge(&memcg->memsw, nr_pages);
  6178. }
  6179. css_get(&memcg->css);
  6180. commit_charge(new, memcg);
  6181. local_irq_save(flags);
  6182. mem_cgroup_charge_statistics(memcg, nr_pages);
  6183. memcg_check_events(memcg, folio_nid(new));
  6184. local_irq_restore(flags);
  6185. }
  6186. DEFINE_STATIC_KEY_FALSE(memcg_sockets_enabled_key);
  6187. EXPORT_SYMBOL(memcg_sockets_enabled_key);
  6188. void mem_cgroup_sk_alloc(struct sock *sk)
  6189. {
  6190. struct mem_cgroup *memcg;
  6191. if (!mem_cgroup_sockets_enabled)
  6192. return;
  6193. /* Do not associate the sock with unrelated interrupted task's memcg. */
  6194. if (!in_task())
  6195. return;
  6196. rcu_read_lock();
  6197. memcg = mem_cgroup_from_task(current);
  6198. if (memcg == root_mem_cgroup)
  6199. goto out;
  6200. if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && !memcg->tcpmem_active)
  6201. goto out;
  6202. if (css_tryget(&memcg->css))
  6203. sk->sk_memcg = memcg;
  6204. out:
  6205. rcu_read_unlock();
  6206. }
  6207. void mem_cgroup_sk_free(struct sock *sk)
  6208. {
  6209. if (sk->sk_memcg)
  6210. css_put(&sk->sk_memcg->css);
  6211. }
  6212. /**
  6213. * mem_cgroup_charge_skmem - charge socket memory
  6214. * @memcg: memcg to charge
  6215. * @nr_pages: number of pages to charge
  6216. * @gfp_mask: reclaim mode
  6217. *
  6218. * Charges @nr_pages to @memcg. Returns %true if the charge fit within
  6219. * @memcg's configured limit, %false if it doesn't.
  6220. */
  6221. bool mem_cgroup_charge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages,
  6222. gfp_t gfp_mask)
  6223. {
  6224. if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
  6225. struct page_counter *fail;
  6226. if (page_counter_try_charge(&memcg->tcpmem, nr_pages, &fail)) {
  6227. memcg->tcpmem_pressure = 0;
  6228. return true;
  6229. }
  6230. memcg->tcpmem_pressure = 1;
  6231. if (gfp_mask & __GFP_NOFAIL) {
  6232. page_counter_charge(&memcg->tcpmem, nr_pages);
  6233. return true;
  6234. }
  6235. return false;
  6236. }
  6237. if (try_charge(memcg, gfp_mask, nr_pages) == 0) {
  6238. mod_memcg_state(memcg, MEMCG_SOCK, nr_pages);
  6239. return true;
  6240. }
  6241. return false;
  6242. }
  6243. /**
  6244. * mem_cgroup_uncharge_skmem - uncharge socket memory
  6245. * @memcg: memcg to uncharge
  6246. * @nr_pages: number of pages to uncharge
  6247. */
  6248. void mem_cgroup_uncharge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages)
  6249. {
  6250. if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
  6251. page_counter_uncharge(&memcg->tcpmem, nr_pages);
  6252. return;
  6253. }
  6254. mod_memcg_state(memcg, MEMCG_SOCK, -nr_pages);
  6255. refill_stock(memcg, nr_pages);
  6256. }
  6257. static int __init cgroup_memory(char *s)
  6258. {
  6259. char *token;
  6260. while ((token = strsep(&s, ",")) != NULL) {
  6261. if (!*token)
  6262. continue;
  6263. if (!strcmp(token, "nosocket"))
  6264. cgroup_memory_nosocket = true;
  6265. if (!strcmp(token, "nokmem"))
  6266. cgroup_memory_nokmem = true;
  6267. }
  6268. return 1;
  6269. }
  6270. __setup("cgroup.memory=", cgroup_memory);
  6271. /*
  6272. * subsys_initcall() for memory controller.
  6273. *
  6274. * Some parts like memcg_hotplug_cpu_dead() have to be initialized from this
  6275. * context because of lock dependencies (cgroup_lock -> cpu hotplug) but
  6276. * basically everything that doesn't depend on a specific mem_cgroup structure
  6277. * should be initialized from here.
  6278. */
  6279. static int __init mem_cgroup_init(void)
  6280. {
  6281. int cpu, node;
  6282. /*
  6283. * Currently s32 type (can refer to struct batched_lruvec_stat) is
  6284. * used for per-memcg-per-cpu caching of per-node statistics. In order
  6285. * to work fine, we should make sure that the overfill threshold can't
  6286. * exceed S32_MAX / PAGE_SIZE.
  6287. */
  6288. BUILD_BUG_ON(MEMCG_CHARGE_BATCH > S32_MAX / PAGE_SIZE);
  6289. cpuhp_setup_state_nocalls(CPUHP_MM_MEMCQ_DEAD, "mm/memctrl:dead", NULL,
  6290. memcg_hotplug_cpu_dead);
  6291. for_each_possible_cpu(cpu)
  6292. INIT_WORK(&per_cpu_ptr(&memcg_stock, cpu)->work,
  6293. drain_local_stock);
  6294. for_each_node(node) {
  6295. struct mem_cgroup_tree_per_node *rtpn;
  6296. rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL,
  6297. node_online(node) ? node : NUMA_NO_NODE);
  6298. rtpn->rb_root = RB_ROOT;
  6299. rtpn->rb_rightmost = NULL;
  6300. spin_lock_init(&rtpn->lock);
  6301. soft_limit_tree.rb_tree_per_node[node] = rtpn;
  6302. }
  6303. return 0;
  6304. }
  6305. subsys_initcall(mem_cgroup_init);
  6306. #ifdef CONFIG_SWAP
  6307. static struct mem_cgroup *mem_cgroup_id_get_online(struct mem_cgroup *memcg)
  6308. {
  6309. while (!refcount_inc_not_zero(&memcg->id.ref)) {
  6310. /*
  6311. * The root cgroup cannot be destroyed, so it's refcount must
  6312. * always be >= 1.
  6313. */
  6314. if (WARN_ON_ONCE(memcg == root_mem_cgroup)) {
  6315. VM_BUG_ON(1);
  6316. break;
  6317. }
  6318. memcg = parent_mem_cgroup(memcg);
  6319. if (!memcg)
  6320. memcg = root_mem_cgroup;
  6321. }
  6322. return memcg;
  6323. }
  6324. /**
  6325. * mem_cgroup_swapout - transfer a memsw charge to swap
  6326. * @folio: folio whose memsw charge to transfer
  6327. * @entry: swap entry to move the charge to
  6328. *
  6329. * Transfer the memsw charge of @folio to @entry.
  6330. */
  6331. void mem_cgroup_swapout(struct folio *folio, swp_entry_t entry)
  6332. {
  6333. struct mem_cgroup *memcg, *swap_memcg;
  6334. unsigned int nr_entries;
  6335. unsigned short oldid;
  6336. VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
  6337. VM_BUG_ON_FOLIO(folio_ref_count(folio), folio);
  6338. if (mem_cgroup_disabled())
  6339. return;
  6340. if (!do_memsw_account())
  6341. return;
  6342. memcg = folio_memcg(folio);
  6343. VM_WARN_ON_ONCE_FOLIO(!memcg, folio);
  6344. if (!memcg)
  6345. return;
  6346. /*
  6347. * In case the memcg owning these pages has been offlined and doesn't
  6348. * have an ID allocated to it anymore, charge the closest online
  6349. * ancestor for the swap instead and transfer the memory+swap charge.
  6350. */
  6351. swap_memcg = mem_cgroup_id_get_online(memcg);
  6352. nr_entries = folio_nr_pages(folio);
  6353. /* Get references for the tail pages, too */
  6354. if (nr_entries > 1)
  6355. mem_cgroup_id_get_many(swap_memcg, nr_entries - 1);
  6356. oldid = swap_cgroup_record(entry, mem_cgroup_id(swap_memcg),
  6357. nr_entries);
  6358. VM_BUG_ON_FOLIO(oldid, folio);
  6359. mod_memcg_state(swap_memcg, MEMCG_SWAP, nr_entries);
  6360. folio->memcg_data = 0;
  6361. if (!mem_cgroup_is_root(memcg))
  6362. page_counter_uncharge(&memcg->memory, nr_entries);
  6363. if (memcg != swap_memcg) {
  6364. if (!mem_cgroup_is_root(swap_memcg))
  6365. page_counter_charge(&swap_memcg->memsw, nr_entries);
  6366. page_counter_uncharge(&memcg->memsw, nr_entries);
  6367. }
  6368. /*
  6369. * Interrupts should be disabled here because the caller holds the
  6370. * i_pages lock which is taken with interrupts-off. It is
  6371. * important here to have the interrupts disabled because it is the
  6372. * only synchronisation we have for updating the per-CPU variables.
  6373. */
  6374. memcg_stats_lock();
  6375. mem_cgroup_charge_statistics(memcg, -nr_entries);
  6376. memcg_stats_unlock();
  6377. memcg_check_events(memcg, folio_nid(folio));
  6378. css_put(&memcg->css);
  6379. }
  6380. /**
  6381. * __mem_cgroup_try_charge_swap - try charging swap space for a folio
  6382. * @folio: folio being added to swap
  6383. * @entry: swap entry to charge
  6384. *
  6385. * Try to charge @folio's memcg for the swap space at @entry.
  6386. *
  6387. * Returns 0 on success, -ENOMEM on failure.
  6388. */
  6389. int __mem_cgroup_try_charge_swap(struct folio *folio, swp_entry_t entry)
  6390. {
  6391. unsigned int nr_pages = folio_nr_pages(folio);
  6392. struct page_counter *counter;
  6393. struct mem_cgroup *memcg;
  6394. unsigned short oldid;
  6395. if (do_memsw_account())
  6396. return 0;
  6397. memcg = folio_memcg(folio);
  6398. VM_WARN_ON_ONCE_FOLIO(!memcg, folio);
  6399. if (!memcg)
  6400. return 0;
  6401. if (!entry.val) {
  6402. memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
  6403. return 0;
  6404. }
  6405. memcg = mem_cgroup_id_get_online(memcg);
  6406. if (!mem_cgroup_is_root(memcg) &&
  6407. !page_counter_try_charge(&memcg->swap, nr_pages, &counter)) {
  6408. memcg_memory_event(memcg, MEMCG_SWAP_MAX);
  6409. memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
  6410. mem_cgroup_id_put(memcg);
  6411. return -ENOMEM;
  6412. }
  6413. /* Get references for the tail pages, too */
  6414. if (nr_pages > 1)
  6415. mem_cgroup_id_get_many(memcg, nr_pages - 1);
  6416. oldid = swap_cgroup_record(entry, mem_cgroup_id(memcg), nr_pages);
  6417. VM_BUG_ON_FOLIO(oldid, folio);
  6418. mod_memcg_state(memcg, MEMCG_SWAP, nr_pages);
  6419. return 0;
  6420. }
  6421. /**
  6422. * __mem_cgroup_uncharge_swap - uncharge swap space
  6423. * @entry: swap entry to uncharge
  6424. * @nr_pages: the amount of swap space to uncharge
  6425. */
  6426. void __mem_cgroup_uncharge_swap(swp_entry_t entry, unsigned int nr_pages)
  6427. {
  6428. struct mem_cgroup *memcg;
  6429. unsigned short id;
  6430. if (mem_cgroup_disabled())
  6431. return;
  6432. id = swap_cgroup_record(entry, 0, nr_pages);
  6433. rcu_read_lock();
  6434. memcg = mem_cgroup_from_id(id);
  6435. if (memcg) {
  6436. if (!mem_cgroup_is_root(memcg)) {
  6437. if (do_memsw_account())
  6438. page_counter_uncharge(&memcg->memsw, nr_pages);
  6439. else
  6440. page_counter_uncharge(&memcg->swap, nr_pages);
  6441. }
  6442. mod_memcg_state(memcg, MEMCG_SWAP, -nr_pages);
  6443. mem_cgroup_id_put_many(memcg, nr_pages);
  6444. }
  6445. rcu_read_unlock();
  6446. }
  6447. long mem_cgroup_get_nr_swap_pages(struct mem_cgroup *memcg)
  6448. {
  6449. long nr_swap_pages = get_nr_swap_pages();
  6450. if (mem_cgroup_disabled() || do_memsw_account())
  6451. return nr_swap_pages;
  6452. for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg))
  6453. nr_swap_pages = min_t(long, nr_swap_pages,
  6454. READ_ONCE(memcg->swap.max) -
  6455. page_counter_read(&memcg->swap));
  6456. return nr_swap_pages;
  6457. }
  6458. bool mem_cgroup_swap_full(struct folio *folio)
  6459. {
  6460. struct mem_cgroup *memcg;
  6461. VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
  6462. if (vm_swap_full())
  6463. return true;
  6464. if (do_memsw_account())
  6465. return false;
  6466. memcg = folio_memcg(folio);
  6467. if (!memcg)
  6468. return false;
  6469. for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg)) {
  6470. unsigned long usage = page_counter_read(&memcg->swap);
  6471. if (usage * 2 >= READ_ONCE(memcg->swap.high) ||
  6472. usage * 2 >= READ_ONCE(memcg->swap.max))
  6473. return true;
  6474. }
  6475. return false;
  6476. }
  6477. static int __init setup_swap_account(char *s)
  6478. {
  6479. pr_warn_once("The swapaccount= commandline option is deprecated. "
  6480. "Please report your usecase to [email protected] if you "
  6481. "depend on this functionality.\n");
  6482. return 1;
  6483. }
  6484. __setup("swapaccount=", setup_swap_account);
  6485. static u64 swap_current_read(struct cgroup_subsys_state *css,
  6486. struct cftype *cft)
  6487. {
  6488. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  6489. return (u64)page_counter_read(&memcg->swap) * PAGE_SIZE;
  6490. }
  6491. static int swap_high_show(struct seq_file *m, void *v)
  6492. {
  6493. return seq_puts_memcg_tunable(m,
  6494. READ_ONCE(mem_cgroup_from_seq(m)->swap.high));
  6495. }
  6496. static ssize_t swap_high_write(struct kernfs_open_file *of,
  6497. char *buf, size_t nbytes, loff_t off)
  6498. {
  6499. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  6500. unsigned long high;
  6501. int err;
  6502. buf = strstrip(buf);
  6503. err = page_counter_memparse(buf, "max", &high);
  6504. if (err)
  6505. return err;
  6506. page_counter_set_high(&memcg->swap, high);
  6507. return nbytes;
  6508. }
  6509. static int swap_max_show(struct seq_file *m, void *v)
  6510. {
  6511. return seq_puts_memcg_tunable(m,
  6512. READ_ONCE(mem_cgroup_from_seq(m)->swap.max));
  6513. }
  6514. static ssize_t swap_max_write(struct kernfs_open_file *of,
  6515. char *buf, size_t nbytes, loff_t off)
  6516. {
  6517. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  6518. unsigned long max;
  6519. int err;
  6520. buf = strstrip(buf);
  6521. err = page_counter_memparse(buf, "max", &max);
  6522. if (err)
  6523. return err;
  6524. xchg(&memcg->swap.max, max);
  6525. return nbytes;
  6526. }
  6527. static int swap_events_show(struct seq_file *m, void *v)
  6528. {
  6529. struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
  6530. seq_printf(m, "high %lu\n",
  6531. atomic_long_read(&memcg->memory_events[MEMCG_SWAP_HIGH]));
  6532. seq_printf(m, "max %lu\n",
  6533. atomic_long_read(&memcg->memory_events[MEMCG_SWAP_MAX]));
  6534. seq_printf(m, "fail %lu\n",
  6535. atomic_long_read(&memcg->memory_events[MEMCG_SWAP_FAIL]));
  6536. return 0;
  6537. }
  6538. static struct cftype swap_files[] = {
  6539. {
  6540. .name = "swap.current",
  6541. .flags = CFTYPE_NOT_ON_ROOT,
  6542. .read_u64 = swap_current_read,
  6543. },
  6544. {
  6545. .name = "swap.high",
  6546. .flags = CFTYPE_NOT_ON_ROOT,
  6547. .seq_show = swap_high_show,
  6548. .write = swap_high_write,
  6549. },
  6550. {
  6551. .name = "swap.max",
  6552. .flags = CFTYPE_NOT_ON_ROOT,
  6553. .seq_show = swap_max_show,
  6554. .write = swap_max_write,
  6555. },
  6556. {
  6557. .name = "swap.events",
  6558. .flags = CFTYPE_NOT_ON_ROOT,
  6559. .file_offset = offsetof(struct mem_cgroup, swap_events_file),
  6560. .seq_show = swap_events_show,
  6561. },
  6562. { } /* terminate */
  6563. };
  6564. static struct cftype memsw_files[] = {
  6565. {
  6566. .name = "memsw.usage_in_bytes",
  6567. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
  6568. .read_u64 = mem_cgroup_read_u64,
  6569. },
  6570. {
  6571. .name = "memsw.max_usage_in_bytes",
  6572. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
  6573. .write = mem_cgroup_reset,
  6574. .read_u64 = mem_cgroup_read_u64,
  6575. },
  6576. {
  6577. .name = "memsw.limit_in_bytes",
  6578. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
  6579. .write = mem_cgroup_write,
  6580. .read_u64 = mem_cgroup_read_u64,
  6581. },
  6582. {
  6583. .name = "memsw.failcnt",
  6584. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
  6585. .write = mem_cgroup_reset,
  6586. .read_u64 = mem_cgroup_read_u64,
  6587. },
  6588. { }, /* terminate */
  6589. };
  6590. #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
  6591. /**
  6592. * obj_cgroup_may_zswap - check if this cgroup can zswap
  6593. * @objcg: the object cgroup
  6594. *
  6595. * Check if the hierarchical zswap limit has been reached.
  6596. *
  6597. * This doesn't check for specific headroom, and it is not atomic
  6598. * either. But with zswap, the size of the allocation is only known
  6599. * once compression has occured, and this optimistic pre-check avoids
  6600. * spending cycles on compression when there is already no room left
  6601. * or zswap is disabled altogether somewhere in the hierarchy.
  6602. */
  6603. bool obj_cgroup_may_zswap(struct obj_cgroup *objcg)
  6604. {
  6605. struct mem_cgroup *memcg, *original_memcg;
  6606. bool ret = true;
  6607. if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
  6608. return true;
  6609. original_memcg = get_mem_cgroup_from_objcg(objcg);
  6610. for (memcg = original_memcg; memcg != root_mem_cgroup;
  6611. memcg = parent_mem_cgroup(memcg)) {
  6612. unsigned long max = READ_ONCE(memcg->zswap_max);
  6613. unsigned long pages;
  6614. if (max == PAGE_COUNTER_MAX)
  6615. continue;
  6616. if (max == 0) {
  6617. ret = false;
  6618. break;
  6619. }
  6620. cgroup_rstat_flush(memcg->css.cgroup);
  6621. pages = memcg_page_state(memcg, MEMCG_ZSWAP_B) / PAGE_SIZE;
  6622. if (pages < max)
  6623. continue;
  6624. ret = false;
  6625. break;
  6626. }
  6627. mem_cgroup_put(original_memcg);
  6628. return ret;
  6629. }
  6630. /**
  6631. * obj_cgroup_charge_zswap - charge compression backend memory
  6632. * @objcg: the object cgroup
  6633. * @size: size of compressed object
  6634. *
  6635. * This forces the charge after obj_cgroup_may_swap() allowed
  6636. * compression and storage in zwap for this cgroup to go ahead.
  6637. */
  6638. void obj_cgroup_charge_zswap(struct obj_cgroup *objcg, size_t size)
  6639. {
  6640. struct mem_cgroup *memcg;
  6641. if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
  6642. return;
  6643. VM_WARN_ON_ONCE(!(current->flags & PF_MEMALLOC));
  6644. /* PF_MEMALLOC context, charging must succeed */
  6645. if (obj_cgroup_charge(objcg, GFP_KERNEL, size))
  6646. VM_WARN_ON_ONCE(1);
  6647. rcu_read_lock();
  6648. memcg = obj_cgroup_memcg(objcg);
  6649. mod_memcg_state(memcg, MEMCG_ZSWAP_B, size);
  6650. mod_memcg_state(memcg, MEMCG_ZSWAPPED, 1);
  6651. rcu_read_unlock();
  6652. }
  6653. /**
  6654. * obj_cgroup_uncharge_zswap - uncharge compression backend memory
  6655. * @objcg: the object cgroup
  6656. * @size: size of compressed object
  6657. *
  6658. * Uncharges zswap memory on page in.
  6659. */
  6660. void obj_cgroup_uncharge_zswap(struct obj_cgroup *objcg, size_t size)
  6661. {
  6662. struct mem_cgroup *memcg;
  6663. if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
  6664. return;
  6665. obj_cgroup_uncharge(objcg, size);
  6666. rcu_read_lock();
  6667. memcg = obj_cgroup_memcg(objcg);
  6668. mod_memcg_state(memcg, MEMCG_ZSWAP_B, -size);
  6669. mod_memcg_state(memcg, MEMCG_ZSWAPPED, -1);
  6670. rcu_read_unlock();
  6671. }
  6672. static u64 zswap_current_read(struct cgroup_subsys_state *css,
  6673. struct cftype *cft)
  6674. {
  6675. cgroup_rstat_flush(css->cgroup);
  6676. return memcg_page_state(mem_cgroup_from_css(css), MEMCG_ZSWAP_B);
  6677. }
  6678. static int zswap_max_show(struct seq_file *m, void *v)
  6679. {
  6680. return seq_puts_memcg_tunable(m,
  6681. READ_ONCE(mem_cgroup_from_seq(m)->zswap_max));
  6682. }
  6683. static ssize_t zswap_max_write(struct kernfs_open_file *of,
  6684. char *buf, size_t nbytes, loff_t off)
  6685. {
  6686. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  6687. unsigned long max;
  6688. int err;
  6689. buf = strstrip(buf);
  6690. err = page_counter_memparse(buf, "max", &max);
  6691. if (err)
  6692. return err;
  6693. xchg(&memcg->zswap_max, max);
  6694. return nbytes;
  6695. }
  6696. static struct cftype zswap_files[] = {
  6697. {
  6698. .name = "zswap.current",
  6699. .flags = CFTYPE_NOT_ON_ROOT,
  6700. .read_u64 = zswap_current_read,
  6701. },
  6702. {
  6703. .name = "zswap.max",
  6704. .flags = CFTYPE_NOT_ON_ROOT,
  6705. .seq_show = zswap_max_show,
  6706. .write = zswap_max_write,
  6707. },
  6708. { } /* terminate */
  6709. };
  6710. #endif /* CONFIG_MEMCG_KMEM && CONFIG_ZSWAP */
  6711. static int __init mem_cgroup_swap_init(void)
  6712. {
  6713. if (mem_cgroup_disabled())
  6714. return 0;
  6715. WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, swap_files));
  6716. WARN_ON(cgroup_add_legacy_cftypes(&memory_cgrp_subsys, memsw_files));
  6717. #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP)
  6718. WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, zswap_files));
  6719. #endif
  6720. return 0;
  6721. }
  6722. subsys_initcall(mem_cgroup_swap_init);
  6723. #endif /* CONFIG_SWAP */