memcontrol.c 155 KB

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