memcontrol.c 151 KB

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