memcontrol.c 156 KB

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