memcontrol.c 179 KB

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