memcontrol.c 170 KB

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