memcontrol.c 147 KB

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