memcontrol.c 173 KB

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