memcontrol.c 182 KB

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