memcontrol.c 148 KB

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