memcontrol.c 152 KB

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