memcontrol.c 157 KB

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