memcontrol.c 162 KB

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