memcontrol.c 150 KB

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