memcontrol.c 159 KB

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