memcontrol.c 177 KB

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