memcontrol.c 172 KB

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