memcontrol.c 180 KB

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