memcontrol.c 155 KB

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