memcontrol.c 181 KB

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