memcontrol.c 186 KB

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