memcontrol.c 187 KB

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