memcontrol.c 150 KB

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