memcontrol.c 188 KB

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