memcontrol.c 161 KB

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