memcontrol.c 149 KB

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