memcontrol.c 193 KB

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