memcontrol.c 149 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900
  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/page_counter.h>
  28. #include <linux/memcontrol.h>
  29. #include <linux/cgroup.h>
  30. #include <linux/mm.h>
  31. #include <linux/hugetlb.h>
  32. #include <linux/pagemap.h>
  33. #include <linux/smp.h>
  34. #include <linux/page-flags.h>
  35. #include <linux/backing-dev.h>
  36. #include <linux/bit_spinlock.h>
  37. #include <linux/rcupdate.h>
  38. #include <linux/limits.h>
  39. #include <linux/export.h>
  40. #include <linux/mutex.h>
  41. #include <linux/rbtree.h>
  42. #include <linux/slab.h>
  43. #include <linux/swap.h>
  44. #include <linux/swapops.h>
  45. #include <linux/spinlock.h>
  46. #include <linux/eventfd.h>
  47. #include <linux/poll.h>
  48. #include <linux/sort.h>
  49. #include <linux/fs.h>
  50. #include <linux/seq_file.h>
  51. #include <linux/vmpressure.h>
  52. #include <linux/mm_inline.h>
  53. #include <linux/swap_cgroup.h>
  54. #include <linux/cpu.h>
  55. #include <linux/oom.h>
  56. #include <linux/lockdep.h>
  57. #include <linux/file.h>
  58. #include "internal.h"
  59. #include <net/sock.h>
  60. #include <net/ip.h>
  61. #include <net/tcp_memcontrol.h>
  62. #include "slab.h"
  63. #include <asm/uaccess.h>
  64. #include <trace/events/vmscan.h>
  65. struct cgroup_subsys memory_cgrp_subsys __read_mostly;
  66. EXPORT_SYMBOL(memory_cgrp_subsys);
  67. #define MEM_CGROUP_RECLAIM_RETRIES 5
  68. static struct mem_cgroup *root_mem_cgroup __read_mostly;
  69. /* Whether the swap controller is active */
  70. #ifdef CONFIG_MEMCG_SWAP
  71. int do_swap_account __read_mostly;
  72. #else
  73. #define do_swap_account 0
  74. #endif
  75. static const char * const mem_cgroup_stat_names[] = {
  76. "cache",
  77. "rss",
  78. "rss_huge",
  79. "mapped_file",
  80. "writeback",
  81. "swap",
  82. };
  83. static const char * const mem_cgroup_events_names[] = {
  84. "pgpgin",
  85. "pgpgout",
  86. "pgfault",
  87. "pgmajfault",
  88. };
  89. static const char * const mem_cgroup_lru_names[] = {
  90. "inactive_anon",
  91. "active_anon",
  92. "inactive_file",
  93. "active_file",
  94. "unevictable",
  95. };
  96. /*
  97. * Per memcg event counter is incremented at every pagein/pageout. With THP,
  98. * it will be incremated by the number of pages. This counter is used for
  99. * for trigger some periodic events. This is straightforward and better
  100. * than using jiffies etc. to handle periodic memcg event.
  101. */
  102. enum mem_cgroup_events_target {
  103. MEM_CGROUP_TARGET_THRESH,
  104. MEM_CGROUP_TARGET_SOFTLIMIT,
  105. MEM_CGROUP_TARGET_NUMAINFO,
  106. MEM_CGROUP_NTARGETS,
  107. };
  108. #define THRESHOLDS_EVENTS_TARGET 128
  109. #define SOFTLIMIT_EVENTS_TARGET 1024
  110. #define NUMAINFO_EVENTS_TARGET 1024
  111. struct mem_cgroup_stat_cpu {
  112. long count[MEM_CGROUP_STAT_NSTATS];
  113. unsigned long events[MEMCG_NR_EVENTS];
  114. unsigned long nr_page_events;
  115. unsigned long targets[MEM_CGROUP_NTARGETS];
  116. };
  117. struct reclaim_iter {
  118. struct mem_cgroup *position;
  119. /* scan generation, increased every round-trip */
  120. unsigned int generation;
  121. };
  122. /*
  123. * per-zone information in memory controller.
  124. */
  125. struct mem_cgroup_per_zone {
  126. struct lruvec lruvec;
  127. unsigned long lru_size[NR_LRU_LISTS];
  128. struct reclaim_iter iter[DEF_PRIORITY + 1];
  129. struct rb_node tree_node; /* RB tree node */
  130. unsigned long usage_in_excess;/* Set to the value by which */
  131. /* the soft limit is exceeded*/
  132. bool on_tree;
  133. struct mem_cgroup *memcg; /* Back pointer, we cannot */
  134. /* use container_of */
  135. };
  136. struct mem_cgroup_per_node {
  137. struct mem_cgroup_per_zone zoneinfo[MAX_NR_ZONES];
  138. };
  139. /*
  140. * Cgroups above their limits are maintained in a RB-Tree, independent of
  141. * their hierarchy representation
  142. */
  143. struct mem_cgroup_tree_per_zone {
  144. struct rb_root rb_root;
  145. spinlock_t lock;
  146. };
  147. struct mem_cgroup_tree_per_node {
  148. struct mem_cgroup_tree_per_zone rb_tree_per_zone[MAX_NR_ZONES];
  149. };
  150. struct mem_cgroup_tree {
  151. struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
  152. };
  153. static struct mem_cgroup_tree soft_limit_tree __read_mostly;
  154. struct mem_cgroup_threshold {
  155. struct eventfd_ctx *eventfd;
  156. unsigned long threshold;
  157. };
  158. /* For threshold */
  159. struct mem_cgroup_threshold_ary {
  160. /* An array index points to threshold just below or equal to usage. */
  161. int current_threshold;
  162. /* Size of entries[] */
  163. unsigned int size;
  164. /* Array of thresholds */
  165. struct mem_cgroup_threshold entries[0];
  166. };
  167. struct mem_cgroup_thresholds {
  168. /* Primary thresholds array */
  169. struct mem_cgroup_threshold_ary *primary;
  170. /*
  171. * Spare threshold array.
  172. * This is needed to make mem_cgroup_unregister_event() "never fail".
  173. * It must be able to store at least primary->size - 1 entries.
  174. */
  175. struct mem_cgroup_threshold_ary *spare;
  176. };
  177. /* for OOM */
  178. struct mem_cgroup_eventfd_list {
  179. struct list_head list;
  180. struct eventfd_ctx *eventfd;
  181. };
  182. /*
  183. * cgroup_event represents events which userspace want to receive.
  184. */
  185. struct mem_cgroup_event {
  186. /*
  187. * memcg which the event belongs to.
  188. */
  189. struct mem_cgroup *memcg;
  190. /*
  191. * eventfd to signal userspace about the event.
  192. */
  193. struct eventfd_ctx *eventfd;
  194. /*
  195. * Each of these stored in a list by the cgroup.
  196. */
  197. struct list_head list;
  198. /*
  199. * register_event() callback will be used to add new userspace
  200. * waiter for changes related to this event. Use eventfd_signal()
  201. * on eventfd to send notification to userspace.
  202. */
  203. int (*register_event)(struct mem_cgroup *memcg,
  204. struct eventfd_ctx *eventfd, const char *args);
  205. /*
  206. * unregister_event() callback will be called when userspace closes
  207. * the eventfd or on cgroup removing. This callback must be set,
  208. * if you want provide notification functionality.
  209. */
  210. void (*unregister_event)(struct mem_cgroup *memcg,
  211. struct eventfd_ctx *eventfd);
  212. /*
  213. * All fields below needed to unregister event when
  214. * userspace closes eventfd.
  215. */
  216. poll_table pt;
  217. wait_queue_head_t *wqh;
  218. wait_queue_t wait;
  219. struct work_struct remove;
  220. };
  221. static void mem_cgroup_threshold(struct mem_cgroup *memcg);
  222. static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
  223. /*
  224. * The memory controller data structure. The memory controller controls both
  225. * page cache and RSS per cgroup. We would eventually like to provide
  226. * statistics based on the statistics developed by Rik Van Riel for clock-pro,
  227. * to help the administrator determine what knobs to tune.
  228. *
  229. * TODO: Add a water mark for the memory controller. Reclaim will begin when
  230. * we hit the water mark. May be even add a low water mark, such that
  231. * no reclaim occurs from a cgroup at it's low water mark, this is
  232. * a feature that will be implemented much later in the future.
  233. */
  234. struct mem_cgroup {
  235. struct cgroup_subsys_state css;
  236. /* Accounted resources */
  237. struct page_counter memory;
  238. struct page_counter memsw;
  239. struct page_counter kmem;
  240. /* Normal memory consumption range */
  241. unsigned long low;
  242. unsigned long high;
  243. unsigned long soft_limit;
  244. /* vmpressure notifications */
  245. struct vmpressure vmpressure;
  246. /* css_online() has been completed */
  247. int initialized;
  248. /*
  249. * Should the accounting and control be hierarchical, per subtree?
  250. */
  251. bool use_hierarchy;
  252. bool oom_lock;
  253. atomic_t under_oom;
  254. atomic_t oom_wakeups;
  255. int swappiness;
  256. /* OOM-Killer disable */
  257. int oom_kill_disable;
  258. /* protect arrays of thresholds */
  259. struct mutex thresholds_lock;
  260. /* thresholds for memory usage. RCU-protected */
  261. struct mem_cgroup_thresholds thresholds;
  262. /* thresholds for mem+swap usage. RCU-protected */
  263. struct mem_cgroup_thresholds memsw_thresholds;
  264. /* For oom notifier event fd */
  265. struct list_head oom_notify;
  266. /*
  267. * Should we move charges of a task when a task is moved into this
  268. * mem_cgroup ? And what type of charges should we move ?
  269. */
  270. unsigned long move_charge_at_immigrate;
  271. /*
  272. * set > 0 if pages under this cgroup are moving to other cgroup.
  273. */
  274. atomic_t moving_account;
  275. /* taken only while moving_account > 0 */
  276. spinlock_t move_lock;
  277. struct task_struct *move_lock_task;
  278. unsigned long move_lock_flags;
  279. /*
  280. * percpu counter.
  281. */
  282. struct mem_cgroup_stat_cpu __percpu *stat;
  283. /*
  284. * used when a cpu is offlined or other synchronizations
  285. * See mem_cgroup_read_stat().
  286. */
  287. struct mem_cgroup_stat_cpu nocpu_base;
  288. spinlock_t pcp_counter_lock;
  289. #if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_INET)
  290. struct cg_proto tcp_mem;
  291. #endif
  292. #if defined(CONFIG_MEMCG_KMEM)
  293. /* Index in the kmem_cache->memcg_params.memcg_caches array */
  294. int kmemcg_id;
  295. #endif
  296. int last_scanned_node;
  297. #if MAX_NUMNODES > 1
  298. nodemask_t scan_nodes;
  299. atomic_t numainfo_events;
  300. atomic_t numainfo_updating;
  301. #endif
  302. /* List of events which userspace want to receive */
  303. struct list_head event_list;
  304. spinlock_t event_list_lock;
  305. struct mem_cgroup_per_node *nodeinfo[0];
  306. /* WARNING: nodeinfo must be the last member here */
  307. };
  308. #ifdef CONFIG_MEMCG_KMEM
  309. bool memcg_kmem_is_active(struct mem_cgroup *memcg)
  310. {
  311. return memcg->kmemcg_id >= 0;
  312. }
  313. #endif
  314. /* Stuffs for move charges at task migration. */
  315. /*
  316. * Types of charges to be moved.
  317. */
  318. #define MOVE_ANON 0x1U
  319. #define MOVE_FILE 0x2U
  320. #define MOVE_MASK (MOVE_ANON | MOVE_FILE)
  321. /* "mc" and its members are protected by cgroup_mutex */
  322. static struct move_charge_struct {
  323. spinlock_t lock; /* for from, to */
  324. struct mem_cgroup *from;
  325. struct mem_cgroup *to;
  326. unsigned long flags;
  327. unsigned long precharge;
  328. unsigned long moved_charge;
  329. unsigned long moved_swap;
  330. struct task_struct *moving_task; /* a task moving charges */
  331. wait_queue_head_t waitq; /* a waitq for other context */
  332. } mc = {
  333. .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
  334. .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
  335. };
  336. /*
  337. * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
  338. * limit reclaim to prevent infinite loops, if they ever occur.
  339. */
  340. #define MEM_CGROUP_MAX_RECLAIM_LOOPS 100
  341. #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS 2
  342. enum charge_type {
  343. MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
  344. MEM_CGROUP_CHARGE_TYPE_ANON,
  345. MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
  346. MEM_CGROUP_CHARGE_TYPE_DROP, /* a page was unused swap cache */
  347. NR_CHARGE_TYPE,
  348. };
  349. /* for encoding cft->private value on file */
  350. enum res_type {
  351. _MEM,
  352. _MEMSWAP,
  353. _OOM_TYPE,
  354. _KMEM,
  355. };
  356. #define MEMFILE_PRIVATE(x, val) ((x) << 16 | (val))
  357. #define MEMFILE_TYPE(val) ((val) >> 16 & 0xffff)
  358. #define MEMFILE_ATTR(val) ((val) & 0xffff)
  359. /* Used for OOM nofiier */
  360. #define OOM_CONTROL (0)
  361. /*
  362. * The memcg_create_mutex will be held whenever a new cgroup is created.
  363. * As a consequence, any change that needs to protect against new child cgroups
  364. * appearing has to hold it as well.
  365. */
  366. static DEFINE_MUTEX(memcg_create_mutex);
  367. struct mem_cgroup *mem_cgroup_from_css(struct cgroup_subsys_state *s)
  368. {
  369. return s ? container_of(s, struct mem_cgroup, css) : NULL;
  370. }
  371. /* Some nice accessors for the vmpressure. */
  372. struct vmpressure *memcg_to_vmpressure(struct mem_cgroup *memcg)
  373. {
  374. if (!memcg)
  375. memcg = root_mem_cgroup;
  376. return &memcg->vmpressure;
  377. }
  378. struct cgroup_subsys_state *vmpressure_to_css(struct vmpressure *vmpr)
  379. {
  380. return &container_of(vmpr, struct mem_cgroup, vmpressure)->css;
  381. }
  382. static inline bool mem_cgroup_is_root(struct mem_cgroup *memcg)
  383. {
  384. return (memcg == root_mem_cgroup);
  385. }
  386. /*
  387. * We restrict the id in the range of [1, 65535], so it can fit into
  388. * an unsigned short.
  389. */
  390. #define MEM_CGROUP_ID_MAX USHRT_MAX
  391. static inline unsigned short mem_cgroup_id(struct mem_cgroup *memcg)
  392. {
  393. return memcg->css.id;
  394. }
  395. static inline struct mem_cgroup *mem_cgroup_from_id(unsigned short id)
  396. {
  397. struct cgroup_subsys_state *css;
  398. css = css_from_id(id, &memory_cgrp_subsys);
  399. return mem_cgroup_from_css(css);
  400. }
  401. /* Writing them here to avoid exposing memcg's inner layout */
  402. #if defined(CONFIG_INET) && defined(CONFIG_MEMCG_KMEM)
  403. void sock_update_memcg(struct sock *sk)
  404. {
  405. if (mem_cgroup_sockets_enabled) {
  406. struct mem_cgroup *memcg;
  407. struct cg_proto *cg_proto;
  408. BUG_ON(!sk->sk_prot->proto_cgroup);
  409. /* Socket cloning can throw us here with sk_cgrp already
  410. * filled. It won't however, necessarily happen from
  411. * process context. So the test for root memcg given
  412. * the current task's memcg won't help us in this case.
  413. *
  414. * Respecting the original socket's memcg is a better
  415. * decision in this case.
  416. */
  417. if (sk->sk_cgrp) {
  418. BUG_ON(mem_cgroup_is_root(sk->sk_cgrp->memcg));
  419. css_get(&sk->sk_cgrp->memcg->css);
  420. return;
  421. }
  422. rcu_read_lock();
  423. memcg = mem_cgroup_from_task(current);
  424. cg_proto = sk->sk_prot->proto_cgroup(memcg);
  425. if (!mem_cgroup_is_root(memcg) &&
  426. memcg_proto_active(cg_proto) &&
  427. css_tryget_online(&memcg->css)) {
  428. sk->sk_cgrp = cg_proto;
  429. }
  430. rcu_read_unlock();
  431. }
  432. }
  433. EXPORT_SYMBOL(sock_update_memcg);
  434. void sock_release_memcg(struct sock *sk)
  435. {
  436. if (mem_cgroup_sockets_enabled && sk->sk_cgrp) {
  437. struct mem_cgroup *memcg;
  438. WARN_ON(!sk->sk_cgrp->memcg);
  439. memcg = sk->sk_cgrp->memcg;
  440. css_put(&sk->sk_cgrp->memcg->css);
  441. }
  442. }
  443. struct cg_proto *tcp_proto_cgroup(struct mem_cgroup *memcg)
  444. {
  445. if (!memcg || mem_cgroup_is_root(memcg))
  446. return NULL;
  447. return &memcg->tcp_mem;
  448. }
  449. EXPORT_SYMBOL(tcp_proto_cgroup);
  450. static void disarm_sock_keys(struct mem_cgroup *memcg)
  451. {
  452. if (!memcg_proto_activated(&memcg->tcp_mem))
  453. return;
  454. static_key_slow_dec(&memcg_socket_limit_enabled);
  455. }
  456. #else
  457. static void disarm_sock_keys(struct mem_cgroup *memcg)
  458. {
  459. }
  460. #endif
  461. #ifdef CONFIG_MEMCG_KMEM
  462. /*
  463. * This will be the memcg's index in each cache's ->memcg_params.memcg_caches.
  464. * The main reason for not using cgroup id for this:
  465. * this works better in sparse environments, where we have a lot of memcgs,
  466. * but only a few kmem-limited. Or also, if we have, for instance, 200
  467. * memcgs, and none but the 200th is kmem-limited, we'd have to have a
  468. * 200 entry array for that.
  469. *
  470. * The current size of the caches array is stored in memcg_nr_cache_ids. It
  471. * will double each time we have to increase it.
  472. */
  473. static DEFINE_IDA(memcg_cache_ida);
  474. int memcg_nr_cache_ids;
  475. /* Protects memcg_nr_cache_ids */
  476. static DECLARE_RWSEM(memcg_cache_ids_sem);
  477. void memcg_get_cache_ids(void)
  478. {
  479. down_read(&memcg_cache_ids_sem);
  480. }
  481. void memcg_put_cache_ids(void)
  482. {
  483. up_read(&memcg_cache_ids_sem);
  484. }
  485. /*
  486. * MIN_SIZE is different than 1, because we would like to avoid going through
  487. * the alloc/free process all the time. In a small machine, 4 kmem-limited
  488. * cgroups is a reasonable guess. In the future, it could be a parameter or
  489. * tunable, but that is strictly not necessary.
  490. *
  491. * MAX_SIZE should be as large as the number of cgrp_ids. Ideally, we could get
  492. * this constant directly from cgroup, but it is understandable that this is
  493. * better kept as an internal representation in cgroup.c. In any case, the
  494. * cgrp_id space is not getting any smaller, and we don't have to necessarily
  495. * increase ours as well if it increases.
  496. */
  497. #define MEMCG_CACHES_MIN_SIZE 4
  498. #define MEMCG_CACHES_MAX_SIZE MEM_CGROUP_ID_MAX
  499. /*
  500. * A lot of the calls to the cache allocation functions are expected to be
  501. * inlined by the compiler. Since the calls to memcg_kmem_get_cache are
  502. * conditional to this static branch, we'll have to allow modules that does
  503. * kmem_cache_alloc and the such to see this symbol as well
  504. */
  505. struct static_key memcg_kmem_enabled_key;
  506. EXPORT_SYMBOL(memcg_kmem_enabled_key);
  507. static void memcg_free_cache_id(int id);
  508. static void disarm_kmem_keys(struct mem_cgroup *memcg)
  509. {
  510. if (memcg_kmem_is_active(memcg)) {
  511. static_key_slow_dec(&memcg_kmem_enabled_key);
  512. memcg_free_cache_id(memcg->kmemcg_id);
  513. }
  514. /*
  515. * This check can't live in kmem destruction function,
  516. * since the charges will outlive the cgroup
  517. */
  518. WARN_ON(page_counter_read(&memcg->kmem));
  519. }
  520. #else
  521. static void disarm_kmem_keys(struct mem_cgroup *memcg)
  522. {
  523. }
  524. #endif /* CONFIG_MEMCG_KMEM */
  525. static void disarm_static_keys(struct mem_cgroup *memcg)
  526. {
  527. disarm_sock_keys(memcg);
  528. disarm_kmem_keys(memcg);
  529. }
  530. static struct mem_cgroup_per_zone *
  531. mem_cgroup_zone_zoneinfo(struct mem_cgroup *memcg, struct zone *zone)
  532. {
  533. int nid = zone_to_nid(zone);
  534. int zid = zone_idx(zone);
  535. return &memcg->nodeinfo[nid]->zoneinfo[zid];
  536. }
  537. struct cgroup_subsys_state *mem_cgroup_css(struct mem_cgroup *memcg)
  538. {
  539. return &memcg->css;
  540. }
  541. static struct mem_cgroup_per_zone *
  542. mem_cgroup_page_zoneinfo(struct mem_cgroup *memcg, struct page *page)
  543. {
  544. int nid = page_to_nid(page);
  545. int zid = page_zonenum(page);
  546. return &memcg->nodeinfo[nid]->zoneinfo[zid];
  547. }
  548. static struct mem_cgroup_tree_per_zone *
  549. soft_limit_tree_node_zone(int nid, int zid)
  550. {
  551. return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
  552. }
  553. static struct mem_cgroup_tree_per_zone *
  554. soft_limit_tree_from_page(struct page *page)
  555. {
  556. int nid = page_to_nid(page);
  557. int zid = page_zonenum(page);
  558. return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
  559. }
  560. static void __mem_cgroup_insert_exceeded(struct mem_cgroup_per_zone *mz,
  561. struct mem_cgroup_tree_per_zone *mctz,
  562. unsigned long new_usage_in_excess)
  563. {
  564. struct rb_node **p = &mctz->rb_root.rb_node;
  565. struct rb_node *parent = NULL;
  566. struct mem_cgroup_per_zone *mz_node;
  567. if (mz->on_tree)
  568. return;
  569. mz->usage_in_excess = new_usage_in_excess;
  570. if (!mz->usage_in_excess)
  571. return;
  572. while (*p) {
  573. parent = *p;
  574. mz_node = rb_entry(parent, struct mem_cgroup_per_zone,
  575. tree_node);
  576. if (mz->usage_in_excess < mz_node->usage_in_excess)
  577. p = &(*p)->rb_left;
  578. /*
  579. * We can't avoid mem cgroups that are over their soft
  580. * limit by the same amount
  581. */
  582. else if (mz->usage_in_excess >= mz_node->usage_in_excess)
  583. p = &(*p)->rb_right;
  584. }
  585. rb_link_node(&mz->tree_node, parent, p);
  586. rb_insert_color(&mz->tree_node, &mctz->rb_root);
  587. mz->on_tree = true;
  588. }
  589. static void __mem_cgroup_remove_exceeded(struct mem_cgroup_per_zone *mz,
  590. struct mem_cgroup_tree_per_zone *mctz)
  591. {
  592. if (!mz->on_tree)
  593. return;
  594. rb_erase(&mz->tree_node, &mctz->rb_root);
  595. mz->on_tree = false;
  596. }
  597. static void mem_cgroup_remove_exceeded(struct mem_cgroup_per_zone *mz,
  598. struct mem_cgroup_tree_per_zone *mctz)
  599. {
  600. unsigned long flags;
  601. spin_lock_irqsave(&mctz->lock, flags);
  602. __mem_cgroup_remove_exceeded(mz, mctz);
  603. spin_unlock_irqrestore(&mctz->lock, flags);
  604. }
  605. static unsigned long soft_limit_excess(struct mem_cgroup *memcg)
  606. {
  607. unsigned long nr_pages = page_counter_read(&memcg->memory);
  608. unsigned long soft_limit = ACCESS_ONCE(memcg->soft_limit);
  609. unsigned long excess = 0;
  610. if (nr_pages > soft_limit)
  611. excess = nr_pages - soft_limit;
  612. return excess;
  613. }
  614. static void mem_cgroup_update_tree(struct mem_cgroup *memcg, struct page *page)
  615. {
  616. unsigned long excess;
  617. struct mem_cgroup_per_zone *mz;
  618. struct mem_cgroup_tree_per_zone *mctz;
  619. mctz = soft_limit_tree_from_page(page);
  620. /*
  621. * Necessary to update all ancestors when hierarchy is used.
  622. * because their event counter is not touched.
  623. */
  624. for (; memcg; memcg = parent_mem_cgroup(memcg)) {
  625. mz = mem_cgroup_page_zoneinfo(memcg, page);
  626. excess = soft_limit_excess(memcg);
  627. /*
  628. * We have to update the tree if mz is on RB-tree or
  629. * mem is over its softlimit.
  630. */
  631. if (excess || mz->on_tree) {
  632. unsigned long flags;
  633. spin_lock_irqsave(&mctz->lock, flags);
  634. /* if on-tree, remove it */
  635. if (mz->on_tree)
  636. __mem_cgroup_remove_exceeded(mz, mctz);
  637. /*
  638. * Insert again. mz->usage_in_excess will be updated.
  639. * If excess is 0, no tree ops.
  640. */
  641. __mem_cgroup_insert_exceeded(mz, mctz, excess);
  642. spin_unlock_irqrestore(&mctz->lock, flags);
  643. }
  644. }
  645. }
  646. static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
  647. {
  648. struct mem_cgroup_tree_per_zone *mctz;
  649. struct mem_cgroup_per_zone *mz;
  650. int nid, zid;
  651. for_each_node(nid) {
  652. for (zid = 0; zid < MAX_NR_ZONES; zid++) {
  653. mz = &memcg->nodeinfo[nid]->zoneinfo[zid];
  654. mctz = soft_limit_tree_node_zone(nid, zid);
  655. mem_cgroup_remove_exceeded(mz, mctz);
  656. }
  657. }
  658. }
  659. static struct mem_cgroup_per_zone *
  660. __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
  661. {
  662. struct rb_node *rightmost = NULL;
  663. struct mem_cgroup_per_zone *mz;
  664. retry:
  665. mz = NULL;
  666. rightmost = rb_last(&mctz->rb_root);
  667. if (!rightmost)
  668. goto done; /* Nothing to reclaim from */
  669. mz = rb_entry(rightmost, struct mem_cgroup_per_zone, tree_node);
  670. /*
  671. * Remove the node now but someone else can add it back,
  672. * we will to add it back at the end of reclaim to its correct
  673. * position in the tree.
  674. */
  675. __mem_cgroup_remove_exceeded(mz, mctz);
  676. if (!soft_limit_excess(mz->memcg) ||
  677. !css_tryget_online(&mz->memcg->css))
  678. goto retry;
  679. done:
  680. return mz;
  681. }
  682. static struct mem_cgroup_per_zone *
  683. mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
  684. {
  685. struct mem_cgroup_per_zone *mz;
  686. spin_lock_irq(&mctz->lock);
  687. mz = __mem_cgroup_largest_soft_limit_node(mctz);
  688. spin_unlock_irq(&mctz->lock);
  689. return mz;
  690. }
  691. /*
  692. * Implementation Note: reading percpu statistics for memcg.
  693. *
  694. * Both of vmstat[] and percpu_counter has threshold and do periodic
  695. * synchronization to implement "quick" read. There are trade-off between
  696. * reading cost and precision of value. Then, we may have a chance to implement
  697. * a periodic synchronizion of counter in memcg's counter.
  698. *
  699. * But this _read() function is used for user interface now. The user accounts
  700. * memory usage by memory cgroup and he _always_ requires exact value because
  701. * he accounts memory. Even if we provide quick-and-fuzzy read, we always
  702. * have to visit all online cpus and make sum. So, for now, unnecessary
  703. * synchronization is not implemented. (just implemented for cpu hotplug)
  704. *
  705. * If there are kernel internal actions which can make use of some not-exact
  706. * value, and reading all cpu value can be performance bottleneck in some
  707. * common workload, threashold and synchonization as vmstat[] should be
  708. * implemented.
  709. */
  710. static long mem_cgroup_read_stat(struct mem_cgroup *memcg,
  711. enum mem_cgroup_stat_index idx)
  712. {
  713. long val = 0;
  714. int cpu;
  715. get_online_cpus();
  716. for_each_online_cpu(cpu)
  717. val += per_cpu(memcg->stat->count[idx], cpu);
  718. #ifdef CONFIG_HOTPLUG_CPU
  719. spin_lock(&memcg->pcp_counter_lock);
  720. val += memcg->nocpu_base.count[idx];
  721. spin_unlock(&memcg->pcp_counter_lock);
  722. #endif
  723. put_online_cpus();
  724. return val;
  725. }
  726. static unsigned long mem_cgroup_read_events(struct mem_cgroup *memcg,
  727. enum mem_cgroup_events_index idx)
  728. {
  729. unsigned long val = 0;
  730. int cpu;
  731. get_online_cpus();
  732. for_each_online_cpu(cpu)
  733. val += per_cpu(memcg->stat->events[idx], cpu);
  734. #ifdef CONFIG_HOTPLUG_CPU
  735. spin_lock(&memcg->pcp_counter_lock);
  736. val += memcg->nocpu_base.events[idx];
  737. spin_unlock(&memcg->pcp_counter_lock);
  738. #endif
  739. put_online_cpus();
  740. return val;
  741. }
  742. static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
  743. struct page *page,
  744. int nr_pages)
  745. {
  746. /*
  747. * Here, RSS means 'mapped anon' and anon's SwapCache. Shmem/tmpfs is
  748. * counted as CACHE even if it's on ANON LRU.
  749. */
  750. if (PageAnon(page))
  751. __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_RSS],
  752. nr_pages);
  753. else
  754. __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_CACHE],
  755. nr_pages);
  756. if (PageTransHuge(page))
  757. __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_RSS_HUGE],
  758. nr_pages);
  759. /* pagein of a big page is an event. So, ignore page size */
  760. if (nr_pages > 0)
  761. __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGIN]);
  762. else {
  763. __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGOUT]);
  764. nr_pages = -nr_pages; /* for event */
  765. }
  766. __this_cpu_add(memcg->stat->nr_page_events, nr_pages);
  767. }
  768. unsigned long mem_cgroup_get_lru_size(struct lruvec *lruvec, enum lru_list lru)
  769. {
  770. struct mem_cgroup_per_zone *mz;
  771. mz = container_of(lruvec, struct mem_cgroup_per_zone, lruvec);
  772. return mz->lru_size[lru];
  773. }
  774. static unsigned long mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
  775. int nid,
  776. unsigned int lru_mask)
  777. {
  778. unsigned long nr = 0;
  779. int zid;
  780. VM_BUG_ON((unsigned)nid >= nr_node_ids);
  781. for (zid = 0; zid < MAX_NR_ZONES; zid++) {
  782. struct mem_cgroup_per_zone *mz;
  783. enum lru_list lru;
  784. for_each_lru(lru) {
  785. if (!(BIT(lru) & lru_mask))
  786. continue;
  787. mz = &memcg->nodeinfo[nid]->zoneinfo[zid];
  788. nr += mz->lru_size[lru];
  789. }
  790. }
  791. return nr;
  792. }
  793. static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
  794. unsigned int lru_mask)
  795. {
  796. unsigned long nr = 0;
  797. int nid;
  798. for_each_node_state(nid, N_MEMORY)
  799. nr += mem_cgroup_node_nr_lru_pages(memcg, nid, lru_mask);
  800. return nr;
  801. }
  802. static bool mem_cgroup_event_ratelimit(struct mem_cgroup *memcg,
  803. enum mem_cgroup_events_target target)
  804. {
  805. unsigned long val, next;
  806. val = __this_cpu_read(memcg->stat->nr_page_events);
  807. next = __this_cpu_read(memcg->stat->targets[target]);
  808. /* from time_after() in jiffies.h */
  809. if ((long)next - (long)val < 0) {
  810. switch (target) {
  811. case MEM_CGROUP_TARGET_THRESH:
  812. next = val + THRESHOLDS_EVENTS_TARGET;
  813. break;
  814. case MEM_CGROUP_TARGET_SOFTLIMIT:
  815. next = val + SOFTLIMIT_EVENTS_TARGET;
  816. break;
  817. case MEM_CGROUP_TARGET_NUMAINFO:
  818. next = val + NUMAINFO_EVENTS_TARGET;
  819. break;
  820. default:
  821. break;
  822. }
  823. __this_cpu_write(memcg->stat->targets[target], next);
  824. return true;
  825. }
  826. return false;
  827. }
  828. /*
  829. * Check events in order.
  830. *
  831. */
  832. static void memcg_check_events(struct mem_cgroup *memcg, struct page *page)
  833. {
  834. /* threshold event is triggered in finer grain than soft limit */
  835. if (unlikely(mem_cgroup_event_ratelimit(memcg,
  836. MEM_CGROUP_TARGET_THRESH))) {
  837. bool do_softlimit;
  838. bool do_numainfo __maybe_unused;
  839. do_softlimit = mem_cgroup_event_ratelimit(memcg,
  840. MEM_CGROUP_TARGET_SOFTLIMIT);
  841. #if MAX_NUMNODES > 1
  842. do_numainfo = mem_cgroup_event_ratelimit(memcg,
  843. MEM_CGROUP_TARGET_NUMAINFO);
  844. #endif
  845. mem_cgroup_threshold(memcg);
  846. if (unlikely(do_softlimit))
  847. mem_cgroup_update_tree(memcg, page);
  848. #if MAX_NUMNODES > 1
  849. if (unlikely(do_numainfo))
  850. atomic_inc(&memcg->numainfo_events);
  851. #endif
  852. }
  853. }
  854. struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
  855. {
  856. /*
  857. * mm_update_next_owner() may clear mm->owner to NULL
  858. * if it races with swapoff, page migration, etc.
  859. * So this can be called with p == NULL.
  860. */
  861. if (unlikely(!p))
  862. return NULL;
  863. return mem_cgroup_from_css(task_css(p, memory_cgrp_id));
  864. }
  865. static struct mem_cgroup *get_mem_cgroup_from_mm(struct mm_struct *mm)
  866. {
  867. struct mem_cgroup *memcg = NULL;
  868. rcu_read_lock();
  869. do {
  870. /*
  871. * Page cache insertions can happen withou an
  872. * actual mm context, e.g. during disk probing
  873. * on boot, loopback IO, acct() writes etc.
  874. */
  875. if (unlikely(!mm))
  876. memcg = root_mem_cgroup;
  877. else {
  878. memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
  879. if (unlikely(!memcg))
  880. memcg = root_mem_cgroup;
  881. }
  882. } while (!css_tryget_online(&memcg->css));
  883. rcu_read_unlock();
  884. return memcg;
  885. }
  886. /**
  887. * mem_cgroup_iter - iterate over memory cgroup hierarchy
  888. * @root: hierarchy root
  889. * @prev: previously returned memcg, NULL on first invocation
  890. * @reclaim: cookie for shared reclaim walks, NULL for full walks
  891. *
  892. * Returns references to children of the hierarchy below @root, or
  893. * @root itself, or %NULL after a full round-trip.
  894. *
  895. * Caller must pass the return value in @prev on subsequent
  896. * invocations for reference counting, or use mem_cgroup_iter_break()
  897. * to cancel a hierarchy walk before the round-trip is complete.
  898. *
  899. * Reclaimers can specify a zone and a priority level in @reclaim to
  900. * divide up the memcgs in the hierarchy among all concurrent
  901. * reclaimers operating on the same zone and priority.
  902. */
  903. struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
  904. struct mem_cgroup *prev,
  905. struct mem_cgroup_reclaim_cookie *reclaim)
  906. {
  907. struct reclaim_iter *uninitialized_var(iter);
  908. struct cgroup_subsys_state *css = NULL;
  909. struct mem_cgroup *memcg = NULL;
  910. struct mem_cgroup *pos = NULL;
  911. if (mem_cgroup_disabled())
  912. return NULL;
  913. if (!root)
  914. root = root_mem_cgroup;
  915. if (prev && !reclaim)
  916. pos = prev;
  917. if (!root->use_hierarchy && root != root_mem_cgroup) {
  918. if (prev)
  919. goto out;
  920. return root;
  921. }
  922. rcu_read_lock();
  923. if (reclaim) {
  924. struct mem_cgroup_per_zone *mz;
  925. mz = mem_cgroup_zone_zoneinfo(root, reclaim->zone);
  926. iter = &mz->iter[reclaim->priority];
  927. if (prev && reclaim->generation != iter->generation)
  928. goto out_unlock;
  929. do {
  930. pos = ACCESS_ONCE(iter->position);
  931. /*
  932. * A racing update may change the position and
  933. * put the last reference, hence css_tryget(),
  934. * or retry to see the updated position.
  935. */
  936. } while (pos && !css_tryget(&pos->css));
  937. }
  938. if (pos)
  939. css = &pos->css;
  940. for (;;) {
  941. css = css_next_descendant_pre(css, &root->css);
  942. if (!css) {
  943. /*
  944. * Reclaimers share the hierarchy walk, and a
  945. * new one might jump in right at the end of
  946. * the hierarchy - make sure they see at least
  947. * one group and restart from the beginning.
  948. */
  949. if (!prev)
  950. continue;
  951. break;
  952. }
  953. /*
  954. * Verify the css and acquire a reference. The root
  955. * is provided by the caller, so we know it's alive
  956. * and kicking, and don't take an extra reference.
  957. */
  958. memcg = mem_cgroup_from_css(css);
  959. if (css == &root->css)
  960. break;
  961. if (css_tryget(css)) {
  962. /*
  963. * Make sure the memcg is initialized:
  964. * mem_cgroup_css_online() orders the the
  965. * initialization against setting the flag.
  966. */
  967. if (smp_load_acquire(&memcg->initialized))
  968. break;
  969. css_put(css);
  970. }
  971. memcg = NULL;
  972. }
  973. if (reclaim) {
  974. if (cmpxchg(&iter->position, pos, memcg) == pos) {
  975. if (memcg)
  976. css_get(&memcg->css);
  977. if (pos)
  978. css_put(&pos->css);
  979. }
  980. /*
  981. * pairs with css_tryget when dereferencing iter->position
  982. * above.
  983. */
  984. if (pos)
  985. css_put(&pos->css);
  986. if (!memcg)
  987. iter->generation++;
  988. else if (!prev)
  989. reclaim->generation = iter->generation;
  990. }
  991. out_unlock:
  992. rcu_read_unlock();
  993. out:
  994. if (prev && prev != root)
  995. css_put(&prev->css);
  996. return memcg;
  997. }
  998. /**
  999. * mem_cgroup_iter_break - abort a hierarchy walk prematurely
  1000. * @root: hierarchy root
  1001. * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
  1002. */
  1003. void mem_cgroup_iter_break(struct mem_cgroup *root,
  1004. struct mem_cgroup *prev)
  1005. {
  1006. if (!root)
  1007. root = root_mem_cgroup;
  1008. if (prev && prev != root)
  1009. css_put(&prev->css);
  1010. }
  1011. /*
  1012. * Iteration constructs for visiting all cgroups (under a tree). If
  1013. * loops are exited prematurely (break), mem_cgroup_iter_break() must
  1014. * be used for reference counting.
  1015. */
  1016. #define for_each_mem_cgroup_tree(iter, root) \
  1017. for (iter = mem_cgroup_iter(root, NULL, NULL); \
  1018. iter != NULL; \
  1019. iter = mem_cgroup_iter(root, iter, NULL))
  1020. #define for_each_mem_cgroup(iter) \
  1021. for (iter = mem_cgroup_iter(NULL, NULL, NULL); \
  1022. iter != NULL; \
  1023. iter = mem_cgroup_iter(NULL, iter, NULL))
  1024. void __mem_cgroup_count_vm_event(struct mm_struct *mm, enum vm_event_item idx)
  1025. {
  1026. struct mem_cgroup *memcg;
  1027. rcu_read_lock();
  1028. memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
  1029. if (unlikely(!memcg))
  1030. goto out;
  1031. switch (idx) {
  1032. case PGFAULT:
  1033. this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGFAULT]);
  1034. break;
  1035. case PGMAJFAULT:
  1036. this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGMAJFAULT]);
  1037. break;
  1038. default:
  1039. BUG();
  1040. }
  1041. out:
  1042. rcu_read_unlock();
  1043. }
  1044. EXPORT_SYMBOL(__mem_cgroup_count_vm_event);
  1045. /**
  1046. * mem_cgroup_zone_lruvec - get the lru list vector for a zone and memcg
  1047. * @zone: zone of the wanted lruvec
  1048. * @memcg: memcg of the wanted lruvec
  1049. *
  1050. * Returns the lru list vector holding pages for the given @zone and
  1051. * @mem. This can be the global zone lruvec, if the memory controller
  1052. * is disabled.
  1053. */
  1054. struct lruvec *mem_cgroup_zone_lruvec(struct zone *zone,
  1055. struct mem_cgroup *memcg)
  1056. {
  1057. struct mem_cgroup_per_zone *mz;
  1058. struct lruvec *lruvec;
  1059. if (mem_cgroup_disabled()) {
  1060. lruvec = &zone->lruvec;
  1061. goto out;
  1062. }
  1063. mz = mem_cgroup_zone_zoneinfo(memcg, zone);
  1064. lruvec = &mz->lruvec;
  1065. out:
  1066. /*
  1067. * Since a node can be onlined after the mem_cgroup was created,
  1068. * we have to be prepared to initialize lruvec->zone here;
  1069. * and if offlined then reonlined, we need to reinitialize it.
  1070. */
  1071. if (unlikely(lruvec->zone != zone))
  1072. lruvec->zone = zone;
  1073. return lruvec;
  1074. }
  1075. /**
  1076. * mem_cgroup_page_lruvec - return lruvec for isolating/putting an LRU page
  1077. * @page: the page
  1078. * @zone: zone of the page
  1079. *
  1080. * This function is only safe when following the LRU page isolation
  1081. * and putback protocol: the LRU lock must be held, and the page must
  1082. * either be PageLRU() or the caller must have isolated/allocated it.
  1083. */
  1084. struct lruvec *mem_cgroup_page_lruvec(struct page *page, struct zone *zone)
  1085. {
  1086. struct mem_cgroup_per_zone *mz;
  1087. struct mem_cgroup *memcg;
  1088. struct lruvec *lruvec;
  1089. if (mem_cgroup_disabled()) {
  1090. lruvec = &zone->lruvec;
  1091. goto out;
  1092. }
  1093. memcg = page->mem_cgroup;
  1094. /*
  1095. * Swapcache readahead pages are added to the LRU - and
  1096. * possibly migrated - before they are charged.
  1097. */
  1098. if (!memcg)
  1099. memcg = root_mem_cgroup;
  1100. mz = mem_cgroup_page_zoneinfo(memcg, page);
  1101. lruvec = &mz->lruvec;
  1102. out:
  1103. /*
  1104. * Since a node can be onlined after the mem_cgroup was created,
  1105. * we have to be prepared to initialize lruvec->zone here;
  1106. * and if offlined then reonlined, we need to reinitialize it.
  1107. */
  1108. if (unlikely(lruvec->zone != zone))
  1109. lruvec->zone = zone;
  1110. return lruvec;
  1111. }
  1112. /**
  1113. * mem_cgroup_update_lru_size - account for adding or removing an lru page
  1114. * @lruvec: mem_cgroup per zone lru vector
  1115. * @lru: index of lru list the page is sitting on
  1116. * @nr_pages: positive when adding or negative when removing
  1117. *
  1118. * This function must be called when a page is added to or removed from an
  1119. * lru list.
  1120. */
  1121. void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
  1122. int nr_pages)
  1123. {
  1124. struct mem_cgroup_per_zone *mz;
  1125. unsigned long *lru_size;
  1126. if (mem_cgroup_disabled())
  1127. return;
  1128. mz = container_of(lruvec, struct mem_cgroup_per_zone, lruvec);
  1129. lru_size = mz->lru_size + lru;
  1130. *lru_size += nr_pages;
  1131. VM_BUG_ON((long)(*lru_size) < 0);
  1132. }
  1133. bool mem_cgroup_is_descendant(struct mem_cgroup *memcg, struct mem_cgroup *root)
  1134. {
  1135. if (root == memcg)
  1136. return true;
  1137. if (!root->use_hierarchy)
  1138. return false;
  1139. return cgroup_is_descendant(memcg->css.cgroup, root->css.cgroup);
  1140. }
  1141. bool task_in_mem_cgroup(struct task_struct *task, struct mem_cgroup *memcg)
  1142. {
  1143. struct mem_cgroup *task_memcg;
  1144. struct task_struct *p;
  1145. bool ret;
  1146. p = find_lock_task_mm(task);
  1147. if (p) {
  1148. task_memcg = get_mem_cgroup_from_mm(p->mm);
  1149. task_unlock(p);
  1150. } else {
  1151. /*
  1152. * All threads may have already detached their mm's, but the oom
  1153. * killer still needs to detect if they have already been oom
  1154. * killed to prevent needlessly killing additional tasks.
  1155. */
  1156. rcu_read_lock();
  1157. task_memcg = mem_cgroup_from_task(task);
  1158. css_get(&task_memcg->css);
  1159. rcu_read_unlock();
  1160. }
  1161. ret = mem_cgroup_is_descendant(task_memcg, memcg);
  1162. css_put(&task_memcg->css);
  1163. return ret;
  1164. }
  1165. int mem_cgroup_inactive_anon_is_low(struct lruvec *lruvec)
  1166. {
  1167. unsigned long inactive_ratio;
  1168. unsigned long inactive;
  1169. unsigned long active;
  1170. unsigned long gb;
  1171. inactive = mem_cgroup_get_lru_size(lruvec, LRU_INACTIVE_ANON);
  1172. active = mem_cgroup_get_lru_size(lruvec, LRU_ACTIVE_ANON);
  1173. gb = (inactive + active) >> (30 - PAGE_SHIFT);
  1174. if (gb)
  1175. inactive_ratio = int_sqrt(10 * gb);
  1176. else
  1177. inactive_ratio = 1;
  1178. return inactive * inactive_ratio < active;
  1179. }
  1180. bool mem_cgroup_lruvec_online(struct lruvec *lruvec)
  1181. {
  1182. struct mem_cgroup_per_zone *mz;
  1183. struct mem_cgroup *memcg;
  1184. if (mem_cgroup_disabled())
  1185. return true;
  1186. mz = container_of(lruvec, struct mem_cgroup_per_zone, lruvec);
  1187. memcg = mz->memcg;
  1188. return !!(memcg->css.flags & CSS_ONLINE);
  1189. }
  1190. #define mem_cgroup_from_counter(counter, member) \
  1191. container_of(counter, struct mem_cgroup, member)
  1192. /**
  1193. * mem_cgroup_margin - calculate chargeable space of a memory cgroup
  1194. * @memcg: the memory cgroup
  1195. *
  1196. * Returns the maximum amount of memory @mem can be charged with, in
  1197. * pages.
  1198. */
  1199. static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
  1200. {
  1201. unsigned long margin = 0;
  1202. unsigned long count;
  1203. unsigned long limit;
  1204. count = page_counter_read(&memcg->memory);
  1205. limit = ACCESS_ONCE(memcg->memory.limit);
  1206. if (count < limit)
  1207. margin = limit - count;
  1208. if (do_swap_account) {
  1209. count = page_counter_read(&memcg->memsw);
  1210. limit = ACCESS_ONCE(memcg->memsw.limit);
  1211. if (count <= limit)
  1212. margin = min(margin, limit - count);
  1213. }
  1214. return margin;
  1215. }
  1216. int mem_cgroup_swappiness(struct mem_cgroup *memcg)
  1217. {
  1218. /* root ? */
  1219. if (mem_cgroup_disabled() || !memcg->css.parent)
  1220. return vm_swappiness;
  1221. return memcg->swappiness;
  1222. }
  1223. /*
  1224. * A routine for checking "mem" is under move_account() or not.
  1225. *
  1226. * Checking a cgroup is mc.from or mc.to or under hierarchy of
  1227. * moving cgroups. This is for waiting at high-memory pressure
  1228. * caused by "move".
  1229. */
  1230. static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
  1231. {
  1232. struct mem_cgroup *from;
  1233. struct mem_cgroup *to;
  1234. bool ret = false;
  1235. /*
  1236. * Unlike task_move routines, we access mc.to, mc.from not under
  1237. * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
  1238. */
  1239. spin_lock(&mc.lock);
  1240. from = mc.from;
  1241. to = mc.to;
  1242. if (!from)
  1243. goto unlock;
  1244. ret = mem_cgroup_is_descendant(from, memcg) ||
  1245. mem_cgroup_is_descendant(to, memcg);
  1246. unlock:
  1247. spin_unlock(&mc.lock);
  1248. return ret;
  1249. }
  1250. static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
  1251. {
  1252. if (mc.moving_task && current != mc.moving_task) {
  1253. if (mem_cgroup_under_move(memcg)) {
  1254. DEFINE_WAIT(wait);
  1255. prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
  1256. /* moving charge context might have finished. */
  1257. if (mc.moving_task)
  1258. schedule();
  1259. finish_wait(&mc.waitq, &wait);
  1260. return true;
  1261. }
  1262. }
  1263. return false;
  1264. }
  1265. #define K(x) ((x) << (PAGE_SHIFT-10))
  1266. /**
  1267. * mem_cgroup_print_oom_info: Print OOM information relevant to memory controller.
  1268. * @memcg: The memory cgroup that went over limit
  1269. * @p: Task that is going to be killed
  1270. *
  1271. * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
  1272. * enabled
  1273. */
  1274. void mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p)
  1275. {
  1276. /* oom_info_lock ensures that parallel ooms do not interleave */
  1277. static DEFINE_MUTEX(oom_info_lock);
  1278. struct mem_cgroup *iter;
  1279. unsigned int i;
  1280. if (!p)
  1281. return;
  1282. mutex_lock(&oom_info_lock);
  1283. rcu_read_lock();
  1284. pr_info("Task in ");
  1285. pr_cont_cgroup_path(task_cgroup(p, memory_cgrp_id));
  1286. pr_cont(" killed as a result of limit of ");
  1287. pr_cont_cgroup_path(memcg->css.cgroup);
  1288. pr_cont("\n");
  1289. rcu_read_unlock();
  1290. pr_info("memory: usage %llukB, limit %llukB, failcnt %lu\n",
  1291. K((u64)page_counter_read(&memcg->memory)),
  1292. K((u64)memcg->memory.limit), memcg->memory.failcnt);
  1293. pr_info("memory+swap: usage %llukB, limit %llukB, failcnt %lu\n",
  1294. K((u64)page_counter_read(&memcg->memsw)),
  1295. K((u64)memcg->memsw.limit), memcg->memsw.failcnt);
  1296. pr_info("kmem: usage %llukB, limit %llukB, failcnt %lu\n",
  1297. K((u64)page_counter_read(&memcg->kmem)),
  1298. K((u64)memcg->kmem.limit), memcg->kmem.failcnt);
  1299. for_each_mem_cgroup_tree(iter, memcg) {
  1300. pr_info("Memory cgroup stats for ");
  1301. pr_cont_cgroup_path(iter->css.cgroup);
  1302. pr_cont(":");
  1303. for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
  1304. if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
  1305. continue;
  1306. pr_cont(" %s:%ldKB", mem_cgroup_stat_names[i],
  1307. K(mem_cgroup_read_stat(iter, i)));
  1308. }
  1309. for (i = 0; i < NR_LRU_LISTS; i++)
  1310. pr_cont(" %s:%luKB", mem_cgroup_lru_names[i],
  1311. K(mem_cgroup_nr_lru_pages(iter, BIT(i))));
  1312. pr_cont("\n");
  1313. }
  1314. mutex_unlock(&oom_info_lock);
  1315. }
  1316. /*
  1317. * This function returns the number of memcg under hierarchy tree. Returns
  1318. * 1(self count) if no children.
  1319. */
  1320. static int mem_cgroup_count_children(struct mem_cgroup *memcg)
  1321. {
  1322. int num = 0;
  1323. struct mem_cgroup *iter;
  1324. for_each_mem_cgroup_tree(iter, memcg)
  1325. num++;
  1326. return num;
  1327. }
  1328. /*
  1329. * Return the memory (and swap, if configured) limit for a memcg.
  1330. */
  1331. static unsigned long mem_cgroup_get_limit(struct mem_cgroup *memcg)
  1332. {
  1333. unsigned long limit;
  1334. limit = memcg->memory.limit;
  1335. if (mem_cgroup_swappiness(memcg)) {
  1336. unsigned long memsw_limit;
  1337. memsw_limit = memcg->memsw.limit;
  1338. limit = min(limit + total_swap_pages, memsw_limit);
  1339. }
  1340. return limit;
  1341. }
  1342. static void mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
  1343. int order)
  1344. {
  1345. struct mem_cgroup *iter;
  1346. unsigned long chosen_points = 0;
  1347. unsigned long totalpages;
  1348. unsigned int points = 0;
  1349. struct task_struct *chosen = NULL;
  1350. /*
  1351. * If current has a pending SIGKILL or is exiting, then automatically
  1352. * select it. The goal is to allow it to allocate so that it may
  1353. * quickly exit and free its memory.
  1354. */
  1355. if (fatal_signal_pending(current) || task_will_free_mem(current)) {
  1356. mark_tsk_oom_victim(current);
  1357. return;
  1358. }
  1359. check_panic_on_oom(CONSTRAINT_MEMCG, gfp_mask, order, NULL);
  1360. totalpages = mem_cgroup_get_limit(memcg) ? : 1;
  1361. for_each_mem_cgroup_tree(iter, memcg) {
  1362. struct css_task_iter it;
  1363. struct task_struct *task;
  1364. css_task_iter_start(&iter->css, &it);
  1365. while ((task = css_task_iter_next(&it))) {
  1366. switch (oom_scan_process_thread(task, totalpages, NULL,
  1367. false)) {
  1368. case OOM_SCAN_SELECT:
  1369. if (chosen)
  1370. put_task_struct(chosen);
  1371. chosen = task;
  1372. chosen_points = ULONG_MAX;
  1373. get_task_struct(chosen);
  1374. /* fall through */
  1375. case OOM_SCAN_CONTINUE:
  1376. continue;
  1377. case OOM_SCAN_ABORT:
  1378. css_task_iter_end(&it);
  1379. mem_cgroup_iter_break(memcg, iter);
  1380. if (chosen)
  1381. put_task_struct(chosen);
  1382. return;
  1383. case OOM_SCAN_OK:
  1384. break;
  1385. };
  1386. points = oom_badness(task, memcg, NULL, totalpages);
  1387. if (!points || points < chosen_points)
  1388. continue;
  1389. /* Prefer thread group leaders for display purposes */
  1390. if (points == chosen_points &&
  1391. thread_group_leader(chosen))
  1392. continue;
  1393. if (chosen)
  1394. put_task_struct(chosen);
  1395. chosen = task;
  1396. chosen_points = points;
  1397. get_task_struct(chosen);
  1398. }
  1399. css_task_iter_end(&it);
  1400. }
  1401. if (!chosen)
  1402. return;
  1403. points = chosen_points * 1000 / totalpages;
  1404. oom_kill_process(chosen, gfp_mask, order, points, totalpages, memcg,
  1405. NULL, "Memory cgroup out of memory");
  1406. }
  1407. #if MAX_NUMNODES > 1
  1408. /**
  1409. * test_mem_cgroup_node_reclaimable
  1410. * @memcg: the target memcg
  1411. * @nid: the node ID to be checked.
  1412. * @noswap : specify true here if the user wants flle only information.
  1413. *
  1414. * This function returns whether the specified memcg contains any
  1415. * reclaimable pages on a node. Returns true if there are any reclaimable
  1416. * pages in the node.
  1417. */
  1418. static bool test_mem_cgroup_node_reclaimable(struct mem_cgroup *memcg,
  1419. int nid, bool noswap)
  1420. {
  1421. if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_FILE))
  1422. return true;
  1423. if (noswap || !total_swap_pages)
  1424. return false;
  1425. if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_ANON))
  1426. return true;
  1427. return false;
  1428. }
  1429. /*
  1430. * Always updating the nodemask is not very good - even if we have an empty
  1431. * list or the wrong list here, we can start from some node and traverse all
  1432. * nodes based on the zonelist. So update the list loosely once per 10 secs.
  1433. *
  1434. */
  1435. static void mem_cgroup_may_update_nodemask(struct mem_cgroup *memcg)
  1436. {
  1437. int nid;
  1438. /*
  1439. * numainfo_events > 0 means there was at least NUMAINFO_EVENTS_TARGET
  1440. * pagein/pageout changes since the last update.
  1441. */
  1442. if (!atomic_read(&memcg->numainfo_events))
  1443. return;
  1444. if (atomic_inc_return(&memcg->numainfo_updating) > 1)
  1445. return;
  1446. /* make a nodemask where this memcg uses memory from */
  1447. memcg->scan_nodes = node_states[N_MEMORY];
  1448. for_each_node_mask(nid, node_states[N_MEMORY]) {
  1449. if (!test_mem_cgroup_node_reclaimable(memcg, nid, false))
  1450. node_clear(nid, memcg->scan_nodes);
  1451. }
  1452. atomic_set(&memcg->numainfo_events, 0);
  1453. atomic_set(&memcg->numainfo_updating, 0);
  1454. }
  1455. /*
  1456. * Selecting a node where we start reclaim from. Because what we need is just
  1457. * reducing usage counter, start from anywhere is O,K. Considering
  1458. * memory reclaim from current node, there are pros. and cons.
  1459. *
  1460. * Freeing memory from current node means freeing memory from a node which
  1461. * we'll use or we've used. So, it may make LRU bad. And if several threads
  1462. * hit limits, it will see a contention on a node. But freeing from remote
  1463. * node means more costs for memory reclaim because of memory latency.
  1464. *
  1465. * Now, we use round-robin. Better algorithm is welcomed.
  1466. */
  1467. int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
  1468. {
  1469. int node;
  1470. mem_cgroup_may_update_nodemask(memcg);
  1471. node = memcg->last_scanned_node;
  1472. node = next_node(node, memcg->scan_nodes);
  1473. if (node == MAX_NUMNODES)
  1474. node = first_node(memcg->scan_nodes);
  1475. /*
  1476. * We call this when we hit limit, not when pages are added to LRU.
  1477. * No LRU may hold pages because all pages are UNEVICTABLE or
  1478. * memcg is too small and all pages are not on LRU. In that case,
  1479. * we use curret node.
  1480. */
  1481. if (unlikely(node == MAX_NUMNODES))
  1482. node = numa_node_id();
  1483. memcg->last_scanned_node = node;
  1484. return node;
  1485. }
  1486. #else
  1487. int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
  1488. {
  1489. return 0;
  1490. }
  1491. #endif
  1492. static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg,
  1493. struct zone *zone,
  1494. gfp_t gfp_mask,
  1495. unsigned long *total_scanned)
  1496. {
  1497. struct mem_cgroup *victim = NULL;
  1498. int total = 0;
  1499. int loop = 0;
  1500. unsigned long excess;
  1501. unsigned long nr_scanned;
  1502. struct mem_cgroup_reclaim_cookie reclaim = {
  1503. .zone = zone,
  1504. .priority = 0,
  1505. };
  1506. excess = soft_limit_excess(root_memcg);
  1507. while (1) {
  1508. victim = mem_cgroup_iter(root_memcg, victim, &reclaim);
  1509. if (!victim) {
  1510. loop++;
  1511. if (loop >= 2) {
  1512. /*
  1513. * If we have not been able to reclaim
  1514. * anything, it might because there are
  1515. * no reclaimable pages under this hierarchy
  1516. */
  1517. if (!total)
  1518. break;
  1519. /*
  1520. * We want to do more targeted reclaim.
  1521. * excess >> 2 is not to excessive so as to
  1522. * reclaim too much, nor too less that we keep
  1523. * coming back to reclaim from this cgroup
  1524. */
  1525. if (total >= (excess >> 2) ||
  1526. (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS))
  1527. break;
  1528. }
  1529. continue;
  1530. }
  1531. total += mem_cgroup_shrink_node_zone(victim, gfp_mask, false,
  1532. zone, &nr_scanned);
  1533. *total_scanned += nr_scanned;
  1534. if (!soft_limit_excess(root_memcg))
  1535. break;
  1536. }
  1537. mem_cgroup_iter_break(root_memcg, victim);
  1538. return total;
  1539. }
  1540. #ifdef CONFIG_LOCKDEP
  1541. static struct lockdep_map memcg_oom_lock_dep_map = {
  1542. .name = "memcg_oom_lock",
  1543. };
  1544. #endif
  1545. static DEFINE_SPINLOCK(memcg_oom_lock);
  1546. /*
  1547. * Check OOM-Killer is already running under our hierarchy.
  1548. * If someone is running, return false.
  1549. */
  1550. static bool mem_cgroup_oom_trylock(struct mem_cgroup *memcg)
  1551. {
  1552. struct mem_cgroup *iter, *failed = NULL;
  1553. spin_lock(&memcg_oom_lock);
  1554. for_each_mem_cgroup_tree(iter, memcg) {
  1555. if (iter->oom_lock) {
  1556. /*
  1557. * this subtree of our hierarchy is already locked
  1558. * so we cannot give a lock.
  1559. */
  1560. failed = iter;
  1561. mem_cgroup_iter_break(memcg, iter);
  1562. break;
  1563. } else
  1564. iter->oom_lock = true;
  1565. }
  1566. if (failed) {
  1567. /*
  1568. * OK, we failed to lock the whole subtree so we have
  1569. * to clean up what we set up to the failing subtree
  1570. */
  1571. for_each_mem_cgroup_tree(iter, memcg) {
  1572. if (iter == failed) {
  1573. mem_cgroup_iter_break(memcg, iter);
  1574. break;
  1575. }
  1576. iter->oom_lock = false;
  1577. }
  1578. } else
  1579. mutex_acquire(&memcg_oom_lock_dep_map, 0, 1, _RET_IP_);
  1580. spin_unlock(&memcg_oom_lock);
  1581. return !failed;
  1582. }
  1583. static void mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
  1584. {
  1585. struct mem_cgroup *iter;
  1586. spin_lock(&memcg_oom_lock);
  1587. mutex_release(&memcg_oom_lock_dep_map, 1, _RET_IP_);
  1588. for_each_mem_cgroup_tree(iter, memcg)
  1589. iter->oom_lock = false;
  1590. spin_unlock(&memcg_oom_lock);
  1591. }
  1592. static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
  1593. {
  1594. struct mem_cgroup *iter;
  1595. for_each_mem_cgroup_tree(iter, memcg)
  1596. atomic_inc(&iter->under_oom);
  1597. }
  1598. static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
  1599. {
  1600. struct mem_cgroup *iter;
  1601. /*
  1602. * When a new child is created while the hierarchy is under oom,
  1603. * mem_cgroup_oom_lock() may not be called. We have to use
  1604. * atomic_add_unless() here.
  1605. */
  1606. for_each_mem_cgroup_tree(iter, memcg)
  1607. atomic_add_unless(&iter->under_oom, -1, 0);
  1608. }
  1609. static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
  1610. struct oom_wait_info {
  1611. struct mem_cgroup *memcg;
  1612. wait_queue_t wait;
  1613. };
  1614. static int memcg_oom_wake_function(wait_queue_t *wait,
  1615. unsigned mode, int sync, void *arg)
  1616. {
  1617. struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg;
  1618. struct mem_cgroup *oom_wait_memcg;
  1619. struct oom_wait_info *oom_wait_info;
  1620. oom_wait_info = container_of(wait, struct oom_wait_info, wait);
  1621. oom_wait_memcg = oom_wait_info->memcg;
  1622. if (!mem_cgroup_is_descendant(wake_memcg, oom_wait_memcg) &&
  1623. !mem_cgroup_is_descendant(oom_wait_memcg, wake_memcg))
  1624. return 0;
  1625. return autoremove_wake_function(wait, mode, sync, arg);
  1626. }
  1627. static void memcg_wakeup_oom(struct mem_cgroup *memcg)
  1628. {
  1629. atomic_inc(&memcg->oom_wakeups);
  1630. /* for filtering, pass "memcg" as argument. */
  1631. __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
  1632. }
  1633. static void memcg_oom_recover(struct mem_cgroup *memcg)
  1634. {
  1635. if (memcg && atomic_read(&memcg->under_oom))
  1636. memcg_wakeup_oom(memcg);
  1637. }
  1638. static void mem_cgroup_oom(struct mem_cgroup *memcg, gfp_t mask, int order)
  1639. {
  1640. if (!current->memcg_oom.may_oom)
  1641. return;
  1642. /*
  1643. * We are in the middle of the charge context here, so we
  1644. * don't want to block when potentially sitting on a callstack
  1645. * that holds all kinds of filesystem and mm locks.
  1646. *
  1647. * Also, the caller may handle a failed allocation gracefully
  1648. * (like optional page cache readahead) and so an OOM killer
  1649. * invocation might not even be necessary.
  1650. *
  1651. * That's why we don't do anything here except remember the
  1652. * OOM context and then deal with it at the end of the page
  1653. * fault when the stack is unwound, the locks are released,
  1654. * and when we know whether the fault was overall successful.
  1655. */
  1656. css_get(&memcg->css);
  1657. current->memcg_oom.memcg = memcg;
  1658. current->memcg_oom.gfp_mask = mask;
  1659. current->memcg_oom.order = order;
  1660. }
  1661. /**
  1662. * mem_cgroup_oom_synchronize - complete memcg OOM handling
  1663. * @handle: actually kill/wait or just clean up the OOM state
  1664. *
  1665. * This has to be called at the end of a page fault if the memcg OOM
  1666. * handler was enabled.
  1667. *
  1668. * Memcg supports userspace OOM handling where failed allocations must
  1669. * sleep on a waitqueue until the userspace task resolves the
  1670. * situation. Sleeping directly in the charge context with all kinds
  1671. * of locks held is not a good idea, instead we remember an OOM state
  1672. * in the task and mem_cgroup_oom_synchronize() has to be called at
  1673. * the end of the page fault to complete the OOM handling.
  1674. *
  1675. * Returns %true if an ongoing memcg OOM situation was detected and
  1676. * completed, %false otherwise.
  1677. */
  1678. bool mem_cgroup_oom_synchronize(bool handle)
  1679. {
  1680. struct mem_cgroup *memcg = current->memcg_oom.memcg;
  1681. struct oom_wait_info owait;
  1682. bool locked;
  1683. /* OOM is global, do not handle */
  1684. if (!memcg)
  1685. return false;
  1686. if (!handle || oom_killer_disabled)
  1687. goto cleanup;
  1688. owait.memcg = memcg;
  1689. owait.wait.flags = 0;
  1690. owait.wait.func = memcg_oom_wake_function;
  1691. owait.wait.private = current;
  1692. INIT_LIST_HEAD(&owait.wait.task_list);
  1693. prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
  1694. mem_cgroup_mark_under_oom(memcg);
  1695. locked = mem_cgroup_oom_trylock(memcg);
  1696. if (locked)
  1697. mem_cgroup_oom_notify(memcg);
  1698. if (locked && !memcg->oom_kill_disable) {
  1699. mem_cgroup_unmark_under_oom(memcg);
  1700. finish_wait(&memcg_oom_waitq, &owait.wait);
  1701. mem_cgroup_out_of_memory(memcg, current->memcg_oom.gfp_mask,
  1702. current->memcg_oom.order);
  1703. } else {
  1704. schedule();
  1705. mem_cgroup_unmark_under_oom(memcg);
  1706. finish_wait(&memcg_oom_waitq, &owait.wait);
  1707. }
  1708. if (locked) {
  1709. mem_cgroup_oom_unlock(memcg);
  1710. /*
  1711. * There is no guarantee that an OOM-lock contender
  1712. * sees the wakeups triggered by the OOM kill
  1713. * uncharges. Wake any sleepers explicitely.
  1714. */
  1715. memcg_oom_recover(memcg);
  1716. }
  1717. cleanup:
  1718. current->memcg_oom.memcg = NULL;
  1719. css_put(&memcg->css);
  1720. return true;
  1721. }
  1722. /**
  1723. * mem_cgroup_begin_page_stat - begin a page state statistics transaction
  1724. * @page: page that is going to change accounted state
  1725. *
  1726. * This function must mark the beginning of an accounted page state
  1727. * change to prevent double accounting when the page is concurrently
  1728. * being moved to another memcg:
  1729. *
  1730. * memcg = mem_cgroup_begin_page_stat(page);
  1731. * if (TestClearPageState(page))
  1732. * mem_cgroup_update_page_stat(memcg, state, -1);
  1733. * mem_cgroup_end_page_stat(memcg);
  1734. */
  1735. struct mem_cgroup *mem_cgroup_begin_page_stat(struct page *page)
  1736. {
  1737. struct mem_cgroup *memcg;
  1738. unsigned long flags;
  1739. /*
  1740. * The RCU lock is held throughout the transaction. The fast
  1741. * path can get away without acquiring the memcg->move_lock
  1742. * because page moving starts with an RCU grace period.
  1743. *
  1744. * The RCU lock also protects the memcg from being freed when
  1745. * the page state that is going to change is the only thing
  1746. * preventing the page from being uncharged.
  1747. * E.g. end-writeback clearing PageWriteback(), which allows
  1748. * migration to go ahead and uncharge the page before the
  1749. * account transaction might be complete.
  1750. */
  1751. rcu_read_lock();
  1752. if (mem_cgroup_disabled())
  1753. return NULL;
  1754. again:
  1755. memcg = page->mem_cgroup;
  1756. if (unlikely(!memcg))
  1757. return NULL;
  1758. if (atomic_read(&memcg->moving_account) <= 0)
  1759. return memcg;
  1760. spin_lock_irqsave(&memcg->move_lock, flags);
  1761. if (memcg != page->mem_cgroup) {
  1762. spin_unlock_irqrestore(&memcg->move_lock, flags);
  1763. goto again;
  1764. }
  1765. /*
  1766. * When charge migration first begins, we can have locked and
  1767. * unlocked page stat updates happening concurrently. Track
  1768. * the task who has the lock for mem_cgroup_end_page_stat().
  1769. */
  1770. memcg->move_lock_task = current;
  1771. memcg->move_lock_flags = flags;
  1772. return memcg;
  1773. }
  1774. /**
  1775. * mem_cgroup_end_page_stat - finish a page state statistics transaction
  1776. * @memcg: the memcg that was accounted against
  1777. */
  1778. void mem_cgroup_end_page_stat(struct mem_cgroup *memcg)
  1779. {
  1780. if (memcg && memcg->move_lock_task == current) {
  1781. unsigned long flags = memcg->move_lock_flags;
  1782. memcg->move_lock_task = NULL;
  1783. memcg->move_lock_flags = 0;
  1784. spin_unlock_irqrestore(&memcg->move_lock, flags);
  1785. }
  1786. rcu_read_unlock();
  1787. }
  1788. /**
  1789. * mem_cgroup_update_page_stat - update page state statistics
  1790. * @memcg: memcg to account against
  1791. * @idx: page state item to account
  1792. * @val: number of pages (positive or negative)
  1793. *
  1794. * See mem_cgroup_begin_page_stat() for locking requirements.
  1795. */
  1796. void mem_cgroup_update_page_stat(struct mem_cgroup *memcg,
  1797. enum mem_cgroup_stat_index idx, int val)
  1798. {
  1799. VM_BUG_ON(!rcu_read_lock_held());
  1800. if (memcg)
  1801. this_cpu_add(memcg->stat->count[idx], val);
  1802. }
  1803. /*
  1804. * size of first charge trial. "32" comes from vmscan.c's magic value.
  1805. * TODO: maybe necessary to use big numbers in big irons.
  1806. */
  1807. #define CHARGE_BATCH 32U
  1808. struct memcg_stock_pcp {
  1809. struct mem_cgroup *cached; /* this never be root cgroup */
  1810. unsigned int nr_pages;
  1811. struct work_struct work;
  1812. unsigned long flags;
  1813. #define FLUSHING_CACHED_CHARGE 0
  1814. };
  1815. static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
  1816. static DEFINE_MUTEX(percpu_charge_mutex);
  1817. /**
  1818. * consume_stock: Try to consume stocked charge on this cpu.
  1819. * @memcg: memcg to consume from.
  1820. * @nr_pages: how many pages to charge.
  1821. *
  1822. * The charges will only happen if @memcg matches the current cpu's memcg
  1823. * stock, and at least @nr_pages are available in that stock. Failure to
  1824. * service an allocation will refill the stock.
  1825. *
  1826. * returns true if successful, false otherwise.
  1827. */
  1828. static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
  1829. {
  1830. struct memcg_stock_pcp *stock;
  1831. bool ret = false;
  1832. if (nr_pages > CHARGE_BATCH)
  1833. return ret;
  1834. stock = &get_cpu_var(memcg_stock);
  1835. if (memcg == stock->cached && stock->nr_pages >= nr_pages) {
  1836. stock->nr_pages -= nr_pages;
  1837. ret = true;
  1838. }
  1839. put_cpu_var(memcg_stock);
  1840. return ret;
  1841. }
  1842. /*
  1843. * Returns stocks cached in percpu and reset cached information.
  1844. */
  1845. static void drain_stock(struct memcg_stock_pcp *stock)
  1846. {
  1847. struct mem_cgroup *old = stock->cached;
  1848. if (stock->nr_pages) {
  1849. page_counter_uncharge(&old->memory, stock->nr_pages);
  1850. if (do_swap_account)
  1851. page_counter_uncharge(&old->memsw, stock->nr_pages);
  1852. css_put_many(&old->css, stock->nr_pages);
  1853. stock->nr_pages = 0;
  1854. }
  1855. stock->cached = NULL;
  1856. }
  1857. /*
  1858. * This must be called under preempt disabled or must be called by
  1859. * a thread which is pinned to local cpu.
  1860. */
  1861. static void drain_local_stock(struct work_struct *dummy)
  1862. {
  1863. struct memcg_stock_pcp *stock = this_cpu_ptr(&memcg_stock);
  1864. drain_stock(stock);
  1865. clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
  1866. }
  1867. /*
  1868. * Cache charges(val) to local per_cpu area.
  1869. * This will be consumed by consume_stock() function, later.
  1870. */
  1871. static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
  1872. {
  1873. struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock);
  1874. if (stock->cached != memcg) { /* reset if necessary */
  1875. drain_stock(stock);
  1876. stock->cached = memcg;
  1877. }
  1878. stock->nr_pages += nr_pages;
  1879. put_cpu_var(memcg_stock);
  1880. }
  1881. /*
  1882. * Drains all per-CPU charge caches for given root_memcg resp. subtree
  1883. * of the hierarchy under it.
  1884. */
  1885. static void drain_all_stock(struct mem_cgroup *root_memcg)
  1886. {
  1887. int cpu, curcpu;
  1888. /* If someone's already draining, avoid adding running more workers. */
  1889. if (!mutex_trylock(&percpu_charge_mutex))
  1890. return;
  1891. /* Notify other cpus that system-wide "drain" is running */
  1892. get_online_cpus();
  1893. curcpu = get_cpu();
  1894. for_each_online_cpu(cpu) {
  1895. struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
  1896. struct mem_cgroup *memcg;
  1897. memcg = stock->cached;
  1898. if (!memcg || !stock->nr_pages)
  1899. continue;
  1900. if (!mem_cgroup_is_descendant(memcg, root_memcg))
  1901. continue;
  1902. if (!test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
  1903. if (cpu == curcpu)
  1904. drain_local_stock(&stock->work);
  1905. else
  1906. schedule_work_on(cpu, &stock->work);
  1907. }
  1908. }
  1909. put_cpu();
  1910. put_online_cpus();
  1911. mutex_unlock(&percpu_charge_mutex);
  1912. }
  1913. /*
  1914. * This function drains percpu counter value from DEAD cpu and
  1915. * move it to local cpu. Note that this function can be preempted.
  1916. */
  1917. static void mem_cgroup_drain_pcp_counter(struct mem_cgroup *memcg, int cpu)
  1918. {
  1919. int i;
  1920. spin_lock(&memcg->pcp_counter_lock);
  1921. for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
  1922. long x = per_cpu(memcg->stat->count[i], cpu);
  1923. per_cpu(memcg->stat->count[i], cpu) = 0;
  1924. memcg->nocpu_base.count[i] += x;
  1925. }
  1926. for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
  1927. unsigned long x = per_cpu(memcg->stat->events[i], cpu);
  1928. per_cpu(memcg->stat->events[i], cpu) = 0;
  1929. memcg->nocpu_base.events[i] += x;
  1930. }
  1931. spin_unlock(&memcg->pcp_counter_lock);
  1932. }
  1933. static int memcg_cpu_hotplug_callback(struct notifier_block *nb,
  1934. unsigned long action,
  1935. void *hcpu)
  1936. {
  1937. int cpu = (unsigned long)hcpu;
  1938. struct memcg_stock_pcp *stock;
  1939. struct mem_cgroup *iter;
  1940. if (action == CPU_ONLINE)
  1941. return NOTIFY_OK;
  1942. if (action != CPU_DEAD && action != CPU_DEAD_FROZEN)
  1943. return NOTIFY_OK;
  1944. for_each_mem_cgroup(iter)
  1945. mem_cgroup_drain_pcp_counter(iter, cpu);
  1946. stock = &per_cpu(memcg_stock, cpu);
  1947. drain_stock(stock);
  1948. return NOTIFY_OK;
  1949. }
  1950. static int try_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
  1951. unsigned int nr_pages)
  1952. {
  1953. unsigned int batch = max(CHARGE_BATCH, nr_pages);
  1954. int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
  1955. struct mem_cgroup *mem_over_limit;
  1956. struct page_counter *counter;
  1957. unsigned long nr_reclaimed;
  1958. bool may_swap = true;
  1959. bool drained = false;
  1960. int ret = 0;
  1961. if (mem_cgroup_is_root(memcg))
  1962. goto done;
  1963. retry:
  1964. if (consume_stock(memcg, nr_pages))
  1965. goto done;
  1966. if (!do_swap_account ||
  1967. !page_counter_try_charge(&memcg->memsw, batch, &counter)) {
  1968. if (!page_counter_try_charge(&memcg->memory, batch, &counter))
  1969. goto done_restock;
  1970. if (do_swap_account)
  1971. page_counter_uncharge(&memcg->memsw, batch);
  1972. mem_over_limit = mem_cgroup_from_counter(counter, memory);
  1973. } else {
  1974. mem_over_limit = mem_cgroup_from_counter(counter, memsw);
  1975. may_swap = false;
  1976. }
  1977. if (batch > nr_pages) {
  1978. batch = nr_pages;
  1979. goto retry;
  1980. }
  1981. /*
  1982. * Unlike in global OOM situations, memcg is not in a physical
  1983. * memory shortage. Allow dying and OOM-killed tasks to
  1984. * bypass the last charges so that they can exit quickly and
  1985. * free their memory.
  1986. */
  1987. if (unlikely(test_thread_flag(TIF_MEMDIE) ||
  1988. fatal_signal_pending(current) ||
  1989. current->flags & PF_EXITING))
  1990. goto bypass;
  1991. if (unlikely(task_in_memcg_oom(current)))
  1992. goto nomem;
  1993. if (!(gfp_mask & __GFP_WAIT))
  1994. goto nomem;
  1995. mem_cgroup_events(mem_over_limit, MEMCG_MAX, 1);
  1996. nr_reclaimed = try_to_free_mem_cgroup_pages(mem_over_limit, nr_pages,
  1997. gfp_mask, may_swap);
  1998. if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
  1999. goto retry;
  2000. if (!drained) {
  2001. drain_all_stock(mem_over_limit);
  2002. drained = true;
  2003. goto retry;
  2004. }
  2005. if (gfp_mask & __GFP_NORETRY)
  2006. goto nomem;
  2007. /*
  2008. * Even though the limit is exceeded at this point, reclaim
  2009. * may have been able to free some pages. Retry the charge
  2010. * before killing the task.
  2011. *
  2012. * Only for regular pages, though: huge pages are rather
  2013. * unlikely to succeed so close to the limit, and we fall back
  2014. * to regular pages anyway in case of failure.
  2015. */
  2016. if (nr_reclaimed && nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER))
  2017. goto retry;
  2018. /*
  2019. * At task move, charge accounts can be doubly counted. So, it's
  2020. * better to wait until the end of task_move if something is going on.
  2021. */
  2022. if (mem_cgroup_wait_acct_move(mem_over_limit))
  2023. goto retry;
  2024. if (nr_retries--)
  2025. goto retry;
  2026. if (gfp_mask & __GFP_NOFAIL)
  2027. goto bypass;
  2028. if (fatal_signal_pending(current))
  2029. goto bypass;
  2030. mem_cgroup_events(mem_over_limit, MEMCG_OOM, 1);
  2031. mem_cgroup_oom(mem_over_limit, gfp_mask, get_order(nr_pages));
  2032. nomem:
  2033. if (!(gfp_mask & __GFP_NOFAIL))
  2034. return -ENOMEM;
  2035. bypass:
  2036. return -EINTR;
  2037. done_restock:
  2038. css_get_many(&memcg->css, batch);
  2039. if (batch > nr_pages)
  2040. refill_stock(memcg, batch - nr_pages);
  2041. /*
  2042. * If the hierarchy is above the normal consumption range,
  2043. * make the charging task trim their excess contribution.
  2044. */
  2045. do {
  2046. if (page_counter_read(&memcg->memory) <= memcg->high)
  2047. continue;
  2048. mem_cgroup_events(memcg, MEMCG_HIGH, 1);
  2049. try_to_free_mem_cgroup_pages(memcg, nr_pages, gfp_mask, true);
  2050. } while ((memcg = parent_mem_cgroup(memcg)));
  2051. done:
  2052. return ret;
  2053. }
  2054. static void cancel_charge(struct mem_cgroup *memcg, unsigned int nr_pages)
  2055. {
  2056. if (mem_cgroup_is_root(memcg))
  2057. return;
  2058. page_counter_uncharge(&memcg->memory, nr_pages);
  2059. if (do_swap_account)
  2060. page_counter_uncharge(&memcg->memsw, nr_pages);
  2061. css_put_many(&memcg->css, nr_pages);
  2062. }
  2063. /*
  2064. * A helper function to get mem_cgroup from ID. must be called under
  2065. * rcu_read_lock(). The caller is responsible for calling
  2066. * css_tryget_online() if the mem_cgroup is used for charging. (dropping
  2067. * refcnt from swap can be called against removed memcg.)
  2068. */
  2069. static struct mem_cgroup *mem_cgroup_lookup(unsigned short id)
  2070. {
  2071. /* ID 0 is unused ID */
  2072. if (!id)
  2073. return NULL;
  2074. return mem_cgroup_from_id(id);
  2075. }
  2076. /*
  2077. * try_get_mem_cgroup_from_page - look up page's memcg association
  2078. * @page: the page
  2079. *
  2080. * Look up, get a css reference, and return the memcg that owns @page.
  2081. *
  2082. * The page must be locked to prevent racing with swap-in and page
  2083. * cache charges. If coming from an unlocked page table, the caller
  2084. * must ensure the page is on the LRU or this can race with charging.
  2085. */
  2086. struct mem_cgroup *try_get_mem_cgroup_from_page(struct page *page)
  2087. {
  2088. struct mem_cgroup *memcg;
  2089. unsigned short id;
  2090. swp_entry_t ent;
  2091. VM_BUG_ON_PAGE(!PageLocked(page), page);
  2092. memcg = page->mem_cgroup;
  2093. if (memcg) {
  2094. if (!css_tryget_online(&memcg->css))
  2095. memcg = NULL;
  2096. } else if (PageSwapCache(page)) {
  2097. ent.val = page_private(page);
  2098. id = lookup_swap_cgroup_id(ent);
  2099. rcu_read_lock();
  2100. memcg = mem_cgroup_lookup(id);
  2101. if (memcg && !css_tryget_online(&memcg->css))
  2102. memcg = NULL;
  2103. rcu_read_unlock();
  2104. }
  2105. return memcg;
  2106. }
  2107. static void lock_page_lru(struct page *page, int *isolated)
  2108. {
  2109. struct zone *zone = page_zone(page);
  2110. spin_lock_irq(&zone->lru_lock);
  2111. if (PageLRU(page)) {
  2112. struct lruvec *lruvec;
  2113. lruvec = mem_cgroup_page_lruvec(page, zone);
  2114. ClearPageLRU(page);
  2115. del_page_from_lru_list(page, lruvec, page_lru(page));
  2116. *isolated = 1;
  2117. } else
  2118. *isolated = 0;
  2119. }
  2120. static void unlock_page_lru(struct page *page, int isolated)
  2121. {
  2122. struct zone *zone = page_zone(page);
  2123. if (isolated) {
  2124. struct lruvec *lruvec;
  2125. lruvec = mem_cgroup_page_lruvec(page, zone);
  2126. VM_BUG_ON_PAGE(PageLRU(page), page);
  2127. SetPageLRU(page);
  2128. add_page_to_lru_list(page, lruvec, page_lru(page));
  2129. }
  2130. spin_unlock_irq(&zone->lru_lock);
  2131. }
  2132. static void commit_charge(struct page *page, struct mem_cgroup *memcg,
  2133. bool lrucare)
  2134. {
  2135. int isolated;
  2136. VM_BUG_ON_PAGE(page->mem_cgroup, page);
  2137. /*
  2138. * In some cases, SwapCache and FUSE(splice_buf->radixtree), the page
  2139. * may already be on some other mem_cgroup's LRU. Take care of it.
  2140. */
  2141. if (lrucare)
  2142. lock_page_lru(page, &isolated);
  2143. /*
  2144. * Nobody should be changing or seriously looking at
  2145. * page->mem_cgroup at this point:
  2146. *
  2147. * - the page is uncharged
  2148. *
  2149. * - the page is off-LRU
  2150. *
  2151. * - an anonymous fault has exclusive page access, except for
  2152. * a locked page table
  2153. *
  2154. * - a page cache insertion, a swapin fault, or a migration
  2155. * have the page locked
  2156. */
  2157. page->mem_cgroup = memcg;
  2158. if (lrucare)
  2159. unlock_page_lru(page, isolated);
  2160. }
  2161. #ifdef CONFIG_MEMCG_KMEM
  2162. int memcg_charge_kmem(struct mem_cgroup *memcg, gfp_t gfp,
  2163. unsigned long nr_pages)
  2164. {
  2165. struct page_counter *counter;
  2166. int ret = 0;
  2167. ret = page_counter_try_charge(&memcg->kmem, nr_pages, &counter);
  2168. if (ret < 0)
  2169. return ret;
  2170. ret = try_charge(memcg, gfp, nr_pages);
  2171. if (ret == -EINTR) {
  2172. /*
  2173. * try_charge() chose to bypass to root due to OOM kill or
  2174. * fatal signal. Since our only options are to either fail
  2175. * the allocation or charge it to this cgroup, do it as a
  2176. * temporary condition. But we can't fail. From a kmem/slab
  2177. * perspective, the cache has already been selected, by
  2178. * mem_cgroup_kmem_get_cache(), so it is too late to change
  2179. * our minds.
  2180. *
  2181. * This condition will only trigger if the task entered
  2182. * memcg_charge_kmem in a sane state, but was OOM-killed
  2183. * during try_charge() above. Tasks that were already dying
  2184. * when the allocation triggers should have been already
  2185. * directed to the root cgroup in memcontrol.h
  2186. */
  2187. page_counter_charge(&memcg->memory, nr_pages);
  2188. if (do_swap_account)
  2189. page_counter_charge(&memcg->memsw, nr_pages);
  2190. css_get_many(&memcg->css, nr_pages);
  2191. ret = 0;
  2192. } else if (ret)
  2193. page_counter_uncharge(&memcg->kmem, nr_pages);
  2194. return ret;
  2195. }
  2196. void memcg_uncharge_kmem(struct mem_cgroup *memcg, unsigned long nr_pages)
  2197. {
  2198. page_counter_uncharge(&memcg->memory, nr_pages);
  2199. if (do_swap_account)
  2200. page_counter_uncharge(&memcg->memsw, nr_pages);
  2201. page_counter_uncharge(&memcg->kmem, nr_pages);
  2202. css_put_many(&memcg->css, nr_pages);
  2203. }
  2204. /*
  2205. * helper for acessing a memcg's index. It will be used as an index in the
  2206. * child cache array in kmem_cache, and also to derive its name. This function
  2207. * will return -1 when this is not a kmem-limited memcg.
  2208. */
  2209. int memcg_cache_id(struct mem_cgroup *memcg)
  2210. {
  2211. return memcg ? memcg->kmemcg_id : -1;
  2212. }
  2213. static int memcg_alloc_cache_id(void)
  2214. {
  2215. int id, size;
  2216. int err;
  2217. id = ida_simple_get(&memcg_cache_ida,
  2218. 0, MEMCG_CACHES_MAX_SIZE, GFP_KERNEL);
  2219. if (id < 0)
  2220. return id;
  2221. if (id < memcg_nr_cache_ids)
  2222. return id;
  2223. /*
  2224. * There's no space for the new id in memcg_caches arrays,
  2225. * so we have to grow them.
  2226. */
  2227. down_write(&memcg_cache_ids_sem);
  2228. size = 2 * (id + 1);
  2229. if (size < MEMCG_CACHES_MIN_SIZE)
  2230. size = MEMCG_CACHES_MIN_SIZE;
  2231. else if (size > MEMCG_CACHES_MAX_SIZE)
  2232. size = MEMCG_CACHES_MAX_SIZE;
  2233. err = memcg_update_all_caches(size);
  2234. if (!err)
  2235. err = memcg_update_all_list_lrus(size);
  2236. if (!err)
  2237. memcg_nr_cache_ids = size;
  2238. up_write(&memcg_cache_ids_sem);
  2239. if (err) {
  2240. ida_simple_remove(&memcg_cache_ida, id);
  2241. return err;
  2242. }
  2243. return id;
  2244. }
  2245. static void memcg_free_cache_id(int id)
  2246. {
  2247. ida_simple_remove(&memcg_cache_ida, id);
  2248. }
  2249. struct memcg_kmem_cache_create_work {
  2250. struct mem_cgroup *memcg;
  2251. struct kmem_cache *cachep;
  2252. struct work_struct work;
  2253. };
  2254. static void memcg_kmem_cache_create_func(struct work_struct *w)
  2255. {
  2256. struct memcg_kmem_cache_create_work *cw =
  2257. container_of(w, struct memcg_kmem_cache_create_work, work);
  2258. struct mem_cgroup *memcg = cw->memcg;
  2259. struct kmem_cache *cachep = cw->cachep;
  2260. memcg_create_kmem_cache(memcg, cachep);
  2261. css_put(&memcg->css);
  2262. kfree(cw);
  2263. }
  2264. /*
  2265. * Enqueue the creation of a per-memcg kmem_cache.
  2266. */
  2267. static void __memcg_schedule_kmem_cache_create(struct mem_cgroup *memcg,
  2268. struct kmem_cache *cachep)
  2269. {
  2270. struct memcg_kmem_cache_create_work *cw;
  2271. cw = kmalloc(sizeof(*cw), GFP_NOWAIT);
  2272. if (!cw)
  2273. return;
  2274. css_get(&memcg->css);
  2275. cw->memcg = memcg;
  2276. cw->cachep = cachep;
  2277. INIT_WORK(&cw->work, memcg_kmem_cache_create_func);
  2278. schedule_work(&cw->work);
  2279. }
  2280. static void memcg_schedule_kmem_cache_create(struct mem_cgroup *memcg,
  2281. struct kmem_cache *cachep)
  2282. {
  2283. /*
  2284. * We need to stop accounting when we kmalloc, because if the
  2285. * corresponding kmalloc cache is not yet created, the first allocation
  2286. * in __memcg_schedule_kmem_cache_create will recurse.
  2287. *
  2288. * However, it is better to enclose the whole function. Depending on
  2289. * the debugging options enabled, INIT_WORK(), for instance, can
  2290. * trigger an allocation. This too, will make us recurse. Because at
  2291. * this point we can't allow ourselves back into memcg_kmem_get_cache,
  2292. * the safest choice is to do it like this, wrapping the whole function.
  2293. */
  2294. current->memcg_kmem_skip_account = 1;
  2295. __memcg_schedule_kmem_cache_create(memcg, cachep);
  2296. current->memcg_kmem_skip_account = 0;
  2297. }
  2298. /*
  2299. * Return the kmem_cache we're supposed to use for a slab allocation.
  2300. * We try to use the current memcg's version of the cache.
  2301. *
  2302. * If the cache does not exist yet, if we are the first user of it,
  2303. * we either create it immediately, if possible, or create it asynchronously
  2304. * in a workqueue.
  2305. * In the latter case, we will let the current allocation go through with
  2306. * the original cache.
  2307. *
  2308. * Can't be called in interrupt context or from kernel threads.
  2309. * This function needs to be called with rcu_read_lock() held.
  2310. */
  2311. struct kmem_cache *__memcg_kmem_get_cache(struct kmem_cache *cachep)
  2312. {
  2313. struct mem_cgroup *memcg;
  2314. struct kmem_cache *memcg_cachep;
  2315. VM_BUG_ON(!is_root_cache(cachep));
  2316. if (current->memcg_kmem_skip_account)
  2317. return cachep;
  2318. memcg = get_mem_cgroup_from_mm(current->mm);
  2319. if (!memcg_kmem_is_active(memcg))
  2320. goto out;
  2321. memcg_cachep = cache_from_memcg_idx(cachep, memcg_cache_id(memcg));
  2322. if (likely(memcg_cachep))
  2323. return memcg_cachep;
  2324. /*
  2325. * If we are in a safe context (can wait, and not in interrupt
  2326. * context), we could be be predictable and return right away.
  2327. * This would guarantee that the allocation being performed
  2328. * already belongs in the new cache.
  2329. *
  2330. * However, there are some clashes that can arrive from locking.
  2331. * For instance, because we acquire the slab_mutex while doing
  2332. * memcg_create_kmem_cache, this means no further allocation
  2333. * could happen with the slab_mutex held. So it's better to
  2334. * defer everything.
  2335. */
  2336. memcg_schedule_kmem_cache_create(memcg, cachep);
  2337. out:
  2338. css_put(&memcg->css);
  2339. return cachep;
  2340. }
  2341. void __memcg_kmem_put_cache(struct kmem_cache *cachep)
  2342. {
  2343. if (!is_root_cache(cachep))
  2344. css_put(&cachep->memcg_params.memcg->css);
  2345. }
  2346. /*
  2347. * We need to verify if the allocation against current->mm->owner's memcg is
  2348. * possible for the given order. But the page is not allocated yet, so we'll
  2349. * need a further commit step to do the final arrangements.
  2350. *
  2351. * It is possible for the task to switch cgroups in this mean time, so at
  2352. * commit time, we can't rely on task conversion any longer. We'll then use
  2353. * the handle argument to return to the caller which cgroup we should commit
  2354. * against. We could also return the memcg directly and avoid the pointer
  2355. * passing, but a boolean return value gives better semantics considering
  2356. * the compiled-out case as well.
  2357. *
  2358. * Returning true means the allocation is possible.
  2359. */
  2360. bool
  2361. __memcg_kmem_newpage_charge(gfp_t gfp, struct mem_cgroup **_memcg, int order)
  2362. {
  2363. struct mem_cgroup *memcg;
  2364. int ret;
  2365. *_memcg = NULL;
  2366. memcg = get_mem_cgroup_from_mm(current->mm);
  2367. if (!memcg_kmem_is_active(memcg)) {
  2368. css_put(&memcg->css);
  2369. return true;
  2370. }
  2371. ret = memcg_charge_kmem(memcg, gfp, 1 << order);
  2372. if (!ret)
  2373. *_memcg = memcg;
  2374. css_put(&memcg->css);
  2375. return (ret == 0);
  2376. }
  2377. void __memcg_kmem_commit_charge(struct page *page, struct mem_cgroup *memcg,
  2378. int order)
  2379. {
  2380. VM_BUG_ON(mem_cgroup_is_root(memcg));
  2381. /* The page allocation failed. Revert */
  2382. if (!page) {
  2383. memcg_uncharge_kmem(memcg, 1 << order);
  2384. return;
  2385. }
  2386. page->mem_cgroup = memcg;
  2387. }
  2388. void __memcg_kmem_uncharge_pages(struct page *page, int order)
  2389. {
  2390. struct mem_cgroup *memcg = page->mem_cgroup;
  2391. if (!memcg)
  2392. return;
  2393. VM_BUG_ON_PAGE(mem_cgroup_is_root(memcg), page);
  2394. memcg_uncharge_kmem(memcg, 1 << order);
  2395. page->mem_cgroup = NULL;
  2396. }
  2397. struct mem_cgroup *__mem_cgroup_from_kmem(void *ptr)
  2398. {
  2399. struct mem_cgroup *memcg = NULL;
  2400. struct kmem_cache *cachep;
  2401. struct page *page;
  2402. page = virt_to_head_page(ptr);
  2403. if (PageSlab(page)) {
  2404. cachep = page->slab_cache;
  2405. if (!is_root_cache(cachep))
  2406. memcg = cachep->memcg_params.memcg;
  2407. } else
  2408. /* page allocated by alloc_kmem_pages */
  2409. memcg = page->mem_cgroup;
  2410. return memcg;
  2411. }
  2412. #endif /* CONFIG_MEMCG_KMEM */
  2413. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  2414. /*
  2415. * Because tail pages are not marked as "used", set it. We're under
  2416. * zone->lru_lock, 'splitting on pmd' and compound_lock.
  2417. * charge/uncharge will be never happen and move_account() is done under
  2418. * compound_lock(), so we don't have to take care of races.
  2419. */
  2420. void mem_cgroup_split_huge_fixup(struct page *head)
  2421. {
  2422. int i;
  2423. if (mem_cgroup_disabled())
  2424. return;
  2425. for (i = 1; i < HPAGE_PMD_NR; i++)
  2426. head[i].mem_cgroup = head->mem_cgroup;
  2427. __this_cpu_sub(head->mem_cgroup->stat->count[MEM_CGROUP_STAT_RSS_HUGE],
  2428. HPAGE_PMD_NR);
  2429. }
  2430. #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
  2431. /**
  2432. * mem_cgroup_move_account - move account of the page
  2433. * @page: the page
  2434. * @nr_pages: number of regular pages (>1 for huge pages)
  2435. * @from: mem_cgroup which the page is moved from.
  2436. * @to: mem_cgroup which the page is moved to. @from != @to.
  2437. *
  2438. * The caller must confirm following.
  2439. * - page is not on LRU (isolate_page() is useful.)
  2440. * - compound_lock is held when nr_pages > 1
  2441. *
  2442. * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
  2443. * from old cgroup.
  2444. */
  2445. static int mem_cgroup_move_account(struct page *page,
  2446. unsigned int nr_pages,
  2447. struct mem_cgroup *from,
  2448. struct mem_cgroup *to)
  2449. {
  2450. unsigned long flags;
  2451. int ret;
  2452. VM_BUG_ON(from == to);
  2453. VM_BUG_ON_PAGE(PageLRU(page), page);
  2454. /*
  2455. * The page is isolated from LRU. So, collapse function
  2456. * will not handle this page. But page splitting can happen.
  2457. * Do this check under compound_page_lock(). The caller should
  2458. * hold it.
  2459. */
  2460. ret = -EBUSY;
  2461. if (nr_pages > 1 && !PageTransHuge(page))
  2462. goto out;
  2463. /*
  2464. * Prevent mem_cgroup_migrate() from looking at page->mem_cgroup
  2465. * of its source page while we change it: page migration takes
  2466. * both pages off the LRU, but page cache replacement doesn't.
  2467. */
  2468. if (!trylock_page(page))
  2469. goto out;
  2470. ret = -EINVAL;
  2471. if (page->mem_cgroup != from)
  2472. goto out_unlock;
  2473. spin_lock_irqsave(&from->move_lock, flags);
  2474. if (!PageAnon(page) && page_mapped(page)) {
  2475. __this_cpu_sub(from->stat->count[MEM_CGROUP_STAT_FILE_MAPPED],
  2476. nr_pages);
  2477. __this_cpu_add(to->stat->count[MEM_CGROUP_STAT_FILE_MAPPED],
  2478. nr_pages);
  2479. }
  2480. if (PageWriteback(page)) {
  2481. __this_cpu_sub(from->stat->count[MEM_CGROUP_STAT_WRITEBACK],
  2482. nr_pages);
  2483. __this_cpu_add(to->stat->count[MEM_CGROUP_STAT_WRITEBACK],
  2484. nr_pages);
  2485. }
  2486. /*
  2487. * It is safe to change page->mem_cgroup here because the page
  2488. * is referenced, charged, and isolated - we can't race with
  2489. * uncharging, charging, migration, or LRU putback.
  2490. */
  2491. /* caller should have done css_get */
  2492. page->mem_cgroup = to;
  2493. spin_unlock_irqrestore(&from->move_lock, flags);
  2494. ret = 0;
  2495. local_irq_disable();
  2496. mem_cgroup_charge_statistics(to, page, nr_pages);
  2497. memcg_check_events(to, page);
  2498. mem_cgroup_charge_statistics(from, page, -nr_pages);
  2499. memcg_check_events(from, page);
  2500. local_irq_enable();
  2501. out_unlock:
  2502. unlock_page(page);
  2503. out:
  2504. return ret;
  2505. }
  2506. #ifdef CONFIG_MEMCG_SWAP
  2507. static void mem_cgroup_swap_statistics(struct mem_cgroup *memcg,
  2508. bool charge)
  2509. {
  2510. int val = (charge) ? 1 : -1;
  2511. this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_SWAP], val);
  2512. }
  2513. /**
  2514. * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
  2515. * @entry: swap entry to be moved
  2516. * @from: mem_cgroup which the entry is moved from
  2517. * @to: mem_cgroup which the entry is moved to
  2518. *
  2519. * It succeeds only when the swap_cgroup's record for this entry is the same
  2520. * as the mem_cgroup's id of @from.
  2521. *
  2522. * Returns 0 on success, -EINVAL on failure.
  2523. *
  2524. * The caller must have charged to @to, IOW, called page_counter_charge() about
  2525. * both res and memsw, and called css_get().
  2526. */
  2527. static int mem_cgroup_move_swap_account(swp_entry_t entry,
  2528. struct mem_cgroup *from, struct mem_cgroup *to)
  2529. {
  2530. unsigned short old_id, new_id;
  2531. old_id = mem_cgroup_id(from);
  2532. new_id = mem_cgroup_id(to);
  2533. if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
  2534. mem_cgroup_swap_statistics(from, false);
  2535. mem_cgroup_swap_statistics(to, true);
  2536. return 0;
  2537. }
  2538. return -EINVAL;
  2539. }
  2540. #else
  2541. static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
  2542. struct mem_cgroup *from, struct mem_cgroup *to)
  2543. {
  2544. return -EINVAL;
  2545. }
  2546. #endif
  2547. static DEFINE_MUTEX(memcg_limit_mutex);
  2548. static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
  2549. unsigned long limit)
  2550. {
  2551. unsigned long curusage;
  2552. unsigned long oldusage;
  2553. bool enlarge = false;
  2554. int retry_count;
  2555. int ret;
  2556. /*
  2557. * For keeping hierarchical_reclaim simple, how long we should retry
  2558. * is depends on callers. We set our retry-count to be function
  2559. * of # of children which we should visit in this loop.
  2560. */
  2561. retry_count = MEM_CGROUP_RECLAIM_RETRIES *
  2562. mem_cgroup_count_children(memcg);
  2563. oldusage = page_counter_read(&memcg->memory);
  2564. do {
  2565. if (signal_pending(current)) {
  2566. ret = -EINTR;
  2567. break;
  2568. }
  2569. mutex_lock(&memcg_limit_mutex);
  2570. if (limit > memcg->memsw.limit) {
  2571. mutex_unlock(&memcg_limit_mutex);
  2572. ret = -EINVAL;
  2573. break;
  2574. }
  2575. if (limit > memcg->memory.limit)
  2576. enlarge = true;
  2577. ret = page_counter_limit(&memcg->memory, limit);
  2578. mutex_unlock(&memcg_limit_mutex);
  2579. if (!ret)
  2580. break;
  2581. try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL, true);
  2582. curusage = page_counter_read(&memcg->memory);
  2583. /* Usage is reduced ? */
  2584. if (curusage >= oldusage)
  2585. retry_count--;
  2586. else
  2587. oldusage = curusage;
  2588. } while (retry_count);
  2589. if (!ret && enlarge)
  2590. memcg_oom_recover(memcg);
  2591. return ret;
  2592. }
  2593. static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
  2594. unsigned long limit)
  2595. {
  2596. unsigned long curusage;
  2597. unsigned long oldusage;
  2598. bool enlarge = false;
  2599. int retry_count;
  2600. int ret;
  2601. /* see mem_cgroup_resize_res_limit */
  2602. retry_count = MEM_CGROUP_RECLAIM_RETRIES *
  2603. mem_cgroup_count_children(memcg);
  2604. oldusage = page_counter_read(&memcg->memsw);
  2605. do {
  2606. if (signal_pending(current)) {
  2607. ret = -EINTR;
  2608. break;
  2609. }
  2610. mutex_lock(&memcg_limit_mutex);
  2611. if (limit < memcg->memory.limit) {
  2612. mutex_unlock(&memcg_limit_mutex);
  2613. ret = -EINVAL;
  2614. break;
  2615. }
  2616. if (limit > memcg->memsw.limit)
  2617. enlarge = true;
  2618. ret = page_counter_limit(&memcg->memsw, limit);
  2619. mutex_unlock(&memcg_limit_mutex);
  2620. if (!ret)
  2621. break;
  2622. try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL, false);
  2623. curusage = page_counter_read(&memcg->memsw);
  2624. /* Usage is reduced ? */
  2625. if (curusage >= oldusage)
  2626. retry_count--;
  2627. else
  2628. oldusage = curusage;
  2629. } while (retry_count);
  2630. if (!ret && enlarge)
  2631. memcg_oom_recover(memcg);
  2632. return ret;
  2633. }
  2634. unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
  2635. gfp_t gfp_mask,
  2636. unsigned long *total_scanned)
  2637. {
  2638. unsigned long nr_reclaimed = 0;
  2639. struct mem_cgroup_per_zone *mz, *next_mz = NULL;
  2640. unsigned long reclaimed;
  2641. int loop = 0;
  2642. struct mem_cgroup_tree_per_zone *mctz;
  2643. unsigned long excess;
  2644. unsigned long nr_scanned;
  2645. if (order > 0)
  2646. return 0;
  2647. mctz = soft_limit_tree_node_zone(zone_to_nid(zone), zone_idx(zone));
  2648. /*
  2649. * This loop can run a while, specially if mem_cgroup's continuously
  2650. * keep exceeding their soft limit and putting the system under
  2651. * pressure
  2652. */
  2653. do {
  2654. if (next_mz)
  2655. mz = next_mz;
  2656. else
  2657. mz = mem_cgroup_largest_soft_limit_node(mctz);
  2658. if (!mz)
  2659. break;
  2660. nr_scanned = 0;
  2661. reclaimed = mem_cgroup_soft_reclaim(mz->memcg, zone,
  2662. gfp_mask, &nr_scanned);
  2663. nr_reclaimed += reclaimed;
  2664. *total_scanned += nr_scanned;
  2665. spin_lock_irq(&mctz->lock);
  2666. __mem_cgroup_remove_exceeded(mz, mctz);
  2667. /*
  2668. * If we failed to reclaim anything from this memory cgroup
  2669. * it is time to move on to the next cgroup
  2670. */
  2671. next_mz = NULL;
  2672. if (!reclaimed)
  2673. next_mz = __mem_cgroup_largest_soft_limit_node(mctz);
  2674. excess = soft_limit_excess(mz->memcg);
  2675. /*
  2676. * One school of thought says that we should not add
  2677. * back the node to the tree if reclaim returns 0.
  2678. * But our reclaim could return 0, simply because due
  2679. * to priority we are exposing a smaller subset of
  2680. * memory to reclaim from. Consider this as a longer
  2681. * term TODO.
  2682. */
  2683. /* If excess == 0, no tree ops */
  2684. __mem_cgroup_insert_exceeded(mz, mctz, excess);
  2685. spin_unlock_irq(&mctz->lock);
  2686. css_put(&mz->memcg->css);
  2687. loop++;
  2688. /*
  2689. * Could not reclaim anything and there are no more
  2690. * mem cgroups to try or we seem to be looping without
  2691. * reclaiming anything.
  2692. */
  2693. if (!nr_reclaimed &&
  2694. (next_mz == NULL ||
  2695. loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
  2696. break;
  2697. } while (!nr_reclaimed);
  2698. if (next_mz)
  2699. css_put(&next_mz->memcg->css);
  2700. return nr_reclaimed;
  2701. }
  2702. /*
  2703. * Test whether @memcg has children, dead or alive. Note that this
  2704. * function doesn't care whether @memcg has use_hierarchy enabled and
  2705. * returns %true if there are child csses according to the cgroup
  2706. * hierarchy. Testing use_hierarchy is the caller's responsiblity.
  2707. */
  2708. static inline bool memcg_has_children(struct mem_cgroup *memcg)
  2709. {
  2710. bool ret;
  2711. /*
  2712. * The lock does not prevent addition or deletion of children, but
  2713. * it prevents a new child from being initialized based on this
  2714. * parent in css_online(), so it's enough to decide whether
  2715. * hierarchically inherited attributes can still be changed or not.
  2716. */
  2717. lockdep_assert_held(&memcg_create_mutex);
  2718. rcu_read_lock();
  2719. ret = css_next_child(NULL, &memcg->css);
  2720. rcu_read_unlock();
  2721. return ret;
  2722. }
  2723. /*
  2724. * Reclaims as many pages from the given memcg as possible and moves
  2725. * the rest to the parent.
  2726. *
  2727. * Caller is responsible for holding css reference for memcg.
  2728. */
  2729. static int mem_cgroup_force_empty(struct mem_cgroup *memcg)
  2730. {
  2731. int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
  2732. /* we call try-to-free pages for make this cgroup empty */
  2733. lru_add_drain_all();
  2734. /* try to free all pages in this cgroup */
  2735. while (nr_retries && page_counter_read(&memcg->memory)) {
  2736. int progress;
  2737. if (signal_pending(current))
  2738. return -EINTR;
  2739. progress = try_to_free_mem_cgroup_pages(memcg, 1,
  2740. GFP_KERNEL, true);
  2741. if (!progress) {
  2742. nr_retries--;
  2743. /* maybe some writeback is necessary */
  2744. congestion_wait(BLK_RW_ASYNC, HZ/10);
  2745. }
  2746. }
  2747. return 0;
  2748. }
  2749. static ssize_t mem_cgroup_force_empty_write(struct kernfs_open_file *of,
  2750. char *buf, size_t nbytes,
  2751. loff_t off)
  2752. {
  2753. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  2754. if (mem_cgroup_is_root(memcg))
  2755. return -EINVAL;
  2756. return mem_cgroup_force_empty(memcg) ?: nbytes;
  2757. }
  2758. static u64 mem_cgroup_hierarchy_read(struct cgroup_subsys_state *css,
  2759. struct cftype *cft)
  2760. {
  2761. return mem_cgroup_from_css(css)->use_hierarchy;
  2762. }
  2763. static int mem_cgroup_hierarchy_write(struct cgroup_subsys_state *css,
  2764. struct cftype *cft, u64 val)
  2765. {
  2766. int retval = 0;
  2767. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  2768. struct mem_cgroup *parent_memcg = mem_cgroup_from_css(memcg->css.parent);
  2769. mutex_lock(&memcg_create_mutex);
  2770. if (memcg->use_hierarchy == val)
  2771. goto out;
  2772. /*
  2773. * If parent's use_hierarchy is set, we can't make any modifications
  2774. * in the child subtrees. If it is unset, then the change can
  2775. * occur, provided the current cgroup has no children.
  2776. *
  2777. * For the root cgroup, parent_mem is NULL, we allow value to be
  2778. * set if there are no children.
  2779. */
  2780. if ((!parent_memcg || !parent_memcg->use_hierarchy) &&
  2781. (val == 1 || val == 0)) {
  2782. if (!memcg_has_children(memcg))
  2783. memcg->use_hierarchy = val;
  2784. else
  2785. retval = -EBUSY;
  2786. } else
  2787. retval = -EINVAL;
  2788. out:
  2789. mutex_unlock(&memcg_create_mutex);
  2790. return retval;
  2791. }
  2792. static unsigned long tree_stat(struct mem_cgroup *memcg,
  2793. enum mem_cgroup_stat_index idx)
  2794. {
  2795. struct mem_cgroup *iter;
  2796. long val = 0;
  2797. /* Per-cpu values can be negative, use a signed accumulator */
  2798. for_each_mem_cgroup_tree(iter, memcg)
  2799. val += mem_cgroup_read_stat(iter, idx);
  2800. if (val < 0) /* race ? */
  2801. val = 0;
  2802. return val;
  2803. }
  2804. static inline u64 mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
  2805. {
  2806. u64 val;
  2807. if (mem_cgroup_is_root(memcg)) {
  2808. val = tree_stat(memcg, MEM_CGROUP_STAT_CACHE);
  2809. val += tree_stat(memcg, MEM_CGROUP_STAT_RSS);
  2810. if (swap)
  2811. val += tree_stat(memcg, MEM_CGROUP_STAT_SWAP);
  2812. } else {
  2813. if (!swap)
  2814. val = page_counter_read(&memcg->memory);
  2815. else
  2816. val = page_counter_read(&memcg->memsw);
  2817. }
  2818. return val << PAGE_SHIFT;
  2819. }
  2820. enum {
  2821. RES_USAGE,
  2822. RES_LIMIT,
  2823. RES_MAX_USAGE,
  2824. RES_FAILCNT,
  2825. RES_SOFT_LIMIT,
  2826. };
  2827. static u64 mem_cgroup_read_u64(struct cgroup_subsys_state *css,
  2828. struct cftype *cft)
  2829. {
  2830. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  2831. struct page_counter *counter;
  2832. switch (MEMFILE_TYPE(cft->private)) {
  2833. case _MEM:
  2834. counter = &memcg->memory;
  2835. break;
  2836. case _MEMSWAP:
  2837. counter = &memcg->memsw;
  2838. break;
  2839. case _KMEM:
  2840. counter = &memcg->kmem;
  2841. break;
  2842. default:
  2843. BUG();
  2844. }
  2845. switch (MEMFILE_ATTR(cft->private)) {
  2846. case RES_USAGE:
  2847. if (counter == &memcg->memory)
  2848. return mem_cgroup_usage(memcg, false);
  2849. if (counter == &memcg->memsw)
  2850. return mem_cgroup_usage(memcg, true);
  2851. return (u64)page_counter_read(counter) * PAGE_SIZE;
  2852. case RES_LIMIT:
  2853. return (u64)counter->limit * PAGE_SIZE;
  2854. case RES_MAX_USAGE:
  2855. return (u64)counter->watermark * PAGE_SIZE;
  2856. case RES_FAILCNT:
  2857. return counter->failcnt;
  2858. case RES_SOFT_LIMIT:
  2859. return (u64)memcg->soft_limit * PAGE_SIZE;
  2860. default:
  2861. BUG();
  2862. }
  2863. }
  2864. #ifdef CONFIG_MEMCG_KMEM
  2865. static int memcg_activate_kmem(struct mem_cgroup *memcg,
  2866. unsigned long nr_pages)
  2867. {
  2868. int err = 0;
  2869. int memcg_id;
  2870. if (memcg_kmem_is_active(memcg))
  2871. return 0;
  2872. /*
  2873. * For simplicity, we won't allow this to be disabled. It also can't
  2874. * be changed if the cgroup has children already, or if tasks had
  2875. * already joined.
  2876. *
  2877. * If tasks join before we set the limit, a person looking at
  2878. * kmem.usage_in_bytes will have no way to determine when it took
  2879. * place, which makes the value quite meaningless.
  2880. *
  2881. * After it first became limited, changes in the value of the limit are
  2882. * of course permitted.
  2883. */
  2884. mutex_lock(&memcg_create_mutex);
  2885. if (cgroup_has_tasks(memcg->css.cgroup) ||
  2886. (memcg->use_hierarchy && memcg_has_children(memcg)))
  2887. err = -EBUSY;
  2888. mutex_unlock(&memcg_create_mutex);
  2889. if (err)
  2890. goto out;
  2891. memcg_id = memcg_alloc_cache_id();
  2892. if (memcg_id < 0) {
  2893. err = memcg_id;
  2894. goto out;
  2895. }
  2896. /*
  2897. * We couldn't have accounted to this cgroup, because it hasn't got
  2898. * activated yet, so this should succeed.
  2899. */
  2900. err = page_counter_limit(&memcg->kmem, nr_pages);
  2901. VM_BUG_ON(err);
  2902. static_key_slow_inc(&memcg_kmem_enabled_key);
  2903. /*
  2904. * A memory cgroup is considered kmem-active as soon as it gets
  2905. * kmemcg_id. Setting the id after enabling static branching will
  2906. * guarantee no one starts accounting before all call sites are
  2907. * patched.
  2908. */
  2909. memcg->kmemcg_id = memcg_id;
  2910. out:
  2911. return err;
  2912. }
  2913. static int memcg_update_kmem_limit(struct mem_cgroup *memcg,
  2914. unsigned long limit)
  2915. {
  2916. int ret;
  2917. mutex_lock(&memcg_limit_mutex);
  2918. if (!memcg_kmem_is_active(memcg))
  2919. ret = memcg_activate_kmem(memcg, limit);
  2920. else
  2921. ret = page_counter_limit(&memcg->kmem, limit);
  2922. mutex_unlock(&memcg_limit_mutex);
  2923. return ret;
  2924. }
  2925. static int memcg_propagate_kmem(struct mem_cgroup *memcg)
  2926. {
  2927. int ret = 0;
  2928. struct mem_cgroup *parent = parent_mem_cgroup(memcg);
  2929. if (!parent)
  2930. return 0;
  2931. mutex_lock(&memcg_limit_mutex);
  2932. /*
  2933. * If the parent cgroup is not kmem-active now, it cannot be activated
  2934. * after this point, because it has at least one child already.
  2935. */
  2936. if (memcg_kmem_is_active(parent))
  2937. ret = memcg_activate_kmem(memcg, PAGE_COUNTER_MAX);
  2938. mutex_unlock(&memcg_limit_mutex);
  2939. return ret;
  2940. }
  2941. #else
  2942. static int memcg_update_kmem_limit(struct mem_cgroup *memcg,
  2943. unsigned long limit)
  2944. {
  2945. return -EINVAL;
  2946. }
  2947. #endif /* CONFIG_MEMCG_KMEM */
  2948. /*
  2949. * The user of this function is...
  2950. * RES_LIMIT.
  2951. */
  2952. static ssize_t mem_cgroup_write(struct kernfs_open_file *of,
  2953. char *buf, size_t nbytes, loff_t off)
  2954. {
  2955. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  2956. unsigned long nr_pages;
  2957. int ret;
  2958. buf = strstrip(buf);
  2959. ret = page_counter_memparse(buf, "-1", &nr_pages);
  2960. if (ret)
  2961. return ret;
  2962. switch (MEMFILE_ATTR(of_cft(of)->private)) {
  2963. case RES_LIMIT:
  2964. if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
  2965. ret = -EINVAL;
  2966. break;
  2967. }
  2968. switch (MEMFILE_TYPE(of_cft(of)->private)) {
  2969. case _MEM:
  2970. ret = mem_cgroup_resize_limit(memcg, nr_pages);
  2971. break;
  2972. case _MEMSWAP:
  2973. ret = mem_cgroup_resize_memsw_limit(memcg, nr_pages);
  2974. break;
  2975. case _KMEM:
  2976. ret = memcg_update_kmem_limit(memcg, nr_pages);
  2977. break;
  2978. }
  2979. break;
  2980. case RES_SOFT_LIMIT:
  2981. memcg->soft_limit = nr_pages;
  2982. ret = 0;
  2983. break;
  2984. }
  2985. return ret ?: nbytes;
  2986. }
  2987. static ssize_t mem_cgroup_reset(struct kernfs_open_file *of, char *buf,
  2988. size_t nbytes, loff_t off)
  2989. {
  2990. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  2991. struct page_counter *counter;
  2992. switch (MEMFILE_TYPE(of_cft(of)->private)) {
  2993. case _MEM:
  2994. counter = &memcg->memory;
  2995. break;
  2996. case _MEMSWAP:
  2997. counter = &memcg->memsw;
  2998. break;
  2999. case _KMEM:
  3000. counter = &memcg->kmem;
  3001. break;
  3002. default:
  3003. BUG();
  3004. }
  3005. switch (MEMFILE_ATTR(of_cft(of)->private)) {
  3006. case RES_MAX_USAGE:
  3007. page_counter_reset_watermark(counter);
  3008. break;
  3009. case RES_FAILCNT:
  3010. counter->failcnt = 0;
  3011. break;
  3012. default:
  3013. BUG();
  3014. }
  3015. return nbytes;
  3016. }
  3017. static u64 mem_cgroup_move_charge_read(struct cgroup_subsys_state *css,
  3018. struct cftype *cft)
  3019. {
  3020. return mem_cgroup_from_css(css)->move_charge_at_immigrate;
  3021. }
  3022. #ifdef CONFIG_MMU
  3023. static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
  3024. struct cftype *cft, u64 val)
  3025. {
  3026. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3027. if (val & ~MOVE_MASK)
  3028. return -EINVAL;
  3029. /*
  3030. * No kind of locking is needed in here, because ->can_attach() will
  3031. * check this value once in the beginning of the process, and then carry
  3032. * on with stale data. This means that changes to this value will only
  3033. * affect task migrations starting after the change.
  3034. */
  3035. memcg->move_charge_at_immigrate = val;
  3036. return 0;
  3037. }
  3038. #else
  3039. static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
  3040. struct cftype *cft, u64 val)
  3041. {
  3042. return -ENOSYS;
  3043. }
  3044. #endif
  3045. #ifdef CONFIG_NUMA
  3046. static int memcg_numa_stat_show(struct seq_file *m, void *v)
  3047. {
  3048. struct numa_stat {
  3049. const char *name;
  3050. unsigned int lru_mask;
  3051. };
  3052. static const struct numa_stat stats[] = {
  3053. { "total", LRU_ALL },
  3054. { "file", LRU_ALL_FILE },
  3055. { "anon", LRU_ALL_ANON },
  3056. { "unevictable", BIT(LRU_UNEVICTABLE) },
  3057. };
  3058. const struct numa_stat *stat;
  3059. int nid;
  3060. unsigned long nr;
  3061. struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
  3062. for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
  3063. nr = mem_cgroup_nr_lru_pages(memcg, stat->lru_mask);
  3064. seq_printf(m, "%s=%lu", stat->name, nr);
  3065. for_each_node_state(nid, N_MEMORY) {
  3066. nr = mem_cgroup_node_nr_lru_pages(memcg, nid,
  3067. stat->lru_mask);
  3068. seq_printf(m, " N%d=%lu", nid, nr);
  3069. }
  3070. seq_putc(m, '\n');
  3071. }
  3072. for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
  3073. struct mem_cgroup *iter;
  3074. nr = 0;
  3075. for_each_mem_cgroup_tree(iter, memcg)
  3076. nr += mem_cgroup_nr_lru_pages(iter, stat->lru_mask);
  3077. seq_printf(m, "hierarchical_%s=%lu", stat->name, nr);
  3078. for_each_node_state(nid, N_MEMORY) {
  3079. nr = 0;
  3080. for_each_mem_cgroup_tree(iter, memcg)
  3081. nr += mem_cgroup_node_nr_lru_pages(
  3082. iter, nid, stat->lru_mask);
  3083. seq_printf(m, " N%d=%lu", nid, nr);
  3084. }
  3085. seq_putc(m, '\n');
  3086. }
  3087. return 0;
  3088. }
  3089. #endif /* CONFIG_NUMA */
  3090. static int memcg_stat_show(struct seq_file *m, void *v)
  3091. {
  3092. struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
  3093. unsigned long memory, memsw;
  3094. struct mem_cgroup *mi;
  3095. unsigned int i;
  3096. BUILD_BUG_ON(ARRAY_SIZE(mem_cgroup_stat_names) !=
  3097. MEM_CGROUP_STAT_NSTATS);
  3098. BUILD_BUG_ON(ARRAY_SIZE(mem_cgroup_events_names) !=
  3099. MEM_CGROUP_EVENTS_NSTATS);
  3100. BUILD_BUG_ON(ARRAY_SIZE(mem_cgroup_lru_names) != NR_LRU_LISTS);
  3101. for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
  3102. if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
  3103. continue;
  3104. seq_printf(m, "%s %ld\n", mem_cgroup_stat_names[i],
  3105. mem_cgroup_read_stat(memcg, i) * PAGE_SIZE);
  3106. }
  3107. for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++)
  3108. seq_printf(m, "%s %lu\n", mem_cgroup_events_names[i],
  3109. mem_cgroup_read_events(memcg, i));
  3110. for (i = 0; i < NR_LRU_LISTS; i++)
  3111. seq_printf(m, "%s %lu\n", mem_cgroup_lru_names[i],
  3112. mem_cgroup_nr_lru_pages(memcg, BIT(i)) * PAGE_SIZE);
  3113. /* Hierarchical information */
  3114. memory = memsw = PAGE_COUNTER_MAX;
  3115. for (mi = memcg; mi; mi = parent_mem_cgroup(mi)) {
  3116. memory = min(memory, mi->memory.limit);
  3117. memsw = min(memsw, mi->memsw.limit);
  3118. }
  3119. seq_printf(m, "hierarchical_memory_limit %llu\n",
  3120. (u64)memory * PAGE_SIZE);
  3121. if (do_swap_account)
  3122. seq_printf(m, "hierarchical_memsw_limit %llu\n",
  3123. (u64)memsw * PAGE_SIZE);
  3124. for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
  3125. long long val = 0;
  3126. if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
  3127. continue;
  3128. for_each_mem_cgroup_tree(mi, memcg)
  3129. val += mem_cgroup_read_stat(mi, i) * PAGE_SIZE;
  3130. seq_printf(m, "total_%s %lld\n", mem_cgroup_stat_names[i], val);
  3131. }
  3132. for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
  3133. unsigned long long val = 0;
  3134. for_each_mem_cgroup_tree(mi, memcg)
  3135. val += mem_cgroup_read_events(mi, i);
  3136. seq_printf(m, "total_%s %llu\n",
  3137. mem_cgroup_events_names[i], val);
  3138. }
  3139. for (i = 0; i < NR_LRU_LISTS; i++) {
  3140. unsigned long long val = 0;
  3141. for_each_mem_cgroup_tree(mi, memcg)
  3142. val += mem_cgroup_nr_lru_pages(mi, BIT(i)) * PAGE_SIZE;
  3143. seq_printf(m, "total_%s %llu\n", mem_cgroup_lru_names[i], val);
  3144. }
  3145. #ifdef CONFIG_DEBUG_VM
  3146. {
  3147. int nid, zid;
  3148. struct mem_cgroup_per_zone *mz;
  3149. struct zone_reclaim_stat *rstat;
  3150. unsigned long recent_rotated[2] = {0, 0};
  3151. unsigned long recent_scanned[2] = {0, 0};
  3152. for_each_online_node(nid)
  3153. for (zid = 0; zid < MAX_NR_ZONES; zid++) {
  3154. mz = &memcg->nodeinfo[nid]->zoneinfo[zid];
  3155. rstat = &mz->lruvec.reclaim_stat;
  3156. recent_rotated[0] += rstat->recent_rotated[0];
  3157. recent_rotated[1] += rstat->recent_rotated[1];
  3158. recent_scanned[0] += rstat->recent_scanned[0];
  3159. recent_scanned[1] += rstat->recent_scanned[1];
  3160. }
  3161. seq_printf(m, "recent_rotated_anon %lu\n", recent_rotated[0]);
  3162. seq_printf(m, "recent_rotated_file %lu\n", recent_rotated[1]);
  3163. seq_printf(m, "recent_scanned_anon %lu\n", recent_scanned[0]);
  3164. seq_printf(m, "recent_scanned_file %lu\n", recent_scanned[1]);
  3165. }
  3166. #endif
  3167. return 0;
  3168. }
  3169. static u64 mem_cgroup_swappiness_read(struct cgroup_subsys_state *css,
  3170. struct cftype *cft)
  3171. {
  3172. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3173. return mem_cgroup_swappiness(memcg);
  3174. }
  3175. static int mem_cgroup_swappiness_write(struct cgroup_subsys_state *css,
  3176. struct cftype *cft, u64 val)
  3177. {
  3178. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3179. if (val > 100)
  3180. return -EINVAL;
  3181. if (css->parent)
  3182. memcg->swappiness = val;
  3183. else
  3184. vm_swappiness = val;
  3185. return 0;
  3186. }
  3187. static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
  3188. {
  3189. struct mem_cgroup_threshold_ary *t;
  3190. unsigned long usage;
  3191. int i;
  3192. rcu_read_lock();
  3193. if (!swap)
  3194. t = rcu_dereference(memcg->thresholds.primary);
  3195. else
  3196. t = rcu_dereference(memcg->memsw_thresholds.primary);
  3197. if (!t)
  3198. goto unlock;
  3199. usage = mem_cgroup_usage(memcg, swap);
  3200. /*
  3201. * current_threshold points to threshold just below or equal to usage.
  3202. * If it's not true, a threshold was crossed after last
  3203. * call of __mem_cgroup_threshold().
  3204. */
  3205. i = t->current_threshold;
  3206. /*
  3207. * Iterate backward over array of thresholds starting from
  3208. * current_threshold and check if a threshold is crossed.
  3209. * If none of thresholds below usage is crossed, we read
  3210. * only one element of the array here.
  3211. */
  3212. for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
  3213. eventfd_signal(t->entries[i].eventfd, 1);
  3214. /* i = current_threshold + 1 */
  3215. i++;
  3216. /*
  3217. * Iterate forward over array of thresholds starting from
  3218. * current_threshold+1 and check if a threshold is crossed.
  3219. * If none of thresholds above usage is crossed, we read
  3220. * only one element of the array here.
  3221. */
  3222. for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
  3223. eventfd_signal(t->entries[i].eventfd, 1);
  3224. /* Update current_threshold */
  3225. t->current_threshold = i - 1;
  3226. unlock:
  3227. rcu_read_unlock();
  3228. }
  3229. static void mem_cgroup_threshold(struct mem_cgroup *memcg)
  3230. {
  3231. while (memcg) {
  3232. __mem_cgroup_threshold(memcg, false);
  3233. if (do_swap_account)
  3234. __mem_cgroup_threshold(memcg, true);
  3235. memcg = parent_mem_cgroup(memcg);
  3236. }
  3237. }
  3238. static int compare_thresholds(const void *a, const void *b)
  3239. {
  3240. const struct mem_cgroup_threshold *_a = a;
  3241. const struct mem_cgroup_threshold *_b = b;
  3242. if (_a->threshold > _b->threshold)
  3243. return 1;
  3244. if (_a->threshold < _b->threshold)
  3245. return -1;
  3246. return 0;
  3247. }
  3248. static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
  3249. {
  3250. struct mem_cgroup_eventfd_list *ev;
  3251. spin_lock(&memcg_oom_lock);
  3252. list_for_each_entry(ev, &memcg->oom_notify, list)
  3253. eventfd_signal(ev->eventfd, 1);
  3254. spin_unlock(&memcg_oom_lock);
  3255. return 0;
  3256. }
  3257. static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
  3258. {
  3259. struct mem_cgroup *iter;
  3260. for_each_mem_cgroup_tree(iter, memcg)
  3261. mem_cgroup_oom_notify_cb(iter);
  3262. }
  3263. static int __mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
  3264. struct eventfd_ctx *eventfd, const char *args, enum res_type type)
  3265. {
  3266. struct mem_cgroup_thresholds *thresholds;
  3267. struct mem_cgroup_threshold_ary *new;
  3268. unsigned long threshold;
  3269. unsigned long usage;
  3270. int i, size, ret;
  3271. ret = page_counter_memparse(args, "-1", &threshold);
  3272. if (ret)
  3273. return ret;
  3274. mutex_lock(&memcg->thresholds_lock);
  3275. if (type == _MEM) {
  3276. thresholds = &memcg->thresholds;
  3277. usage = mem_cgroup_usage(memcg, false);
  3278. } else if (type == _MEMSWAP) {
  3279. thresholds = &memcg->memsw_thresholds;
  3280. usage = mem_cgroup_usage(memcg, true);
  3281. } else
  3282. BUG();
  3283. /* Check if a threshold crossed before adding a new one */
  3284. if (thresholds->primary)
  3285. __mem_cgroup_threshold(memcg, type == _MEMSWAP);
  3286. size = thresholds->primary ? thresholds->primary->size + 1 : 1;
  3287. /* Allocate memory for new array of thresholds */
  3288. new = kmalloc(sizeof(*new) + size * sizeof(struct mem_cgroup_threshold),
  3289. GFP_KERNEL);
  3290. if (!new) {
  3291. ret = -ENOMEM;
  3292. goto unlock;
  3293. }
  3294. new->size = size;
  3295. /* Copy thresholds (if any) to new array */
  3296. if (thresholds->primary) {
  3297. memcpy(new->entries, thresholds->primary->entries, (size - 1) *
  3298. sizeof(struct mem_cgroup_threshold));
  3299. }
  3300. /* Add new threshold */
  3301. new->entries[size - 1].eventfd = eventfd;
  3302. new->entries[size - 1].threshold = threshold;
  3303. /* Sort thresholds. Registering of new threshold isn't time-critical */
  3304. sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
  3305. compare_thresholds, NULL);
  3306. /* Find current threshold */
  3307. new->current_threshold = -1;
  3308. for (i = 0; i < size; i++) {
  3309. if (new->entries[i].threshold <= usage) {
  3310. /*
  3311. * new->current_threshold will not be used until
  3312. * rcu_assign_pointer(), so it's safe to increment
  3313. * it here.
  3314. */
  3315. ++new->current_threshold;
  3316. } else
  3317. break;
  3318. }
  3319. /* Free old spare buffer and save old primary buffer as spare */
  3320. kfree(thresholds->spare);
  3321. thresholds->spare = thresholds->primary;
  3322. rcu_assign_pointer(thresholds->primary, new);
  3323. /* To be sure that nobody uses thresholds */
  3324. synchronize_rcu();
  3325. unlock:
  3326. mutex_unlock(&memcg->thresholds_lock);
  3327. return ret;
  3328. }
  3329. static int mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
  3330. struct eventfd_ctx *eventfd, const char *args)
  3331. {
  3332. return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEM);
  3333. }
  3334. static int memsw_cgroup_usage_register_event(struct mem_cgroup *memcg,
  3335. struct eventfd_ctx *eventfd, const char *args)
  3336. {
  3337. return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEMSWAP);
  3338. }
  3339. static void __mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
  3340. struct eventfd_ctx *eventfd, enum res_type type)
  3341. {
  3342. struct mem_cgroup_thresholds *thresholds;
  3343. struct mem_cgroup_threshold_ary *new;
  3344. unsigned long usage;
  3345. int i, j, size;
  3346. mutex_lock(&memcg->thresholds_lock);
  3347. if (type == _MEM) {
  3348. thresholds = &memcg->thresholds;
  3349. usage = mem_cgroup_usage(memcg, false);
  3350. } else if (type == _MEMSWAP) {
  3351. thresholds = &memcg->memsw_thresholds;
  3352. usage = mem_cgroup_usage(memcg, true);
  3353. } else
  3354. BUG();
  3355. if (!thresholds->primary)
  3356. goto unlock;
  3357. /* Check if a threshold crossed before removing */
  3358. __mem_cgroup_threshold(memcg, type == _MEMSWAP);
  3359. /* Calculate new number of threshold */
  3360. size = 0;
  3361. for (i = 0; i < thresholds->primary->size; i++) {
  3362. if (thresholds->primary->entries[i].eventfd != eventfd)
  3363. size++;
  3364. }
  3365. new = thresholds->spare;
  3366. /* Set thresholds array to NULL if we don't have thresholds */
  3367. if (!size) {
  3368. kfree(new);
  3369. new = NULL;
  3370. goto swap_buffers;
  3371. }
  3372. new->size = size;
  3373. /* Copy thresholds and find current threshold */
  3374. new->current_threshold = -1;
  3375. for (i = 0, j = 0; i < thresholds->primary->size; i++) {
  3376. if (thresholds->primary->entries[i].eventfd == eventfd)
  3377. continue;
  3378. new->entries[j] = thresholds->primary->entries[i];
  3379. if (new->entries[j].threshold <= usage) {
  3380. /*
  3381. * new->current_threshold will not be used
  3382. * until rcu_assign_pointer(), so it's safe to increment
  3383. * it here.
  3384. */
  3385. ++new->current_threshold;
  3386. }
  3387. j++;
  3388. }
  3389. swap_buffers:
  3390. /* Swap primary and spare array */
  3391. thresholds->spare = thresholds->primary;
  3392. /* If all events are unregistered, free the spare array */
  3393. if (!new) {
  3394. kfree(thresholds->spare);
  3395. thresholds->spare = NULL;
  3396. }
  3397. rcu_assign_pointer(thresholds->primary, new);
  3398. /* To be sure that nobody uses thresholds */
  3399. synchronize_rcu();
  3400. unlock:
  3401. mutex_unlock(&memcg->thresholds_lock);
  3402. }
  3403. static void mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
  3404. struct eventfd_ctx *eventfd)
  3405. {
  3406. return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEM);
  3407. }
  3408. static void memsw_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
  3409. struct eventfd_ctx *eventfd)
  3410. {
  3411. return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEMSWAP);
  3412. }
  3413. static int mem_cgroup_oom_register_event(struct mem_cgroup *memcg,
  3414. struct eventfd_ctx *eventfd, const char *args)
  3415. {
  3416. struct mem_cgroup_eventfd_list *event;
  3417. event = kmalloc(sizeof(*event), GFP_KERNEL);
  3418. if (!event)
  3419. return -ENOMEM;
  3420. spin_lock(&memcg_oom_lock);
  3421. event->eventfd = eventfd;
  3422. list_add(&event->list, &memcg->oom_notify);
  3423. /* already in OOM ? */
  3424. if (atomic_read(&memcg->under_oom))
  3425. eventfd_signal(eventfd, 1);
  3426. spin_unlock(&memcg_oom_lock);
  3427. return 0;
  3428. }
  3429. static void mem_cgroup_oom_unregister_event(struct mem_cgroup *memcg,
  3430. struct eventfd_ctx *eventfd)
  3431. {
  3432. struct mem_cgroup_eventfd_list *ev, *tmp;
  3433. spin_lock(&memcg_oom_lock);
  3434. list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
  3435. if (ev->eventfd == eventfd) {
  3436. list_del(&ev->list);
  3437. kfree(ev);
  3438. }
  3439. }
  3440. spin_unlock(&memcg_oom_lock);
  3441. }
  3442. static int mem_cgroup_oom_control_read(struct seq_file *sf, void *v)
  3443. {
  3444. struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(sf));
  3445. seq_printf(sf, "oom_kill_disable %d\n", memcg->oom_kill_disable);
  3446. seq_printf(sf, "under_oom %d\n", (bool)atomic_read(&memcg->under_oom));
  3447. return 0;
  3448. }
  3449. static int mem_cgroup_oom_control_write(struct cgroup_subsys_state *css,
  3450. struct cftype *cft, u64 val)
  3451. {
  3452. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3453. /* cannot set to root cgroup and only 0 and 1 are allowed */
  3454. if (!css->parent || !((val == 0) || (val == 1)))
  3455. return -EINVAL;
  3456. memcg->oom_kill_disable = val;
  3457. if (!val)
  3458. memcg_oom_recover(memcg);
  3459. return 0;
  3460. }
  3461. #ifdef CONFIG_MEMCG_KMEM
  3462. static int memcg_init_kmem(struct mem_cgroup *memcg, struct cgroup_subsys *ss)
  3463. {
  3464. int ret;
  3465. ret = memcg_propagate_kmem(memcg);
  3466. if (ret)
  3467. return ret;
  3468. return mem_cgroup_sockets_init(memcg, ss);
  3469. }
  3470. static void memcg_destroy_kmem(struct mem_cgroup *memcg)
  3471. {
  3472. memcg_destroy_kmem_caches(memcg);
  3473. mem_cgroup_sockets_destroy(memcg);
  3474. }
  3475. #else
  3476. static int memcg_init_kmem(struct mem_cgroup *memcg, struct cgroup_subsys *ss)
  3477. {
  3478. return 0;
  3479. }
  3480. static void memcg_destroy_kmem(struct mem_cgroup *memcg)
  3481. {
  3482. }
  3483. #endif
  3484. /*
  3485. * DO NOT USE IN NEW FILES.
  3486. *
  3487. * "cgroup.event_control" implementation.
  3488. *
  3489. * This is way over-engineered. It tries to support fully configurable
  3490. * events for each user. Such level of flexibility is completely
  3491. * unnecessary especially in the light of the planned unified hierarchy.
  3492. *
  3493. * Please deprecate this and replace with something simpler if at all
  3494. * possible.
  3495. */
  3496. /*
  3497. * Unregister event and free resources.
  3498. *
  3499. * Gets called from workqueue.
  3500. */
  3501. static void memcg_event_remove(struct work_struct *work)
  3502. {
  3503. struct mem_cgroup_event *event =
  3504. container_of(work, struct mem_cgroup_event, remove);
  3505. struct mem_cgroup *memcg = event->memcg;
  3506. remove_wait_queue(event->wqh, &event->wait);
  3507. event->unregister_event(memcg, event->eventfd);
  3508. /* Notify userspace the event is going away. */
  3509. eventfd_signal(event->eventfd, 1);
  3510. eventfd_ctx_put(event->eventfd);
  3511. kfree(event);
  3512. css_put(&memcg->css);
  3513. }
  3514. /*
  3515. * Gets called on POLLHUP on eventfd when user closes it.
  3516. *
  3517. * Called with wqh->lock held and interrupts disabled.
  3518. */
  3519. static int memcg_event_wake(wait_queue_t *wait, unsigned mode,
  3520. int sync, void *key)
  3521. {
  3522. struct mem_cgroup_event *event =
  3523. container_of(wait, struct mem_cgroup_event, wait);
  3524. struct mem_cgroup *memcg = event->memcg;
  3525. unsigned long flags = (unsigned long)key;
  3526. if (flags & POLLHUP) {
  3527. /*
  3528. * If the event has been detached at cgroup removal, we
  3529. * can simply return knowing the other side will cleanup
  3530. * for us.
  3531. *
  3532. * We can't race against event freeing since the other
  3533. * side will require wqh->lock via remove_wait_queue(),
  3534. * which we hold.
  3535. */
  3536. spin_lock(&memcg->event_list_lock);
  3537. if (!list_empty(&event->list)) {
  3538. list_del_init(&event->list);
  3539. /*
  3540. * We are in atomic context, but cgroup_event_remove()
  3541. * may sleep, so we have to call it in workqueue.
  3542. */
  3543. schedule_work(&event->remove);
  3544. }
  3545. spin_unlock(&memcg->event_list_lock);
  3546. }
  3547. return 0;
  3548. }
  3549. static void memcg_event_ptable_queue_proc(struct file *file,
  3550. wait_queue_head_t *wqh, poll_table *pt)
  3551. {
  3552. struct mem_cgroup_event *event =
  3553. container_of(pt, struct mem_cgroup_event, pt);
  3554. event->wqh = wqh;
  3555. add_wait_queue(wqh, &event->wait);
  3556. }
  3557. /*
  3558. * DO NOT USE IN NEW FILES.
  3559. *
  3560. * Parse input and register new cgroup event handler.
  3561. *
  3562. * Input must be in format '<event_fd> <control_fd> <args>'.
  3563. * Interpretation of args is defined by control file implementation.
  3564. */
  3565. static ssize_t memcg_write_event_control(struct kernfs_open_file *of,
  3566. char *buf, size_t nbytes, loff_t off)
  3567. {
  3568. struct cgroup_subsys_state *css = of_css(of);
  3569. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3570. struct mem_cgroup_event *event;
  3571. struct cgroup_subsys_state *cfile_css;
  3572. unsigned int efd, cfd;
  3573. struct fd efile;
  3574. struct fd cfile;
  3575. const char *name;
  3576. char *endp;
  3577. int ret;
  3578. buf = strstrip(buf);
  3579. efd = simple_strtoul(buf, &endp, 10);
  3580. if (*endp != ' ')
  3581. return -EINVAL;
  3582. buf = endp + 1;
  3583. cfd = simple_strtoul(buf, &endp, 10);
  3584. if ((*endp != ' ') && (*endp != '\0'))
  3585. return -EINVAL;
  3586. buf = endp + 1;
  3587. event = kzalloc(sizeof(*event), GFP_KERNEL);
  3588. if (!event)
  3589. return -ENOMEM;
  3590. event->memcg = memcg;
  3591. INIT_LIST_HEAD(&event->list);
  3592. init_poll_funcptr(&event->pt, memcg_event_ptable_queue_proc);
  3593. init_waitqueue_func_entry(&event->wait, memcg_event_wake);
  3594. INIT_WORK(&event->remove, memcg_event_remove);
  3595. efile = fdget(efd);
  3596. if (!efile.file) {
  3597. ret = -EBADF;
  3598. goto out_kfree;
  3599. }
  3600. event->eventfd = eventfd_ctx_fileget(efile.file);
  3601. if (IS_ERR(event->eventfd)) {
  3602. ret = PTR_ERR(event->eventfd);
  3603. goto out_put_efile;
  3604. }
  3605. cfile = fdget(cfd);
  3606. if (!cfile.file) {
  3607. ret = -EBADF;
  3608. goto out_put_eventfd;
  3609. }
  3610. /* the process need read permission on control file */
  3611. /* AV: shouldn't we check that it's been opened for read instead? */
  3612. ret = inode_permission(file_inode(cfile.file), MAY_READ);
  3613. if (ret < 0)
  3614. goto out_put_cfile;
  3615. /*
  3616. * Determine the event callbacks and set them in @event. This used
  3617. * to be done via struct cftype but cgroup core no longer knows
  3618. * about these events. The following is crude but the whole thing
  3619. * is for compatibility anyway.
  3620. *
  3621. * DO NOT ADD NEW FILES.
  3622. */
  3623. name = cfile.file->f_path.dentry->d_name.name;
  3624. if (!strcmp(name, "memory.usage_in_bytes")) {
  3625. event->register_event = mem_cgroup_usage_register_event;
  3626. event->unregister_event = mem_cgroup_usage_unregister_event;
  3627. } else if (!strcmp(name, "memory.oom_control")) {
  3628. event->register_event = mem_cgroup_oom_register_event;
  3629. event->unregister_event = mem_cgroup_oom_unregister_event;
  3630. } else if (!strcmp(name, "memory.pressure_level")) {
  3631. event->register_event = vmpressure_register_event;
  3632. event->unregister_event = vmpressure_unregister_event;
  3633. } else if (!strcmp(name, "memory.memsw.usage_in_bytes")) {
  3634. event->register_event = memsw_cgroup_usage_register_event;
  3635. event->unregister_event = memsw_cgroup_usage_unregister_event;
  3636. } else {
  3637. ret = -EINVAL;
  3638. goto out_put_cfile;
  3639. }
  3640. /*
  3641. * Verify @cfile should belong to @css. Also, remaining events are
  3642. * automatically removed on cgroup destruction but the removal is
  3643. * asynchronous, so take an extra ref on @css.
  3644. */
  3645. cfile_css = css_tryget_online_from_dir(cfile.file->f_path.dentry->d_parent,
  3646. &memory_cgrp_subsys);
  3647. ret = -EINVAL;
  3648. if (IS_ERR(cfile_css))
  3649. goto out_put_cfile;
  3650. if (cfile_css != css) {
  3651. css_put(cfile_css);
  3652. goto out_put_cfile;
  3653. }
  3654. ret = event->register_event(memcg, event->eventfd, buf);
  3655. if (ret)
  3656. goto out_put_css;
  3657. efile.file->f_op->poll(efile.file, &event->pt);
  3658. spin_lock(&memcg->event_list_lock);
  3659. list_add(&event->list, &memcg->event_list);
  3660. spin_unlock(&memcg->event_list_lock);
  3661. fdput(cfile);
  3662. fdput(efile);
  3663. return nbytes;
  3664. out_put_css:
  3665. css_put(css);
  3666. out_put_cfile:
  3667. fdput(cfile);
  3668. out_put_eventfd:
  3669. eventfd_ctx_put(event->eventfd);
  3670. out_put_efile:
  3671. fdput(efile);
  3672. out_kfree:
  3673. kfree(event);
  3674. return ret;
  3675. }
  3676. static struct cftype mem_cgroup_legacy_files[] = {
  3677. {
  3678. .name = "usage_in_bytes",
  3679. .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
  3680. .read_u64 = mem_cgroup_read_u64,
  3681. },
  3682. {
  3683. .name = "max_usage_in_bytes",
  3684. .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
  3685. .write = mem_cgroup_reset,
  3686. .read_u64 = mem_cgroup_read_u64,
  3687. },
  3688. {
  3689. .name = "limit_in_bytes",
  3690. .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
  3691. .write = mem_cgroup_write,
  3692. .read_u64 = mem_cgroup_read_u64,
  3693. },
  3694. {
  3695. .name = "soft_limit_in_bytes",
  3696. .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
  3697. .write = mem_cgroup_write,
  3698. .read_u64 = mem_cgroup_read_u64,
  3699. },
  3700. {
  3701. .name = "failcnt",
  3702. .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
  3703. .write = mem_cgroup_reset,
  3704. .read_u64 = mem_cgroup_read_u64,
  3705. },
  3706. {
  3707. .name = "stat",
  3708. .seq_show = memcg_stat_show,
  3709. },
  3710. {
  3711. .name = "force_empty",
  3712. .write = mem_cgroup_force_empty_write,
  3713. },
  3714. {
  3715. .name = "use_hierarchy",
  3716. .write_u64 = mem_cgroup_hierarchy_write,
  3717. .read_u64 = mem_cgroup_hierarchy_read,
  3718. },
  3719. {
  3720. .name = "cgroup.event_control", /* XXX: for compat */
  3721. .write = memcg_write_event_control,
  3722. .flags = CFTYPE_NO_PREFIX,
  3723. .mode = S_IWUGO,
  3724. },
  3725. {
  3726. .name = "swappiness",
  3727. .read_u64 = mem_cgroup_swappiness_read,
  3728. .write_u64 = mem_cgroup_swappiness_write,
  3729. },
  3730. {
  3731. .name = "move_charge_at_immigrate",
  3732. .read_u64 = mem_cgroup_move_charge_read,
  3733. .write_u64 = mem_cgroup_move_charge_write,
  3734. },
  3735. {
  3736. .name = "oom_control",
  3737. .seq_show = mem_cgroup_oom_control_read,
  3738. .write_u64 = mem_cgroup_oom_control_write,
  3739. .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
  3740. },
  3741. {
  3742. .name = "pressure_level",
  3743. },
  3744. #ifdef CONFIG_NUMA
  3745. {
  3746. .name = "numa_stat",
  3747. .seq_show = memcg_numa_stat_show,
  3748. },
  3749. #endif
  3750. #ifdef CONFIG_MEMCG_KMEM
  3751. {
  3752. .name = "kmem.limit_in_bytes",
  3753. .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
  3754. .write = mem_cgroup_write,
  3755. .read_u64 = mem_cgroup_read_u64,
  3756. },
  3757. {
  3758. .name = "kmem.usage_in_bytes",
  3759. .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
  3760. .read_u64 = mem_cgroup_read_u64,
  3761. },
  3762. {
  3763. .name = "kmem.failcnt",
  3764. .private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
  3765. .write = mem_cgroup_reset,
  3766. .read_u64 = mem_cgroup_read_u64,
  3767. },
  3768. {
  3769. .name = "kmem.max_usage_in_bytes",
  3770. .private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
  3771. .write = mem_cgroup_reset,
  3772. .read_u64 = mem_cgroup_read_u64,
  3773. },
  3774. #ifdef CONFIG_SLABINFO
  3775. {
  3776. .name = "kmem.slabinfo",
  3777. .seq_start = slab_start,
  3778. .seq_next = slab_next,
  3779. .seq_stop = slab_stop,
  3780. .seq_show = memcg_slab_show,
  3781. },
  3782. #endif
  3783. #endif
  3784. { }, /* terminate */
  3785. };
  3786. static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
  3787. {
  3788. struct mem_cgroup_per_node *pn;
  3789. struct mem_cgroup_per_zone *mz;
  3790. int zone, tmp = node;
  3791. /*
  3792. * This routine is called against possible nodes.
  3793. * But it's BUG to call kmalloc() against offline node.
  3794. *
  3795. * TODO: this routine can waste much memory for nodes which will
  3796. * never be onlined. It's better to use memory hotplug callback
  3797. * function.
  3798. */
  3799. if (!node_state(node, N_NORMAL_MEMORY))
  3800. tmp = -1;
  3801. pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
  3802. if (!pn)
  3803. return 1;
  3804. for (zone = 0; zone < MAX_NR_ZONES; zone++) {
  3805. mz = &pn->zoneinfo[zone];
  3806. lruvec_init(&mz->lruvec);
  3807. mz->usage_in_excess = 0;
  3808. mz->on_tree = false;
  3809. mz->memcg = memcg;
  3810. }
  3811. memcg->nodeinfo[node] = pn;
  3812. return 0;
  3813. }
  3814. static void free_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
  3815. {
  3816. kfree(memcg->nodeinfo[node]);
  3817. }
  3818. static struct mem_cgroup *mem_cgroup_alloc(void)
  3819. {
  3820. struct mem_cgroup *memcg;
  3821. size_t size;
  3822. size = sizeof(struct mem_cgroup);
  3823. size += nr_node_ids * sizeof(struct mem_cgroup_per_node *);
  3824. memcg = kzalloc(size, GFP_KERNEL);
  3825. if (!memcg)
  3826. return NULL;
  3827. memcg->stat = alloc_percpu(struct mem_cgroup_stat_cpu);
  3828. if (!memcg->stat)
  3829. goto out_free;
  3830. spin_lock_init(&memcg->pcp_counter_lock);
  3831. return memcg;
  3832. out_free:
  3833. kfree(memcg);
  3834. return NULL;
  3835. }
  3836. /*
  3837. * At destroying mem_cgroup, references from swap_cgroup can remain.
  3838. * (scanning all at force_empty is too costly...)
  3839. *
  3840. * Instead of clearing all references at force_empty, we remember
  3841. * the number of reference from swap_cgroup and free mem_cgroup when
  3842. * it goes down to 0.
  3843. *
  3844. * Removal of cgroup itself succeeds regardless of refs from swap.
  3845. */
  3846. static void __mem_cgroup_free(struct mem_cgroup *memcg)
  3847. {
  3848. int node;
  3849. mem_cgroup_remove_from_trees(memcg);
  3850. for_each_node(node)
  3851. free_mem_cgroup_per_zone_info(memcg, node);
  3852. free_percpu(memcg->stat);
  3853. disarm_static_keys(memcg);
  3854. kfree(memcg);
  3855. }
  3856. /*
  3857. * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
  3858. */
  3859. struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *memcg)
  3860. {
  3861. if (!memcg->memory.parent)
  3862. return NULL;
  3863. return mem_cgroup_from_counter(memcg->memory.parent, memory);
  3864. }
  3865. EXPORT_SYMBOL(parent_mem_cgroup);
  3866. static struct cgroup_subsys_state * __ref
  3867. mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
  3868. {
  3869. struct mem_cgroup *memcg;
  3870. long error = -ENOMEM;
  3871. int node;
  3872. memcg = mem_cgroup_alloc();
  3873. if (!memcg)
  3874. return ERR_PTR(error);
  3875. for_each_node(node)
  3876. if (alloc_mem_cgroup_per_zone_info(memcg, node))
  3877. goto free_out;
  3878. /* root ? */
  3879. if (parent_css == NULL) {
  3880. root_mem_cgroup = memcg;
  3881. page_counter_init(&memcg->memory, NULL);
  3882. memcg->high = PAGE_COUNTER_MAX;
  3883. memcg->soft_limit = PAGE_COUNTER_MAX;
  3884. page_counter_init(&memcg->memsw, NULL);
  3885. page_counter_init(&memcg->kmem, NULL);
  3886. }
  3887. memcg->last_scanned_node = MAX_NUMNODES;
  3888. INIT_LIST_HEAD(&memcg->oom_notify);
  3889. memcg->move_charge_at_immigrate = 0;
  3890. mutex_init(&memcg->thresholds_lock);
  3891. spin_lock_init(&memcg->move_lock);
  3892. vmpressure_init(&memcg->vmpressure);
  3893. INIT_LIST_HEAD(&memcg->event_list);
  3894. spin_lock_init(&memcg->event_list_lock);
  3895. #ifdef CONFIG_MEMCG_KMEM
  3896. memcg->kmemcg_id = -1;
  3897. #endif
  3898. return &memcg->css;
  3899. free_out:
  3900. __mem_cgroup_free(memcg);
  3901. return ERR_PTR(error);
  3902. }
  3903. static int
  3904. mem_cgroup_css_online(struct cgroup_subsys_state *css)
  3905. {
  3906. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3907. struct mem_cgroup *parent = mem_cgroup_from_css(css->parent);
  3908. int ret;
  3909. if (css->id > MEM_CGROUP_ID_MAX)
  3910. return -ENOSPC;
  3911. if (!parent)
  3912. return 0;
  3913. mutex_lock(&memcg_create_mutex);
  3914. memcg->use_hierarchy = parent->use_hierarchy;
  3915. memcg->oom_kill_disable = parent->oom_kill_disable;
  3916. memcg->swappiness = mem_cgroup_swappiness(parent);
  3917. if (parent->use_hierarchy) {
  3918. page_counter_init(&memcg->memory, &parent->memory);
  3919. memcg->high = PAGE_COUNTER_MAX;
  3920. memcg->soft_limit = PAGE_COUNTER_MAX;
  3921. page_counter_init(&memcg->memsw, &parent->memsw);
  3922. page_counter_init(&memcg->kmem, &parent->kmem);
  3923. /*
  3924. * No need to take a reference to the parent because cgroup
  3925. * core guarantees its existence.
  3926. */
  3927. } else {
  3928. page_counter_init(&memcg->memory, NULL);
  3929. memcg->high = PAGE_COUNTER_MAX;
  3930. memcg->soft_limit = PAGE_COUNTER_MAX;
  3931. page_counter_init(&memcg->memsw, NULL);
  3932. page_counter_init(&memcg->kmem, NULL);
  3933. /*
  3934. * Deeper hierachy with use_hierarchy == false doesn't make
  3935. * much sense so let cgroup subsystem know about this
  3936. * unfortunate state in our controller.
  3937. */
  3938. if (parent != root_mem_cgroup)
  3939. memory_cgrp_subsys.broken_hierarchy = true;
  3940. }
  3941. mutex_unlock(&memcg_create_mutex);
  3942. ret = memcg_init_kmem(memcg, &memory_cgrp_subsys);
  3943. if (ret)
  3944. return ret;
  3945. /*
  3946. * Make sure the memcg is initialized: mem_cgroup_iter()
  3947. * orders reading memcg->initialized against its callers
  3948. * reading the memcg members.
  3949. */
  3950. smp_store_release(&memcg->initialized, 1);
  3951. return 0;
  3952. }
  3953. static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
  3954. {
  3955. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3956. struct mem_cgroup_event *event, *tmp;
  3957. /*
  3958. * Unregister events and notify userspace.
  3959. * Notify userspace about cgroup removing only after rmdir of cgroup
  3960. * directory to avoid race between userspace and kernelspace.
  3961. */
  3962. spin_lock(&memcg->event_list_lock);
  3963. list_for_each_entry_safe(event, tmp, &memcg->event_list, list) {
  3964. list_del_init(&event->list);
  3965. schedule_work(&event->remove);
  3966. }
  3967. spin_unlock(&memcg->event_list_lock);
  3968. vmpressure_cleanup(&memcg->vmpressure);
  3969. }
  3970. static void mem_cgroup_css_free(struct cgroup_subsys_state *css)
  3971. {
  3972. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3973. memcg_destroy_kmem(memcg);
  3974. __mem_cgroup_free(memcg);
  3975. }
  3976. /**
  3977. * mem_cgroup_css_reset - reset the states of a mem_cgroup
  3978. * @css: the target css
  3979. *
  3980. * Reset the states of the mem_cgroup associated with @css. This is
  3981. * invoked when the userland requests disabling on the default hierarchy
  3982. * but the memcg is pinned through dependency. The memcg should stop
  3983. * applying policies and should revert to the vanilla state as it may be
  3984. * made visible again.
  3985. *
  3986. * The current implementation only resets the essential configurations.
  3987. * This needs to be expanded to cover all the visible parts.
  3988. */
  3989. static void mem_cgroup_css_reset(struct cgroup_subsys_state *css)
  3990. {
  3991. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3992. mem_cgroup_resize_limit(memcg, PAGE_COUNTER_MAX);
  3993. mem_cgroup_resize_memsw_limit(memcg, PAGE_COUNTER_MAX);
  3994. memcg_update_kmem_limit(memcg, PAGE_COUNTER_MAX);
  3995. memcg->low = 0;
  3996. memcg->high = PAGE_COUNTER_MAX;
  3997. memcg->soft_limit = PAGE_COUNTER_MAX;
  3998. }
  3999. #ifdef CONFIG_MMU
  4000. /* Handlers for move charge at task migration. */
  4001. static int mem_cgroup_do_precharge(unsigned long count)
  4002. {
  4003. int ret;
  4004. /* Try a single bulk charge without reclaim first */
  4005. ret = try_charge(mc.to, GFP_KERNEL & ~__GFP_WAIT, count);
  4006. if (!ret) {
  4007. mc.precharge += count;
  4008. return ret;
  4009. }
  4010. if (ret == -EINTR) {
  4011. cancel_charge(root_mem_cgroup, count);
  4012. return ret;
  4013. }
  4014. /* Try charges one by one with reclaim */
  4015. while (count--) {
  4016. ret = try_charge(mc.to, GFP_KERNEL & ~__GFP_NORETRY, 1);
  4017. /*
  4018. * In case of failure, any residual charges against
  4019. * mc.to will be dropped by mem_cgroup_clear_mc()
  4020. * later on. However, cancel any charges that are
  4021. * bypassed to root right away or they'll be lost.
  4022. */
  4023. if (ret == -EINTR)
  4024. cancel_charge(root_mem_cgroup, 1);
  4025. if (ret)
  4026. return ret;
  4027. mc.precharge++;
  4028. cond_resched();
  4029. }
  4030. return 0;
  4031. }
  4032. /**
  4033. * get_mctgt_type - get target type of moving charge
  4034. * @vma: the vma the pte to be checked belongs
  4035. * @addr: the address corresponding to the pte to be checked
  4036. * @ptent: the pte to be checked
  4037. * @target: the pointer the target page or swap ent will be stored(can be NULL)
  4038. *
  4039. * Returns
  4040. * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
  4041. * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
  4042. * move charge. if @target is not NULL, the page is stored in target->page
  4043. * with extra refcnt got(Callers should handle it).
  4044. * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
  4045. * target for charge migration. if @target is not NULL, the entry is stored
  4046. * in target->ent.
  4047. *
  4048. * Called with pte lock held.
  4049. */
  4050. union mc_target {
  4051. struct page *page;
  4052. swp_entry_t ent;
  4053. };
  4054. enum mc_target_type {
  4055. MC_TARGET_NONE = 0,
  4056. MC_TARGET_PAGE,
  4057. MC_TARGET_SWAP,
  4058. };
  4059. static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
  4060. unsigned long addr, pte_t ptent)
  4061. {
  4062. struct page *page = vm_normal_page(vma, addr, ptent);
  4063. if (!page || !page_mapped(page))
  4064. return NULL;
  4065. if (PageAnon(page)) {
  4066. if (!(mc.flags & MOVE_ANON))
  4067. return NULL;
  4068. } else {
  4069. if (!(mc.flags & MOVE_FILE))
  4070. return NULL;
  4071. }
  4072. if (!get_page_unless_zero(page))
  4073. return NULL;
  4074. return page;
  4075. }
  4076. #ifdef CONFIG_SWAP
  4077. static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
  4078. unsigned long addr, pte_t ptent, swp_entry_t *entry)
  4079. {
  4080. struct page *page = NULL;
  4081. swp_entry_t ent = pte_to_swp_entry(ptent);
  4082. if (!(mc.flags & MOVE_ANON) || non_swap_entry(ent))
  4083. return NULL;
  4084. /*
  4085. * Because lookup_swap_cache() updates some statistics counter,
  4086. * we call find_get_page() with swapper_space directly.
  4087. */
  4088. page = find_get_page(swap_address_space(ent), ent.val);
  4089. if (do_swap_account)
  4090. entry->val = ent.val;
  4091. return page;
  4092. }
  4093. #else
  4094. static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
  4095. unsigned long addr, pte_t ptent, swp_entry_t *entry)
  4096. {
  4097. return NULL;
  4098. }
  4099. #endif
  4100. static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
  4101. unsigned long addr, pte_t ptent, swp_entry_t *entry)
  4102. {
  4103. struct page *page = NULL;
  4104. struct address_space *mapping;
  4105. pgoff_t pgoff;
  4106. if (!vma->vm_file) /* anonymous vma */
  4107. return NULL;
  4108. if (!(mc.flags & MOVE_FILE))
  4109. return NULL;
  4110. mapping = vma->vm_file->f_mapping;
  4111. pgoff = linear_page_index(vma, addr);
  4112. /* page is moved even if it's not RSS of this task(page-faulted). */
  4113. #ifdef CONFIG_SWAP
  4114. /* shmem/tmpfs may report page out on swap: account for that too. */
  4115. if (shmem_mapping(mapping)) {
  4116. page = find_get_entry(mapping, pgoff);
  4117. if (radix_tree_exceptional_entry(page)) {
  4118. swp_entry_t swp = radix_to_swp_entry(page);
  4119. if (do_swap_account)
  4120. *entry = swp;
  4121. page = find_get_page(swap_address_space(swp), swp.val);
  4122. }
  4123. } else
  4124. page = find_get_page(mapping, pgoff);
  4125. #else
  4126. page = find_get_page(mapping, pgoff);
  4127. #endif
  4128. return page;
  4129. }
  4130. static enum mc_target_type get_mctgt_type(struct vm_area_struct *vma,
  4131. unsigned long addr, pte_t ptent, union mc_target *target)
  4132. {
  4133. struct page *page = NULL;
  4134. enum mc_target_type ret = MC_TARGET_NONE;
  4135. swp_entry_t ent = { .val = 0 };
  4136. if (pte_present(ptent))
  4137. page = mc_handle_present_pte(vma, addr, ptent);
  4138. else if (is_swap_pte(ptent))
  4139. page = mc_handle_swap_pte(vma, addr, ptent, &ent);
  4140. else if (pte_none(ptent))
  4141. page = mc_handle_file_pte(vma, addr, ptent, &ent);
  4142. if (!page && !ent.val)
  4143. return ret;
  4144. if (page) {
  4145. /*
  4146. * Do only loose check w/o serialization.
  4147. * mem_cgroup_move_account() checks the page is valid or
  4148. * not under LRU exclusion.
  4149. */
  4150. if (page->mem_cgroup == mc.from) {
  4151. ret = MC_TARGET_PAGE;
  4152. if (target)
  4153. target->page = page;
  4154. }
  4155. if (!ret || !target)
  4156. put_page(page);
  4157. }
  4158. /* There is a swap entry and a page doesn't exist or isn't charged */
  4159. if (ent.val && !ret &&
  4160. mem_cgroup_id(mc.from) == lookup_swap_cgroup_id(ent)) {
  4161. ret = MC_TARGET_SWAP;
  4162. if (target)
  4163. target->ent = ent;
  4164. }
  4165. return ret;
  4166. }
  4167. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  4168. /*
  4169. * We don't consider swapping or file mapped pages because THP does not
  4170. * support them for now.
  4171. * Caller should make sure that pmd_trans_huge(pmd) is true.
  4172. */
  4173. static enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
  4174. unsigned long addr, pmd_t pmd, union mc_target *target)
  4175. {
  4176. struct page *page = NULL;
  4177. enum mc_target_type ret = MC_TARGET_NONE;
  4178. page = pmd_page(pmd);
  4179. VM_BUG_ON_PAGE(!page || !PageHead(page), page);
  4180. if (!(mc.flags & MOVE_ANON))
  4181. return ret;
  4182. if (page->mem_cgroup == mc.from) {
  4183. ret = MC_TARGET_PAGE;
  4184. if (target) {
  4185. get_page(page);
  4186. target->page = page;
  4187. }
  4188. }
  4189. return ret;
  4190. }
  4191. #else
  4192. static inline enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
  4193. unsigned long addr, pmd_t pmd, union mc_target *target)
  4194. {
  4195. return MC_TARGET_NONE;
  4196. }
  4197. #endif
  4198. static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
  4199. unsigned long addr, unsigned long end,
  4200. struct mm_walk *walk)
  4201. {
  4202. struct vm_area_struct *vma = walk->vma;
  4203. pte_t *pte;
  4204. spinlock_t *ptl;
  4205. if (pmd_trans_huge_lock(pmd, vma, &ptl) == 1) {
  4206. if (get_mctgt_type_thp(vma, addr, *pmd, NULL) == MC_TARGET_PAGE)
  4207. mc.precharge += HPAGE_PMD_NR;
  4208. spin_unlock(ptl);
  4209. return 0;
  4210. }
  4211. if (pmd_trans_unstable(pmd))
  4212. return 0;
  4213. pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
  4214. for (; addr != end; pte++, addr += PAGE_SIZE)
  4215. if (get_mctgt_type(vma, addr, *pte, NULL))
  4216. mc.precharge++; /* increment precharge temporarily */
  4217. pte_unmap_unlock(pte - 1, ptl);
  4218. cond_resched();
  4219. return 0;
  4220. }
  4221. static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
  4222. {
  4223. unsigned long precharge;
  4224. struct mm_walk mem_cgroup_count_precharge_walk = {
  4225. .pmd_entry = mem_cgroup_count_precharge_pte_range,
  4226. .mm = mm,
  4227. };
  4228. down_read(&mm->mmap_sem);
  4229. walk_page_range(0, ~0UL, &mem_cgroup_count_precharge_walk);
  4230. up_read(&mm->mmap_sem);
  4231. precharge = mc.precharge;
  4232. mc.precharge = 0;
  4233. return precharge;
  4234. }
  4235. static int mem_cgroup_precharge_mc(struct mm_struct *mm)
  4236. {
  4237. unsigned long precharge = mem_cgroup_count_precharge(mm);
  4238. VM_BUG_ON(mc.moving_task);
  4239. mc.moving_task = current;
  4240. return mem_cgroup_do_precharge(precharge);
  4241. }
  4242. /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
  4243. static void __mem_cgroup_clear_mc(void)
  4244. {
  4245. struct mem_cgroup *from = mc.from;
  4246. struct mem_cgroup *to = mc.to;
  4247. /* we must uncharge all the leftover precharges from mc.to */
  4248. if (mc.precharge) {
  4249. cancel_charge(mc.to, mc.precharge);
  4250. mc.precharge = 0;
  4251. }
  4252. /*
  4253. * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
  4254. * we must uncharge here.
  4255. */
  4256. if (mc.moved_charge) {
  4257. cancel_charge(mc.from, mc.moved_charge);
  4258. mc.moved_charge = 0;
  4259. }
  4260. /* we must fixup refcnts and charges */
  4261. if (mc.moved_swap) {
  4262. /* uncharge swap account from the old cgroup */
  4263. if (!mem_cgroup_is_root(mc.from))
  4264. page_counter_uncharge(&mc.from->memsw, mc.moved_swap);
  4265. /*
  4266. * we charged both to->memory and to->memsw, so we
  4267. * should uncharge to->memory.
  4268. */
  4269. if (!mem_cgroup_is_root(mc.to))
  4270. page_counter_uncharge(&mc.to->memory, mc.moved_swap);
  4271. css_put_many(&mc.from->css, mc.moved_swap);
  4272. /* we've already done css_get(mc.to) */
  4273. mc.moved_swap = 0;
  4274. }
  4275. memcg_oom_recover(from);
  4276. memcg_oom_recover(to);
  4277. wake_up_all(&mc.waitq);
  4278. }
  4279. static void mem_cgroup_clear_mc(void)
  4280. {
  4281. /*
  4282. * we must clear moving_task before waking up waiters at the end of
  4283. * task migration.
  4284. */
  4285. mc.moving_task = NULL;
  4286. __mem_cgroup_clear_mc();
  4287. spin_lock(&mc.lock);
  4288. mc.from = NULL;
  4289. mc.to = NULL;
  4290. spin_unlock(&mc.lock);
  4291. }
  4292. static int mem_cgroup_can_attach(struct cgroup_subsys_state *css,
  4293. struct cgroup_taskset *tset)
  4294. {
  4295. struct task_struct *p = cgroup_taskset_first(tset);
  4296. int ret = 0;
  4297. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  4298. unsigned long move_flags;
  4299. /*
  4300. * We are now commited to this value whatever it is. Changes in this
  4301. * tunable will only affect upcoming migrations, not the current one.
  4302. * So we need to save it, and keep it going.
  4303. */
  4304. move_flags = ACCESS_ONCE(memcg->move_charge_at_immigrate);
  4305. if (move_flags) {
  4306. struct mm_struct *mm;
  4307. struct mem_cgroup *from = mem_cgroup_from_task(p);
  4308. VM_BUG_ON(from == memcg);
  4309. mm = get_task_mm(p);
  4310. if (!mm)
  4311. return 0;
  4312. /* We move charges only when we move a owner of the mm */
  4313. if (mm->owner == p) {
  4314. VM_BUG_ON(mc.from);
  4315. VM_BUG_ON(mc.to);
  4316. VM_BUG_ON(mc.precharge);
  4317. VM_BUG_ON(mc.moved_charge);
  4318. VM_BUG_ON(mc.moved_swap);
  4319. spin_lock(&mc.lock);
  4320. mc.from = from;
  4321. mc.to = memcg;
  4322. mc.flags = move_flags;
  4323. spin_unlock(&mc.lock);
  4324. /* We set mc.moving_task later */
  4325. ret = mem_cgroup_precharge_mc(mm);
  4326. if (ret)
  4327. mem_cgroup_clear_mc();
  4328. }
  4329. mmput(mm);
  4330. }
  4331. return ret;
  4332. }
  4333. static void mem_cgroup_cancel_attach(struct cgroup_subsys_state *css,
  4334. struct cgroup_taskset *tset)
  4335. {
  4336. if (mc.to)
  4337. mem_cgroup_clear_mc();
  4338. }
  4339. static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
  4340. unsigned long addr, unsigned long end,
  4341. struct mm_walk *walk)
  4342. {
  4343. int ret = 0;
  4344. struct vm_area_struct *vma = walk->vma;
  4345. pte_t *pte;
  4346. spinlock_t *ptl;
  4347. enum mc_target_type target_type;
  4348. union mc_target target;
  4349. struct page *page;
  4350. /*
  4351. * We don't take compound_lock() here but no race with splitting thp
  4352. * happens because:
  4353. * - if pmd_trans_huge_lock() returns 1, the relevant thp is not
  4354. * under splitting, which means there's no concurrent thp split,
  4355. * - if another thread runs into split_huge_page() just after we
  4356. * entered this if-block, the thread must wait for page table lock
  4357. * to be unlocked in __split_huge_page_splitting(), where the main
  4358. * part of thp split is not executed yet.
  4359. */
  4360. if (pmd_trans_huge_lock(pmd, vma, &ptl) == 1) {
  4361. if (mc.precharge < HPAGE_PMD_NR) {
  4362. spin_unlock(ptl);
  4363. return 0;
  4364. }
  4365. target_type = get_mctgt_type_thp(vma, addr, *pmd, &target);
  4366. if (target_type == MC_TARGET_PAGE) {
  4367. page = target.page;
  4368. if (!isolate_lru_page(page)) {
  4369. if (!mem_cgroup_move_account(page, HPAGE_PMD_NR,
  4370. mc.from, mc.to)) {
  4371. mc.precharge -= HPAGE_PMD_NR;
  4372. mc.moved_charge += HPAGE_PMD_NR;
  4373. }
  4374. putback_lru_page(page);
  4375. }
  4376. put_page(page);
  4377. }
  4378. spin_unlock(ptl);
  4379. return 0;
  4380. }
  4381. if (pmd_trans_unstable(pmd))
  4382. return 0;
  4383. retry:
  4384. pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
  4385. for (; addr != end; addr += PAGE_SIZE) {
  4386. pte_t ptent = *(pte++);
  4387. swp_entry_t ent;
  4388. if (!mc.precharge)
  4389. break;
  4390. switch (get_mctgt_type(vma, addr, ptent, &target)) {
  4391. case MC_TARGET_PAGE:
  4392. page = target.page;
  4393. if (isolate_lru_page(page))
  4394. goto put;
  4395. if (!mem_cgroup_move_account(page, 1, mc.from, mc.to)) {
  4396. mc.precharge--;
  4397. /* we uncharge from mc.from later. */
  4398. mc.moved_charge++;
  4399. }
  4400. putback_lru_page(page);
  4401. put: /* get_mctgt_type() gets the page */
  4402. put_page(page);
  4403. break;
  4404. case MC_TARGET_SWAP:
  4405. ent = target.ent;
  4406. if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to)) {
  4407. mc.precharge--;
  4408. /* we fixup refcnts and charges later. */
  4409. mc.moved_swap++;
  4410. }
  4411. break;
  4412. default:
  4413. break;
  4414. }
  4415. }
  4416. pte_unmap_unlock(pte - 1, ptl);
  4417. cond_resched();
  4418. if (addr != end) {
  4419. /*
  4420. * We have consumed all precharges we got in can_attach().
  4421. * We try charge one by one, but don't do any additional
  4422. * charges to mc.to if we have failed in charge once in attach()
  4423. * phase.
  4424. */
  4425. ret = mem_cgroup_do_precharge(1);
  4426. if (!ret)
  4427. goto retry;
  4428. }
  4429. return ret;
  4430. }
  4431. static void mem_cgroup_move_charge(struct mm_struct *mm)
  4432. {
  4433. struct mm_walk mem_cgroup_move_charge_walk = {
  4434. .pmd_entry = mem_cgroup_move_charge_pte_range,
  4435. .mm = mm,
  4436. };
  4437. lru_add_drain_all();
  4438. /*
  4439. * Signal mem_cgroup_begin_page_stat() to take the memcg's
  4440. * move_lock while we're moving its pages to another memcg.
  4441. * Then wait for already started RCU-only updates to finish.
  4442. */
  4443. atomic_inc(&mc.from->moving_account);
  4444. synchronize_rcu();
  4445. retry:
  4446. if (unlikely(!down_read_trylock(&mm->mmap_sem))) {
  4447. /*
  4448. * Someone who are holding the mmap_sem might be waiting in
  4449. * waitq. So we cancel all extra charges, wake up all waiters,
  4450. * and retry. Because we cancel precharges, we might not be able
  4451. * to move enough charges, but moving charge is a best-effort
  4452. * feature anyway, so it wouldn't be a big problem.
  4453. */
  4454. __mem_cgroup_clear_mc();
  4455. cond_resched();
  4456. goto retry;
  4457. }
  4458. /*
  4459. * When we have consumed all precharges and failed in doing
  4460. * additional charge, the page walk just aborts.
  4461. */
  4462. walk_page_range(0, ~0UL, &mem_cgroup_move_charge_walk);
  4463. up_read(&mm->mmap_sem);
  4464. atomic_dec(&mc.from->moving_account);
  4465. }
  4466. static void mem_cgroup_move_task(struct cgroup_subsys_state *css,
  4467. struct cgroup_taskset *tset)
  4468. {
  4469. struct task_struct *p = cgroup_taskset_first(tset);
  4470. struct mm_struct *mm = get_task_mm(p);
  4471. if (mm) {
  4472. if (mc.to)
  4473. mem_cgroup_move_charge(mm);
  4474. mmput(mm);
  4475. }
  4476. if (mc.to)
  4477. mem_cgroup_clear_mc();
  4478. }
  4479. #else /* !CONFIG_MMU */
  4480. static int mem_cgroup_can_attach(struct cgroup_subsys_state *css,
  4481. struct cgroup_taskset *tset)
  4482. {
  4483. return 0;
  4484. }
  4485. static void mem_cgroup_cancel_attach(struct cgroup_subsys_state *css,
  4486. struct cgroup_taskset *tset)
  4487. {
  4488. }
  4489. static void mem_cgroup_move_task(struct cgroup_subsys_state *css,
  4490. struct cgroup_taskset *tset)
  4491. {
  4492. }
  4493. #endif
  4494. /*
  4495. * Cgroup retains root cgroups across [un]mount cycles making it necessary
  4496. * to verify whether we're attached to the default hierarchy on each mount
  4497. * attempt.
  4498. */
  4499. static void mem_cgroup_bind(struct cgroup_subsys_state *root_css)
  4500. {
  4501. /*
  4502. * use_hierarchy is forced on the default hierarchy. cgroup core
  4503. * guarantees that @root doesn't have any children, so turning it
  4504. * on for the root memcg is enough.
  4505. */
  4506. if (cgroup_on_dfl(root_css->cgroup))
  4507. mem_cgroup_from_css(root_css)->use_hierarchy = true;
  4508. }
  4509. static u64 memory_current_read(struct cgroup_subsys_state *css,
  4510. struct cftype *cft)
  4511. {
  4512. return mem_cgroup_usage(mem_cgroup_from_css(css), false);
  4513. }
  4514. static int memory_low_show(struct seq_file *m, void *v)
  4515. {
  4516. struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
  4517. unsigned long low = ACCESS_ONCE(memcg->low);
  4518. if (low == PAGE_COUNTER_MAX)
  4519. seq_puts(m, "infinity\n");
  4520. else
  4521. seq_printf(m, "%llu\n", (u64)low * PAGE_SIZE);
  4522. return 0;
  4523. }
  4524. static ssize_t memory_low_write(struct kernfs_open_file *of,
  4525. char *buf, size_t nbytes, loff_t off)
  4526. {
  4527. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  4528. unsigned long low;
  4529. int err;
  4530. buf = strstrip(buf);
  4531. err = page_counter_memparse(buf, "infinity", &low);
  4532. if (err)
  4533. return err;
  4534. memcg->low = low;
  4535. return nbytes;
  4536. }
  4537. static int memory_high_show(struct seq_file *m, void *v)
  4538. {
  4539. struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
  4540. unsigned long high = ACCESS_ONCE(memcg->high);
  4541. if (high == PAGE_COUNTER_MAX)
  4542. seq_puts(m, "infinity\n");
  4543. else
  4544. seq_printf(m, "%llu\n", (u64)high * PAGE_SIZE);
  4545. return 0;
  4546. }
  4547. static ssize_t memory_high_write(struct kernfs_open_file *of,
  4548. char *buf, size_t nbytes, loff_t off)
  4549. {
  4550. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  4551. unsigned long high;
  4552. int err;
  4553. buf = strstrip(buf);
  4554. err = page_counter_memparse(buf, "infinity", &high);
  4555. if (err)
  4556. return err;
  4557. memcg->high = high;
  4558. return nbytes;
  4559. }
  4560. static int memory_max_show(struct seq_file *m, void *v)
  4561. {
  4562. struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
  4563. unsigned long max = ACCESS_ONCE(memcg->memory.limit);
  4564. if (max == PAGE_COUNTER_MAX)
  4565. seq_puts(m, "infinity\n");
  4566. else
  4567. seq_printf(m, "%llu\n", (u64)max * PAGE_SIZE);
  4568. return 0;
  4569. }
  4570. static ssize_t memory_max_write(struct kernfs_open_file *of,
  4571. char *buf, size_t nbytes, loff_t off)
  4572. {
  4573. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  4574. unsigned long max;
  4575. int err;
  4576. buf = strstrip(buf);
  4577. err = page_counter_memparse(buf, "infinity", &max);
  4578. if (err)
  4579. return err;
  4580. err = mem_cgroup_resize_limit(memcg, max);
  4581. if (err)
  4582. return err;
  4583. return nbytes;
  4584. }
  4585. static int memory_events_show(struct seq_file *m, void *v)
  4586. {
  4587. struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
  4588. seq_printf(m, "low %lu\n", mem_cgroup_read_events(memcg, MEMCG_LOW));
  4589. seq_printf(m, "high %lu\n", mem_cgroup_read_events(memcg, MEMCG_HIGH));
  4590. seq_printf(m, "max %lu\n", mem_cgroup_read_events(memcg, MEMCG_MAX));
  4591. seq_printf(m, "oom %lu\n", mem_cgroup_read_events(memcg, MEMCG_OOM));
  4592. return 0;
  4593. }
  4594. static struct cftype memory_files[] = {
  4595. {
  4596. .name = "current",
  4597. .read_u64 = memory_current_read,
  4598. },
  4599. {
  4600. .name = "low",
  4601. .flags = CFTYPE_NOT_ON_ROOT,
  4602. .seq_show = memory_low_show,
  4603. .write = memory_low_write,
  4604. },
  4605. {
  4606. .name = "high",
  4607. .flags = CFTYPE_NOT_ON_ROOT,
  4608. .seq_show = memory_high_show,
  4609. .write = memory_high_write,
  4610. },
  4611. {
  4612. .name = "max",
  4613. .flags = CFTYPE_NOT_ON_ROOT,
  4614. .seq_show = memory_max_show,
  4615. .write = memory_max_write,
  4616. },
  4617. {
  4618. .name = "events",
  4619. .flags = CFTYPE_NOT_ON_ROOT,
  4620. .seq_show = memory_events_show,
  4621. },
  4622. { } /* terminate */
  4623. };
  4624. struct cgroup_subsys memory_cgrp_subsys = {
  4625. .css_alloc = mem_cgroup_css_alloc,
  4626. .css_online = mem_cgroup_css_online,
  4627. .css_offline = mem_cgroup_css_offline,
  4628. .css_free = mem_cgroup_css_free,
  4629. .css_reset = mem_cgroup_css_reset,
  4630. .can_attach = mem_cgroup_can_attach,
  4631. .cancel_attach = mem_cgroup_cancel_attach,
  4632. .attach = mem_cgroup_move_task,
  4633. .bind = mem_cgroup_bind,
  4634. .dfl_cftypes = memory_files,
  4635. .legacy_cftypes = mem_cgroup_legacy_files,
  4636. .early_init = 0,
  4637. };
  4638. /**
  4639. * mem_cgroup_events - count memory events against a cgroup
  4640. * @memcg: the memory cgroup
  4641. * @idx: the event index
  4642. * @nr: the number of events to account for
  4643. */
  4644. void mem_cgroup_events(struct mem_cgroup *memcg,
  4645. enum mem_cgroup_events_index idx,
  4646. unsigned int nr)
  4647. {
  4648. this_cpu_add(memcg->stat->events[idx], nr);
  4649. }
  4650. /**
  4651. * mem_cgroup_low - check if memory consumption is below the normal range
  4652. * @root: the highest ancestor to consider
  4653. * @memcg: the memory cgroup to check
  4654. *
  4655. * Returns %true if memory consumption of @memcg, and that of all
  4656. * configurable ancestors up to @root, is below the normal range.
  4657. */
  4658. bool mem_cgroup_low(struct mem_cgroup *root, struct mem_cgroup *memcg)
  4659. {
  4660. if (mem_cgroup_disabled())
  4661. return false;
  4662. /*
  4663. * The toplevel group doesn't have a configurable range, so
  4664. * it's never low when looked at directly, and it is not
  4665. * considered an ancestor when assessing the hierarchy.
  4666. */
  4667. if (memcg == root_mem_cgroup)
  4668. return false;
  4669. if (page_counter_read(&memcg->memory) > memcg->low)
  4670. return false;
  4671. while (memcg != root) {
  4672. memcg = parent_mem_cgroup(memcg);
  4673. if (memcg == root_mem_cgroup)
  4674. break;
  4675. if (page_counter_read(&memcg->memory) > memcg->low)
  4676. return false;
  4677. }
  4678. return true;
  4679. }
  4680. /**
  4681. * mem_cgroup_try_charge - try charging a page
  4682. * @page: page to charge
  4683. * @mm: mm context of the victim
  4684. * @gfp_mask: reclaim mode
  4685. * @memcgp: charged memcg return
  4686. *
  4687. * Try to charge @page to the memcg that @mm belongs to, reclaiming
  4688. * pages according to @gfp_mask if necessary.
  4689. *
  4690. * Returns 0 on success, with *@memcgp pointing to the charged memcg.
  4691. * Otherwise, an error code is returned.
  4692. *
  4693. * After page->mapping has been set up, the caller must finalize the
  4694. * charge with mem_cgroup_commit_charge(). Or abort the transaction
  4695. * with mem_cgroup_cancel_charge() in case page instantiation fails.
  4696. */
  4697. int mem_cgroup_try_charge(struct page *page, struct mm_struct *mm,
  4698. gfp_t gfp_mask, struct mem_cgroup **memcgp)
  4699. {
  4700. struct mem_cgroup *memcg = NULL;
  4701. unsigned int nr_pages = 1;
  4702. int ret = 0;
  4703. if (mem_cgroup_disabled())
  4704. goto out;
  4705. if (PageSwapCache(page)) {
  4706. /*
  4707. * Every swap fault against a single page tries to charge the
  4708. * page, bail as early as possible. shmem_unuse() encounters
  4709. * already charged pages, too. The USED bit is protected by
  4710. * the page lock, which serializes swap cache removal, which
  4711. * in turn serializes uncharging.
  4712. */
  4713. if (page->mem_cgroup)
  4714. goto out;
  4715. }
  4716. if (PageTransHuge(page)) {
  4717. nr_pages <<= compound_order(page);
  4718. VM_BUG_ON_PAGE(!PageTransHuge(page), page);
  4719. }
  4720. if (do_swap_account && PageSwapCache(page))
  4721. memcg = try_get_mem_cgroup_from_page(page);
  4722. if (!memcg)
  4723. memcg = get_mem_cgroup_from_mm(mm);
  4724. ret = try_charge(memcg, gfp_mask, nr_pages);
  4725. css_put(&memcg->css);
  4726. if (ret == -EINTR) {
  4727. memcg = root_mem_cgroup;
  4728. ret = 0;
  4729. }
  4730. out:
  4731. *memcgp = memcg;
  4732. return ret;
  4733. }
  4734. /**
  4735. * mem_cgroup_commit_charge - commit a page charge
  4736. * @page: page to charge
  4737. * @memcg: memcg to charge the page to
  4738. * @lrucare: page might be on LRU already
  4739. *
  4740. * Finalize a charge transaction started by mem_cgroup_try_charge(),
  4741. * after page->mapping has been set up. This must happen atomically
  4742. * as part of the page instantiation, i.e. under the page table lock
  4743. * for anonymous pages, under the page lock for page and swap cache.
  4744. *
  4745. * In addition, the page must not be on the LRU during the commit, to
  4746. * prevent racing with task migration. If it might be, use @lrucare.
  4747. *
  4748. * Use mem_cgroup_cancel_charge() to cancel the transaction instead.
  4749. */
  4750. void mem_cgroup_commit_charge(struct page *page, struct mem_cgroup *memcg,
  4751. bool lrucare)
  4752. {
  4753. unsigned int nr_pages = 1;
  4754. VM_BUG_ON_PAGE(!page->mapping, page);
  4755. VM_BUG_ON_PAGE(PageLRU(page) && !lrucare, page);
  4756. if (mem_cgroup_disabled())
  4757. return;
  4758. /*
  4759. * Swap faults will attempt to charge the same page multiple
  4760. * times. But reuse_swap_page() might have removed the page
  4761. * from swapcache already, so we can't check PageSwapCache().
  4762. */
  4763. if (!memcg)
  4764. return;
  4765. commit_charge(page, memcg, lrucare);
  4766. if (PageTransHuge(page)) {
  4767. nr_pages <<= compound_order(page);
  4768. VM_BUG_ON_PAGE(!PageTransHuge(page), page);
  4769. }
  4770. local_irq_disable();
  4771. mem_cgroup_charge_statistics(memcg, page, nr_pages);
  4772. memcg_check_events(memcg, page);
  4773. local_irq_enable();
  4774. if (do_swap_account && PageSwapCache(page)) {
  4775. swp_entry_t entry = { .val = page_private(page) };
  4776. /*
  4777. * The swap entry might not get freed for a long time,
  4778. * let's not wait for it. The page already received a
  4779. * memory+swap charge, drop the swap entry duplicate.
  4780. */
  4781. mem_cgroup_uncharge_swap(entry);
  4782. }
  4783. }
  4784. /**
  4785. * mem_cgroup_cancel_charge - cancel a page charge
  4786. * @page: page to charge
  4787. * @memcg: memcg to charge the page to
  4788. *
  4789. * Cancel a charge transaction started by mem_cgroup_try_charge().
  4790. */
  4791. void mem_cgroup_cancel_charge(struct page *page, struct mem_cgroup *memcg)
  4792. {
  4793. unsigned int nr_pages = 1;
  4794. if (mem_cgroup_disabled())
  4795. return;
  4796. /*
  4797. * Swap faults will attempt to charge the same page multiple
  4798. * times. But reuse_swap_page() might have removed the page
  4799. * from swapcache already, so we can't check PageSwapCache().
  4800. */
  4801. if (!memcg)
  4802. return;
  4803. if (PageTransHuge(page)) {
  4804. nr_pages <<= compound_order(page);
  4805. VM_BUG_ON_PAGE(!PageTransHuge(page), page);
  4806. }
  4807. cancel_charge(memcg, nr_pages);
  4808. }
  4809. static void uncharge_batch(struct mem_cgroup *memcg, unsigned long pgpgout,
  4810. unsigned long nr_anon, unsigned long nr_file,
  4811. unsigned long nr_huge, struct page *dummy_page)
  4812. {
  4813. unsigned long nr_pages = nr_anon + nr_file;
  4814. unsigned long flags;
  4815. if (!mem_cgroup_is_root(memcg)) {
  4816. page_counter_uncharge(&memcg->memory, nr_pages);
  4817. if (do_swap_account)
  4818. page_counter_uncharge(&memcg->memsw, nr_pages);
  4819. memcg_oom_recover(memcg);
  4820. }
  4821. local_irq_save(flags);
  4822. __this_cpu_sub(memcg->stat->count[MEM_CGROUP_STAT_RSS], nr_anon);
  4823. __this_cpu_sub(memcg->stat->count[MEM_CGROUP_STAT_CACHE], nr_file);
  4824. __this_cpu_sub(memcg->stat->count[MEM_CGROUP_STAT_RSS_HUGE], nr_huge);
  4825. __this_cpu_add(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGOUT], pgpgout);
  4826. __this_cpu_add(memcg->stat->nr_page_events, nr_pages);
  4827. memcg_check_events(memcg, dummy_page);
  4828. local_irq_restore(flags);
  4829. if (!mem_cgroup_is_root(memcg))
  4830. css_put_many(&memcg->css, nr_pages);
  4831. }
  4832. static void uncharge_list(struct list_head *page_list)
  4833. {
  4834. struct mem_cgroup *memcg = NULL;
  4835. unsigned long nr_anon = 0;
  4836. unsigned long nr_file = 0;
  4837. unsigned long nr_huge = 0;
  4838. unsigned long pgpgout = 0;
  4839. struct list_head *next;
  4840. struct page *page;
  4841. next = page_list->next;
  4842. do {
  4843. unsigned int nr_pages = 1;
  4844. page = list_entry(next, struct page, lru);
  4845. next = page->lru.next;
  4846. VM_BUG_ON_PAGE(PageLRU(page), page);
  4847. VM_BUG_ON_PAGE(page_count(page), page);
  4848. if (!page->mem_cgroup)
  4849. continue;
  4850. /*
  4851. * Nobody should be changing or seriously looking at
  4852. * page->mem_cgroup at this point, we have fully
  4853. * exclusive access to the page.
  4854. */
  4855. if (memcg != page->mem_cgroup) {
  4856. if (memcg) {
  4857. uncharge_batch(memcg, pgpgout, nr_anon, nr_file,
  4858. nr_huge, page);
  4859. pgpgout = nr_anon = nr_file = nr_huge = 0;
  4860. }
  4861. memcg = page->mem_cgroup;
  4862. }
  4863. if (PageTransHuge(page)) {
  4864. nr_pages <<= compound_order(page);
  4865. VM_BUG_ON_PAGE(!PageTransHuge(page), page);
  4866. nr_huge += nr_pages;
  4867. }
  4868. if (PageAnon(page))
  4869. nr_anon += nr_pages;
  4870. else
  4871. nr_file += nr_pages;
  4872. page->mem_cgroup = NULL;
  4873. pgpgout++;
  4874. } while (next != page_list);
  4875. if (memcg)
  4876. uncharge_batch(memcg, pgpgout, nr_anon, nr_file,
  4877. nr_huge, page);
  4878. }
  4879. /**
  4880. * mem_cgroup_uncharge - uncharge a page
  4881. * @page: page to uncharge
  4882. *
  4883. * Uncharge a page previously charged with mem_cgroup_try_charge() and
  4884. * mem_cgroup_commit_charge().
  4885. */
  4886. void mem_cgroup_uncharge(struct page *page)
  4887. {
  4888. if (mem_cgroup_disabled())
  4889. return;
  4890. /* Don't touch page->lru of any random page, pre-check: */
  4891. if (!page->mem_cgroup)
  4892. return;
  4893. INIT_LIST_HEAD(&page->lru);
  4894. uncharge_list(&page->lru);
  4895. }
  4896. /**
  4897. * mem_cgroup_uncharge_list - uncharge a list of page
  4898. * @page_list: list of pages to uncharge
  4899. *
  4900. * Uncharge a list of pages previously charged with
  4901. * mem_cgroup_try_charge() and mem_cgroup_commit_charge().
  4902. */
  4903. void mem_cgroup_uncharge_list(struct list_head *page_list)
  4904. {
  4905. if (mem_cgroup_disabled())
  4906. return;
  4907. if (!list_empty(page_list))
  4908. uncharge_list(page_list);
  4909. }
  4910. /**
  4911. * mem_cgroup_migrate - migrate a charge to another page
  4912. * @oldpage: currently charged page
  4913. * @newpage: page to transfer the charge to
  4914. * @lrucare: either or both pages might be on the LRU already
  4915. *
  4916. * Migrate the charge from @oldpage to @newpage.
  4917. *
  4918. * Both pages must be locked, @newpage->mapping must be set up.
  4919. */
  4920. void mem_cgroup_migrate(struct page *oldpage, struct page *newpage,
  4921. bool lrucare)
  4922. {
  4923. struct mem_cgroup *memcg;
  4924. int isolated;
  4925. VM_BUG_ON_PAGE(!PageLocked(oldpage), oldpage);
  4926. VM_BUG_ON_PAGE(!PageLocked(newpage), newpage);
  4927. VM_BUG_ON_PAGE(!lrucare && PageLRU(oldpage), oldpage);
  4928. VM_BUG_ON_PAGE(!lrucare && PageLRU(newpage), newpage);
  4929. VM_BUG_ON_PAGE(PageAnon(oldpage) != PageAnon(newpage), newpage);
  4930. VM_BUG_ON_PAGE(PageTransHuge(oldpage) != PageTransHuge(newpage),
  4931. newpage);
  4932. if (mem_cgroup_disabled())
  4933. return;
  4934. /* Page cache replacement: new page already charged? */
  4935. if (newpage->mem_cgroup)
  4936. return;
  4937. /*
  4938. * Swapcache readahead pages can get migrated before being
  4939. * charged, and migration from compaction can happen to an
  4940. * uncharged page when the PFN walker finds a page that
  4941. * reclaim just put back on the LRU but has not released yet.
  4942. */
  4943. memcg = oldpage->mem_cgroup;
  4944. if (!memcg)
  4945. return;
  4946. if (lrucare)
  4947. lock_page_lru(oldpage, &isolated);
  4948. oldpage->mem_cgroup = NULL;
  4949. if (lrucare)
  4950. unlock_page_lru(oldpage, isolated);
  4951. commit_charge(newpage, memcg, lrucare);
  4952. }
  4953. /*
  4954. * subsys_initcall() for memory controller.
  4955. *
  4956. * Some parts like hotcpu_notifier() have to be initialized from this context
  4957. * because of lock dependencies (cgroup_lock -> cpu hotplug) but basically
  4958. * everything that doesn't depend on a specific mem_cgroup structure should
  4959. * be initialized from here.
  4960. */
  4961. static int __init mem_cgroup_init(void)
  4962. {
  4963. int cpu, node;
  4964. hotcpu_notifier(memcg_cpu_hotplug_callback, 0);
  4965. for_each_possible_cpu(cpu)
  4966. INIT_WORK(&per_cpu_ptr(&memcg_stock, cpu)->work,
  4967. drain_local_stock);
  4968. for_each_node(node) {
  4969. struct mem_cgroup_tree_per_node *rtpn;
  4970. int zone;
  4971. rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL,
  4972. node_online(node) ? node : NUMA_NO_NODE);
  4973. for (zone = 0; zone < MAX_NR_ZONES; zone++) {
  4974. struct mem_cgroup_tree_per_zone *rtpz;
  4975. rtpz = &rtpn->rb_tree_per_zone[zone];
  4976. rtpz->rb_root = RB_ROOT;
  4977. spin_lock_init(&rtpz->lock);
  4978. }
  4979. soft_limit_tree.rb_tree_per_node[node] = rtpn;
  4980. }
  4981. return 0;
  4982. }
  4983. subsys_initcall(mem_cgroup_init);
  4984. #ifdef CONFIG_MEMCG_SWAP
  4985. /**
  4986. * mem_cgroup_swapout - transfer a memsw charge to swap
  4987. * @page: page whose memsw charge to transfer
  4988. * @entry: swap entry to move the charge to
  4989. *
  4990. * Transfer the memsw charge of @page to @entry.
  4991. */
  4992. void mem_cgroup_swapout(struct page *page, swp_entry_t entry)
  4993. {
  4994. struct mem_cgroup *memcg;
  4995. unsigned short oldid;
  4996. VM_BUG_ON_PAGE(PageLRU(page), page);
  4997. VM_BUG_ON_PAGE(page_count(page), page);
  4998. if (!do_swap_account)
  4999. return;
  5000. memcg = page->mem_cgroup;
  5001. /* Readahead page, never charged */
  5002. if (!memcg)
  5003. return;
  5004. oldid = swap_cgroup_record(entry, mem_cgroup_id(memcg));
  5005. VM_BUG_ON_PAGE(oldid, page);
  5006. mem_cgroup_swap_statistics(memcg, true);
  5007. page->mem_cgroup = NULL;
  5008. if (!mem_cgroup_is_root(memcg))
  5009. page_counter_uncharge(&memcg->memory, 1);
  5010. /* XXX: caller holds IRQ-safe mapping->tree_lock */
  5011. VM_BUG_ON(!irqs_disabled());
  5012. mem_cgroup_charge_statistics(memcg, page, -1);
  5013. memcg_check_events(memcg, page);
  5014. }
  5015. /**
  5016. * mem_cgroup_uncharge_swap - uncharge a swap entry
  5017. * @entry: swap entry to uncharge
  5018. *
  5019. * Drop the memsw charge associated with @entry.
  5020. */
  5021. void mem_cgroup_uncharge_swap(swp_entry_t entry)
  5022. {
  5023. struct mem_cgroup *memcg;
  5024. unsigned short id;
  5025. if (!do_swap_account)
  5026. return;
  5027. id = swap_cgroup_record(entry, 0);
  5028. rcu_read_lock();
  5029. memcg = mem_cgroup_lookup(id);
  5030. if (memcg) {
  5031. if (!mem_cgroup_is_root(memcg))
  5032. page_counter_uncharge(&memcg->memsw, 1);
  5033. mem_cgroup_swap_statistics(memcg, false);
  5034. css_put(&memcg->css);
  5035. }
  5036. rcu_read_unlock();
  5037. }
  5038. /* for remember boot option*/
  5039. #ifdef CONFIG_MEMCG_SWAP_ENABLED
  5040. static int really_do_swap_account __initdata = 1;
  5041. #else
  5042. static int really_do_swap_account __initdata;
  5043. #endif
  5044. static int __init enable_swap_account(char *s)
  5045. {
  5046. if (!strcmp(s, "1"))
  5047. really_do_swap_account = 1;
  5048. else if (!strcmp(s, "0"))
  5049. really_do_swap_account = 0;
  5050. return 1;
  5051. }
  5052. __setup("swapaccount=", enable_swap_account);
  5053. static struct cftype memsw_cgroup_files[] = {
  5054. {
  5055. .name = "memsw.usage_in_bytes",
  5056. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
  5057. .read_u64 = mem_cgroup_read_u64,
  5058. },
  5059. {
  5060. .name = "memsw.max_usage_in_bytes",
  5061. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
  5062. .write = mem_cgroup_reset,
  5063. .read_u64 = mem_cgroup_read_u64,
  5064. },
  5065. {
  5066. .name = "memsw.limit_in_bytes",
  5067. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
  5068. .write = mem_cgroup_write,
  5069. .read_u64 = mem_cgroup_read_u64,
  5070. },
  5071. {
  5072. .name = "memsw.failcnt",
  5073. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
  5074. .write = mem_cgroup_reset,
  5075. .read_u64 = mem_cgroup_read_u64,
  5076. },
  5077. { }, /* terminate */
  5078. };
  5079. static int __init mem_cgroup_swap_init(void)
  5080. {
  5081. if (!mem_cgroup_disabled() && really_do_swap_account) {
  5082. do_swap_account = 1;
  5083. WARN_ON(cgroup_add_legacy_cftypes(&memory_cgrp_subsys,
  5084. memsw_cgroup_files));
  5085. }
  5086. return 0;
  5087. }
  5088. subsys_initcall(mem_cgroup_swap_init);
  5089. #endif /* CONFIG_MEMCG_SWAP */