memcontrol.c 174 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652
  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. static inline bool memcg_can_account_kmem(struct mem_cgroup *memcg)
  2413. {
  2414. return !mem_cgroup_disabled() && !mem_cgroup_is_root(memcg) &&
  2415. memcg_kmem_is_active(memcg);
  2416. }
  2417. /*
  2418. * This is a bit cumbersome, but it is rarely used and avoids a backpointer
  2419. * in the memcg_cache_params struct.
  2420. */
  2421. static struct kmem_cache *memcg_params_to_cache(struct memcg_cache_params *p)
  2422. {
  2423. struct kmem_cache *cachep;
  2424. VM_BUG_ON(p->is_root_cache);
  2425. cachep = p->root_cache;
  2426. return cache_from_memcg_idx(cachep, memcg_cache_id(p->memcg));
  2427. }
  2428. #ifdef CONFIG_SLABINFO
  2429. static int mem_cgroup_slabinfo_read(struct seq_file *m, void *v)
  2430. {
  2431. struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
  2432. struct memcg_cache_params *params;
  2433. if (!memcg_can_account_kmem(memcg))
  2434. return -EIO;
  2435. print_slabinfo_header(m);
  2436. mutex_lock(&memcg_slab_mutex);
  2437. list_for_each_entry(params, &memcg->memcg_slab_caches, list)
  2438. cache_show(memcg_params_to_cache(params), m);
  2439. mutex_unlock(&memcg_slab_mutex);
  2440. return 0;
  2441. }
  2442. #endif
  2443. static int memcg_charge_kmem(struct mem_cgroup *memcg, gfp_t gfp, u64 size)
  2444. {
  2445. struct res_counter *fail_res;
  2446. int ret = 0;
  2447. ret = res_counter_charge(&memcg->kmem, size, &fail_res);
  2448. if (ret)
  2449. return ret;
  2450. ret = try_charge(memcg, gfp, size >> PAGE_SHIFT);
  2451. if (ret == -EINTR) {
  2452. /*
  2453. * try_charge() chose to bypass to root due to OOM kill or
  2454. * fatal signal. Since our only options are to either fail
  2455. * the allocation or charge it to this cgroup, do it as a
  2456. * temporary condition. But we can't fail. From a kmem/slab
  2457. * perspective, the cache has already been selected, by
  2458. * mem_cgroup_kmem_get_cache(), so it is too late to change
  2459. * our minds.
  2460. *
  2461. * This condition will only trigger if the task entered
  2462. * memcg_charge_kmem in a sane state, but was OOM-killed
  2463. * during try_charge() above. Tasks that were already dying
  2464. * when the allocation triggers should have been already
  2465. * directed to the root cgroup in memcontrol.h
  2466. */
  2467. res_counter_charge_nofail(&memcg->res, size, &fail_res);
  2468. if (do_swap_account)
  2469. res_counter_charge_nofail(&memcg->memsw, size,
  2470. &fail_res);
  2471. ret = 0;
  2472. } else if (ret)
  2473. res_counter_uncharge(&memcg->kmem, size);
  2474. return ret;
  2475. }
  2476. static void memcg_uncharge_kmem(struct mem_cgroup *memcg, u64 size)
  2477. {
  2478. res_counter_uncharge(&memcg->res, size);
  2479. if (do_swap_account)
  2480. res_counter_uncharge(&memcg->memsw, size);
  2481. /* Not down to 0 */
  2482. if (res_counter_uncharge(&memcg->kmem, size))
  2483. return;
  2484. /*
  2485. * Releases a reference taken in kmem_cgroup_css_offline in case
  2486. * this last uncharge is racing with the offlining code or it is
  2487. * outliving the memcg existence.
  2488. *
  2489. * The memory barrier imposed by test&clear is paired with the
  2490. * explicit one in memcg_kmem_mark_dead().
  2491. */
  2492. if (memcg_kmem_test_and_clear_dead(memcg))
  2493. css_put(&memcg->css);
  2494. }
  2495. /*
  2496. * helper for acessing a memcg's index. It will be used as an index in the
  2497. * child cache array in kmem_cache, and also to derive its name. This function
  2498. * will return -1 when this is not a kmem-limited memcg.
  2499. */
  2500. int memcg_cache_id(struct mem_cgroup *memcg)
  2501. {
  2502. return memcg ? memcg->kmemcg_id : -1;
  2503. }
  2504. static int memcg_alloc_cache_id(void)
  2505. {
  2506. int id, size;
  2507. int err;
  2508. id = ida_simple_get(&kmem_limited_groups,
  2509. 0, MEMCG_CACHES_MAX_SIZE, GFP_KERNEL);
  2510. if (id < 0)
  2511. return id;
  2512. if (id < memcg_limited_groups_array_size)
  2513. return id;
  2514. /*
  2515. * There's no space for the new id in memcg_caches arrays,
  2516. * so we have to grow them.
  2517. */
  2518. size = 2 * (id + 1);
  2519. if (size < MEMCG_CACHES_MIN_SIZE)
  2520. size = MEMCG_CACHES_MIN_SIZE;
  2521. else if (size > MEMCG_CACHES_MAX_SIZE)
  2522. size = MEMCG_CACHES_MAX_SIZE;
  2523. mutex_lock(&memcg_slab_mutex);
  2524. err = memcg_update_all_caches(size);
  2525. mutex_unlock(&memcg_slab_mutex);
  2526. if (err) {
  2527. ida_simple_remove(&kmem_limited_groups, id);
  2528. return err;
  2529. }
  2530. return id;
  2531. }
  2532. static void memcg_free_cache_id(int id)
  2533. {
  2534. ida_simple_remove(&kmem_limited_groups, id);
  2535. }
  2536. /*
  2537. * We should update the current array size iff all caches updates succeed. This
  2538. * can only be done from the slab side. The slab mutex needs to be held when
  2539. * calling this.
  2540. */
  2541. void memcg_update_array_size(int num)
  2542. {
  2543. memcg_limited_groups_array_size = num;
  2544. }
  2545. static void memcg_register_cache(struct mem_cgroup *memcg,
  2546. struct kmem_cache *root_cache)
  2547. {
  2548. static char memcg_name_buf[NAME_MAX + 1]; /* protected by
  2549. memcg_slab_mutex */
  2550. struct kmem_cache *cachep;
  2551. int id;
  2552. lockdep_assert_held(&memcg_slab_mutex);
  2553. id = memcg_cache_id(memcg);
  2554. /*
  2555. * Since per-memcg caches are created asynchronously on first
  2556. * allocation (see memcg_kmem_get_cache()), several threads can try to
  2557. * create the same cache, but only one of them may succeed.
  2558. */
  2559. if (cache_from_memcg_idx(root_cache, id))
  2560. return;
  2561. cgroup_name(memcg->css.cgroup, memcg_name_buf, NAME_MAX + 1);
  2562. cachep = memcg_create_kmem_cache(memcg, root_cache, memcg_name_buf);
  2563. /*
  2564. * If we could not create a memcg cache, do not complain, because
  2565. * that's not critical at all as we can always proceed with the root
  2566. * cache.
  2567. */
  2568. if (!cachep)
  2569. return;
  2570. css_get(&memcg->css);
  2571. list_add(&cachep->memcg_params->list, &memcg->memcg_slab_caches);
  2572. /*
  2573. * Since readers won't lock (see cache_from_memcg_idx()), we need a
  2574. * barrier here to ensure nobody will see the kmem_cache partially
  2575. * initialized.
  2576. */
  2577. smp_wmb();
  2578. BUG_ON(root_cache->memcg_params->memcg_caches[id]);
  2579. root_cache->memcg_params->memcg_caches[id] = cachep;
  2580. }
  2581. static void memcg_unregister_cache(struct kmem_cache *cachep)
  2582. {
  2583. struct kmem_cache *root_cache;
  2584. struct mem_cgroup *memcg;
  2585. int id;
  2586. lockdep_assert_held(&memcg_slab_mutex);
  2587. BUG_ON(is_root_cache(cachep));
  2588. root_cache = cachep->memcg_params->root_cache;
  2589. memcg = cachep->memcg_params->memcg;
  2590. id = memcg_cache_id(memcg);
  2591. BUG_ON(root_cache->memcg_params->memcg_caches[id] != cachep);
  2592. root_cache->memcg_params->memcg_caches[id] = NULL;
  2593. list_del(&cachep->memcg_params->list);
  2594. kmem_cache_destroy(cachep);
  2595. /* drop the reference taken in memcg_register_cache */
  2596. css_put(&memcg->css);
  2597. }
  2598. /*
  2599. * During the creation a new cache, we need to disable our accounting mechanism
  2600. * altogether. This is true even if we are not creating, but rather just
  2601. * enqueing new caches to be created.
  2602. *
  2603. * This is because that process will trigger allocations; some visible, like
  2604. * explicit kmallocs to auxiliary data structures, name strings and internal
  2605. * cache structures; some well concealed, like INIT_WORK() that can allocate
  2606. * objects during debug.
  2607. *
  2608. * If any allocation happens during memcg_kmem_get_cache, we will recurse back
  2609. * to it. This may not be a bounded recursion: since the first cache creation
  2610. * failed to complete (waiting on the allocation), we'll just try to create the
  2611. * cache again, failing at the same point.
  2612. *
  2613. * memcg_kmem_get_cache is prepared to abort after seeing a positive count of
  2614. * memcg_kmem_skip_account. So we enclose anything that might allocate memory
  2615. * inside the following two functions.
  2616. */
  2617. static inline void memcg_stop_kmem_account(void)
  2618. {
  2619. VM_BUG_ON(!current->mm);
  2620. current->memcg_kmem_skip_account++;
  2621. }
  2622. static inline void memcg_resume_kmem_account(void)
  2623. {
  2624. VM_BUG_ON(!current->mm);
  2625. current->memcg_kmem_skip_account--;
  2626. }
  2627. int __memcg_cleanup_cache_params(struct kmem_cache *s)
  2628. {
  2629. struct kmem_cache *c;
  2630. int i, failed = 0;
  2631. mutex_lock(&memcg_slab_mutex);
  2632. for_each_memcg_cache_index(i) {
  2633. c = cache_from_memcg_idx(s, i);
  2634. if (!c)
  2635. continue;
  2636. memcg_unregister_cache(c);
  2637. if (cache_from_memcg_idx(s, i))
  2638. failed++;
  2639. }
  2640. mutex_unlock(&memcg_slab_mutex);
  2641. return failed;
  2642. }
  2643. static void memcg_unregister_all_caches(struct mem_cgroup *memcg)
  2644. {
  2645. struct kmem_cache *cachep;
  2646. struct memcg_cache_params *params, *tmp;
  2647. if (!memcg_kmem_is_active(memcg))
  2648. return;
  2649. mutex_lock(&memcg_slab_mutex);
  2650. list_for_each_entry_safe(params, tmp, &memcg->memcg_slab_caches, list) {
  2651. cachep = memcg_params_to_cache(params);
  2652. kmem_cache_shrink(cachep);
  2653. if (atomic_read(&cachep->memcg_params->nr_pages) == 0)
  2654. memcg_unregister_cache(cachep);
  2655. }
  2656. mutex_unlock(&memcg_slab_mutex);
  2657. }
  2658. struct memcg_register_cache_work {
  2659. struct mem_cgroup *memcg;
  2660. struct kmem_cache *cachep;
  2661. struct work_struct work;
  2662. };
  2663. static void memcg_register_cache_func(struct work_struct *w)
  2664. {
  2665. struct memcg_register_cache_work *cw =
  2666. container_of(w, struct memcg_register_cache_work, work);
  2667. struct mem_cgroup *memcg = cw->memcg;
  2668. struct kmem_cache *cachep = cw->cachep;
  2669. mutex_lock(&memcg_slab_mutex);
  2670. memcg_register_cache(memcg, cachep);
  2671. mutex_unlock(&memcg_slab_mutex);
  2672. css_put(&memcg->css);
  2673. kfree(cw);
  2674. }
  2675. /*
  2676. * Enqueue the creation of a per-memcg kmem_cache.
  2677. */
  2678. static void __memcg_schedule_register_cache(struct mem_cgroup *memcg,
  2679. struct kmem_cache *cachep)
  2680. {
  2681. struct memcg_register_cache_work *cw;
  2682. cw = kmalloc(sizeof(*cw), GFP_NOWAIT);
  2683. if (cw == NULL) {
  2684. css_put(&memcg->css);
  2685. return;
  2686. }
  2687. cw->memcg = memcg;
  2688. cw->cachep = cachep;
  2689. INIT_WORK(&cw->work, memcg_register_cache_func);
  2690. schedule_work(&cw->work);
  2691. }
  2692. static void memcg_schedule_register_cache(struct mem_cgroup *memcg,
  2693. struct kmem_cache *cachep)
  2694. {
  2695. /*
  2696. * We need to stop accounting when we kmalloc, because if the
  2697. * corresponding kmalloc cache is not yet created, the first allocation
  2698. * in __memcg_schedule_register_cache will recurse.
  2699. *
  2700. * However, it is better to enclose the whole function. Depending on
  2701. * the debugging options enabled, INIT_WORK(), for instance, can
  2702. * trigger an allocation. This too, will make us recurse. Because at
  2703. * this point we can't allow ourselves back into memcg_kmem_get_cache,
  2704. * the safest choice is to do it like this, wrapping the whole function.
  2705. */
  2706. memcg_stop_kmem_account();
  2707. __memcg_schedule_register_cache(memcg, cachep);
  2708. memcg_resume_kmem_account();
  2709. }
  2710. int __memcg_charge_slab(struct kmem_cache *cachep, gfp_t gfp, int order)
  2711. {
  2712. int res;
  2713. res = memcg_charge_kmem(cachep->memcg_params->memcg, gfp,
  2714. PAGE_SIZE << order);
  2715. if (!res)
  2716. atomic_add(1 << order, &cachep->memcg_params->nr_pages);
  2717. return res;
  2718. }
  2719. void __memcg_uncharge_slab(struct kmem_cache *cachep, int order)
  2720. {
  2721. memcg_uncharge_kmem(cachep->memcg_params->memcg, PAGE_SIZE << order);
  2722. atomic_sub(1 << order, &cachep->memcg_params->nr_pages);
  2723. }
  2724. /*
  2725. * Return the kmem_cache we're supposed to use for a slab allocation.
  2726. * We try to use the current memcg's version of the cache.
  2727. *
  2728. * If the cache does not exist yet, if we are the first user of it,
  2729. * we either create it immediately, if possible, or create it asynchronously
  2730. * in a workqueue.
  2731. * In the latter case, we will let the current allocation go through with
  2732. * the original cache.
  2733. *
  2734. * Can't be called in interrupt context or from kernel threads.
  2735. * This function needs to be called with rcu_read_lock() held.
  2736. */
  2737. struct kmem_cache *__memcg_kmem_get_cache(struct kmem_cache *cachep,
  2738. gfp_t gfp)
  2739. {
  2740. struct mem_cgroup *memcg;
  2741. struct kmem_cache *memcg_cachep;
  2742. VM_BUG_ON(!cachep->memcg_params);
  2743. VM_BUG_ON(!cachep->memcg_params->is_root_cache);
  2744. if (!current->mm || current->memcg_kmem_skip_account)
  2745. return cachep;
  2746. rcu_read_lock();
  2747. memcg = mem_cgroup_from_task(rcu_dereference(current->mm->owner));
  2748. if (!memcg_can_account_kmem(memcg))
  2749. goto out;
  2750. memcg_cachep = cache_from_memcg_idx(cachep, memcg_cache_id(memcg));
  2751. if (likely(memcg_cachep)) {
  2752. cachep = memcg_cachep;
  2753. goto out;
  2754. }
  2755. /* The corresponding put will be done in the workqueue. */
  2756. if (!css_tryget_online(&memcg->css))
  2757. goto out;
  2758. rcu_read_unlock();
  2759. /*
  2760. * If we are in a safe context (can wait, and not in interrupt
  2761. * context), we could be be predictable and return right away.
  2762. * This would guarantee that the allocation being performed
  2763. * already belongs in the new cache.
  2764. *
  2765. * However, there are some clashes that can arrive from locking.
  2766. * For instance, because we acquire the slab_mutex while doing
  2767. * memcg_create_kmem_cache, this means no further allocation
  2768. * could happen with the slab_mutex held. So it's better to
  2769. * defer everything.
  2770. */
  2771. memcg_schedule_register_cache(memcg, cachep);
  2772. return cachep;
  2773. out:
  2774. rcu_read_unlock();
  2775. return cachep;
  2776. }
  2777. /*
  2778. * We need to verify if the allocation against current->mm->owner's memcg is
  2779. * possible for the given order. But the page is not allocated yet, so we'll
  2780. * need a further commit step to do the final arrangements.
  2781. *
  2782. * It is possible for the task to switch cgroups in this mean time, so at
  2783. * commit time, we can't rely on task conversion any longer. We'll then use
  2784. * the handle argument to return to the caller which cgroup we should commit
  2785. * against. We could also return the memcg directly and avoid the pointer
  2786. * passing, but a boolean return value gives better semantics considering
  2787. * the compiled-out case as well.
  2788. *
  2789. * Returning true means the allocation is possible.
  2790. */
  2791. bool
  2792. __memcg_kmem_newpage_charge(gfp_t gfp, struct mem_cgroup **_memcg, int order)
  2793. {
  2794. struct mem_cgroup *memcg;
  2795. int ret;
  2796. *_memcg = NULL;
  2797. /*
  2798. * Disabling accounting is only relevant for some specific memcg
  2799. * internal allocations. Therefore we would initially not have such
  2800. * check here, since direct calls to the page allocator that are
  2801. * accounted to kmemcg (alloc_kmem_pages and friends) only happen
  2802. * outside memcg core. We are mostly concerned with cache allocations,
  2803. * and by having this test at memcg_kmem_get_cache, we are already able
  2804. * to relay the allocation to the root cache and bypass the memcg cache
  2805. * altogether.
  2806. *
  2807. * There is one exception, though: the SLUB allocator does not create
  2808. * large order caches, but rather service large kmallocs directly from
  2809. * the page allocator. Therefore, the following sequence when backed by
  2810. * the SLUB allocator:
  2811. *
  2812. * memcg_stop_kmem_account();
  2813. * kmalloc(<large_number>)
  2814. * memcg_resume_kmem_account();
  2815. *
  2816. * would effectively ignore the fact that we should skip accounting,
  2817. * since it will drive us directly to this function without passing
  2818. * through the cache selector memcg_kmem_get_cache. Such large
  2819. * allocations are extremely rare but can happen, for instance, for the
  2820. * cache arrays. We bring this test here.
  2821. */
  2822. if (!current->mm || current->memcg_kmem_skip_account)
  2823. return true;
  2824. memcg = get_mem_cgroup_from_mm(current->mm);
  2825. if (!memcg_can_account_kmem(memcg)) {
  2826. css_put(&memcg->css);
  2827. return true;
  2828. }
  2829. ret = memcg_charge_kmem(memcg, gfp, PAGE_SIZE << order);
  2830. if (!ret)
  2831. *_memcg = memcg;
  2832. css_put(&memcg->css);
  2833. return (ret == 0);
  2834. }
  2835. void __memcg_kmem_commit_charge(struct page *page, struct mem_cgroup *memcg,
  2836. int order)
  2837. {
  2838. struct page_cgroup *pc;
  2839. VM_BUG_ON(mem_cgroup_is_root(memcg));
  2840. /* The page allocation failed. Revert */
  2841. if (!page) {
  2842. memcg_uncharge_kmem(memcg, PAGE_SIZE << order);
  2843. return;
  2844. }
  2845. /*
  2846. * The page is freshly allocated and not visible to any
  2847. * outside callers yet. Set up pc non-atomically.
  2848. */
  2849. pc = lookup_page_cgroup(page);
  2850. pc->mem_cgroup = memcg;
  2851. pc->flags = PCG_USED;
  2852. }
  2853. void __memcg_kmem_uncharge_pages(struct page *page, int order)
  2854. {
  2855. struct mem_cgroup *memcg = NULL;
  2856. struct page_cgroup *pc;
  2857. pc = lookup_page_cgroup(page);
  2858. if (!PageCgroupUsed(pc))
  2859. return;
  2860. memcg = pc->mem_cgroup;
  2861. pc->flags = 0;
  2862. /*
  2863. * We trust that only if there is a memcg associated with the page, it
  2864. * is a valid allocation
  2865. */
  2866. if (!memcg)
  2867. return;
  2868. VM_BUG_ON_PAGE(mem_cgroup_is_root(memcg), page);
  2869. memcg_uncharge_kmem(memcg, PAGE_SIZE << order);
  2870. }
  2871. #else
  2872. static inline void memcg_unregister_all_caches(struct mem_cgroup *memcg)
  2873. {
  2874. }
  2875. #endif /* CONFIG_MEMCG_KMEM */
  2876. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  2877. /*
  2878. * Because tail pages are not marked as "used", set it. We're under
  2879. * zone->lru_lock, 'splitting on pmd' and compound_lock.
  2880. * charge/uncharge will be never happen and move_account() is done under
  2881. * compound_lock(), so we don't have to take care of races.
  2882. */
  2883. void mem_cgroup_split_huge_fixup(struct page *head)
  2884. {
  2885. struct page_cgroup *head_pc = lookup_page_cgroup(head);
  2886. struct page_cgroup *pc;
  2887. struct mem_cgroup *memcg;
  2888. int i;
  2889. if (mem_cgroup_disabled())
  2890. return;
  2891. memcg = head_pc->mem_cgroup;
  2892. for (i = 1; i < HPAGE_PMD_NR; i++) {
  2893. pc = head_pc + i;
  2894. pc->mem_cgroup = memcg;
  2895. pc->flags = head_pc->flags;
  2896. }
  2897. __this_cpu_sub(memcg->stat->count[MEM_CGROUP_STAT_RSS_HUGE],
  2898. HPAGE_PMD_NR);
  2899. }
  2900. #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
  2901. /**
  2902. * mem_cgroup_move_account - move account of the page
  2903. * @page: the page
  2904. * @nr_pages: number of regular pages (>1 for huge pages)
  2905. * @pc: page_cgroup of the page.
  2906. * @from: mem_cgroup which the page is moved from.
  2907. * @to: mem_cgroup which the page is moved to. @from != @to.
  2908. *
  2909. * The caller must confirm following.
  2910. * - page is not on LRU (isolate_page() is useful.)
  2911. * - compound_lock is held when nr_pages > 1
  2912. *
  2913. * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
  2914. * from old cgroup.
  2915. */
  2916. static int mem_cgroup_move_account(struct page *page,
  2917. unsigned int nr_pages,
  2918. struct page_cgroup *pc,
  2919. struct mem_cgroup *from,
  2920. struct mem_cgroup *to)
  2921. {
  2922. unsigned long flags;
  2923. int ret;
  2924. VM_BUG_ON(from == to);
  2925. VM_BUG_ON_PAGE(PageLRU(page), page);
  2926. /*
  2927. * The page is isolated from LRU. So, collapse function
  2928. * will not handle this page. But page splitting can happen.
  2929. * Do this check under compound_page_lock(). The caller should
  2930. * hold it.
  2931. */
  2932. ret = -EBUSY;
  2933. if (nr_pages > 1 && !PageTransHuge(page))
  2934. goto out;
  2935. /*
  2936. * Prevent mem_cgroup_migrate() from looking at pc->mem_cgroup
  2937. * of its source page while we change it: page migration takes
  2938. * both pages off the LRU, but page cache replacement doesn't.
  2939. */
  2940. if (!trylock_page(page))
  2941. goto out;
  2942. ret = -EINVAL;
  2943. if (!PageCgroupUsed(pc) || pc->mem_cgroup != from)
  2944. goto out_unlock;
  2945. move_lock_mem_cgroup(from, &flags);
  2946. if (!PageAnon(page) && page_mapped(page)) {
  2947. __this_cpu_sub(from->stat->count[MEM_CGROUP_STAT_FILE_MAPPED],
  2948. nr_pages);
  2949. __this_cpu_add(to->stat->count[MEM_CGROUP_STAT_FILE_MAPPED],
  2950. nr_pages);
  2951. }
  2952. if (PageWriteback(page)) {
  2953. __this_cpu_sub(from->stat->count[MEM_CGROUP_STAT_WRITEBACK],
  2954. nr_pages);
  2955. __this_cpu_add(to->stat->count[MEM_CGROUP_STAT_WRITEBACK],
  2956. nr_pages);
  2957. }
  2958. /*
  2959. * It is safe to change pc->mem_cgroup here because the page
  2960. * is referenced, charged, and isolated - we can't race with
  2961. * uncharging, charging, migration, or LRU putback.
  2962. */
  2963. /* caller should have done css_get */
  2964. pc->mem_cgroup = to;
  2965. move_unlock_mem_cgroup(from, &flags);
  2966. ret = 0;
  2967. local_irq_disable();
  2968. mem_cgroup_charge_statistics(to, page, nr_pages);
  2969. memcg_check_events(to, page);
  2970. mem_cgroup_charge_statistics(from, page, -nr_pages);
  2971. memcg_check_events(from, page);
  2972. local_irq_enable();
  2973. out_unlock:
  2974. unlock_page(page);
  2975. out:
  2976. return ret;
  2977. }
  2978. /**
  2979. * mem_cgroup_move_parent - moves page to the parent group
  2980. * @page: the page to move
  2981. * @pc: page_cgroup of the page
  2982. * @child: page's cgroup
  2983. *
  2984. * move charges to its parent or the root cgroup if the group has no
  2985. * parent (aka use_hierarchy==0).
  2986. * Although this might fail (get_page_unless_zero, isolate_lru_page or
  2987. * mem_cgroup_move_account fails) the failure is always temporary and
  2988. * it signals a race with a page removal/uncharge or migration. In the
  2989. * first case the page is on the way out and it will vanish from the LRU
  2990. * on the next attempt and the call should be retried later.
  2991. * Isolation from the LRU fails only if page has been isolated from
  2992. * the LRU since we looked at it and that usually means either global
  2993. * reclaim or migration going on. The page will either get back to the
  2994. * LRU or vanish.
  2995. * Finaly mem_cgroup_move_account fails only if the page got uncharged
  2996. * (!PageCgroupUsed) or moved to a different group. The page will
  2997. * disappear in the next attempt.
  2998. */
  2999. static int mem_cgroup_move_parent(struct page *page,
  3000. struct page_cgroup *pc,
  3001. struct mem_cgroup *child)
  3002. {
  3003. struct mem_cgroup *parent;
  3004. unsigned int nr_pages;
  3005. unsigned long uninitialized_var(flags);
  3006. int ret;
  3007. VM_BUG_ON(mem_cgroup_is_root(child));
  3008. ret = -EBUSY;
  3009. if (!get_page_unless_zero(page))
  3010. goto out;
  3011. if (isolate_lru_page(page))
  3012. goto put;
  3013. nr_pages = hpage_nr_pages(page);
  3014. parent = parent_mem_cgroup(child);
  3015. /*
  3016. * If no parent, move charges to root cgroup.
  3017. */
  3018. if (!parent)
  3019. parent = root_mem_cgroup;
  3020. if (nr_pages > 1) {
  3021. VM_BUG_ON_PAGE(!PageTransHuge(page), page);
  3022. flags = compound_lock_irqsave(page);
  3023. }
  3024. ret = mem_cgroup_move_account(page, nr_pages,
  3025. pc, child, parent);
  3026. if (!ret)
  3027. __mem_cgroup_cancel_local_charge(child, nr_pages);
  3028. if (nr_pages > 1)
  3029. compound_unlock_irqrestore(page, flags);
  3030. putback_lru_page(page);
  3031. put:
  3032. put_page(page);
  3033. out:
  3034. return ret;
  3035. }
  3036. #ifdef CONFIG_MEMCG_SWAP
  3037. static void mem_cgroup_swap_statistics(struct mem_cgroup *memcg,
  3038. bool charge)
  3039. {
  3040. int val = (charge) ? 1 : -1;
  3041. this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_SWAP], val);
  3042. }
  3043. /**
  3044. * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
  3045. * @entry: swap entry to be moved
  3046. * @from: mem_cgroup which the entry is moved from
  3047. * @to: mem_cgroup which the entry is moved to
  3048. *
  3049. * It succeeds only when the swap_cgroup's record for this entry is the same
  3050. * as the mem_cgroup's id of @from.
  3051. *
  3052. * Returns 0 on success, -EINVAL on failure.
  3053. *
  3054. * The caller must have charged to @to, IOW, called res_counter_charge() about
  3055. * both res and memsw, and called css_get().
  3056. */
  3057. static int mem_cgroup_move_swap_account(swp_entry_t entry,
  3058. struct mem_cgroup *from, struct mem_cgroup *to)
  3059. {
  3060. unsigned short old_id, new_id;
  3061. old_id = mem_cgroup_id(from);
  3062. new_id = mem_cgroup_id(to);
  3063. if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
  3064. mem_cgroup_swap_statistics(from, false);
  3065. mem_cgroup_swap_statistics(to, true);
  3066. /*
  3067. * This function is only called from task migration context now.
  3068. * It postpones res_counter and refcount handling till the end
  3069. * of task migration(mem_cgroup_clear_mc()) for performance
  3070. * improvement. But we cannot postpone css_get(to) because if
  3071. * the process that has been moved to @to does swap-in, the
  3072. * refcount of @to might be decreased to 0.
  3073. *
  3074. * We are in attach() phase, so the cgroup is guaranteed to be
  3075. * alive, so we can just call css_get().
  3076. */
  3077. css_get(&to->css);
  3078. return 0;
  3079. }
  3080. return -EINVAL;
  3081. }
  3082. #else
  3083. static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
  3084. struct mem_cgroup *from, struct mem_cgroup *to)
  3085. {
  3086. return -EINVAL;
  3087. }
  3088. #endif
  3089. #ifdef CONFIG_DEBUG_VM
  3090. static struct page_cgroup *lookup_page_cgroup_used(struct page *page)
  3091. {
  3092. struct page_cgroup *pc;
  3093. pc = lookup_page_cgroup(page);
  3094. /*
  3095. * Can be NULL while feeding pages into the page allocator for
  3096. * the first time, i.e. during boot or memory hotplug;
  3097. * or when mem_cgroup_disabled().
  3098. */
  3099. if (likely(pc) && PageCgroupUsed(pc))
  3100. return pc;
  3101. return NULL;
  3102. }
  3103. bool mem_cgroup_bad_page_check(struct page *page)
  3104. {
  3105. if (mem_cgroup_disabled())
  3106. return false;
  3107. return lookup_page_cgroup_used(page) != NULL;
  3108. }
  3109. void mem_cgroup_print_bad_page(struct page *page)
  3110. {
  3111. struct page_cgroup *pc;
  3112. pc = lookup_page_cgroup_used(page);
  3113. if (pc) {
  3114. pr_alert("pc:%p pc->flags:%lx pc->mem_cgroup:%p\n",
  3115. pc, pc->flags, pc->mem_cgroup);
  3116. }
  3117. }
  3118. #endif
  3119. static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
  3120. unsigned long long val)
  3121. {
  3122. int retry_count;
  3123. int ret = 0;
  3124. int children = mem_cgroup_count_children(memcg);
  3125. u64 curusage, oldusage;
  3126. int enlarge;
  3127. /*
  3128. * For keeping hierarchical_reclaim simple, how long we should retry
  3129. * is depends on callers. We set our retry-count to be function
  3130. * of # of children which we should visit in this loop.
  3131. */
  3132. retry_count = MEM_CGROUP_RECLAIM_RETRIES * children;
  3133. oldusage = res_counter_read_u64(&memcg->res, RES_USAGE);
  3134. enlarge = 0;
  3135. while (retry_count) {
  3136. if (signal_pending(current)) {
  3137. ret = -EINTR;
  3138. break;
  3139. }
  3140. /*
  3141. * Rather than hide all in some function, I do this in
  3142. * open coded manner. You see what this really does.
  3143. * We have to guarantee memcg->res.limit <= memcg->memsw.limit.
  3144. */
  3145. mutex_lock(&set_limit_mutex);
  3146. if (res_counter_read_u64(&memcg->memsw, RES_LIMIT) < val) {
  3147. ret = -EINVAL;
  3148. mutex_unlock(&set_limit_mutex);
  3149. break;
  3150. }
  3151. if (res_counter_read_u64(&memcg->res, RES_LIMIT) < val)
  3152. enlarge = 1;
  3153. ret = res_counter_set_limit(&memcg->res, val);
  3154. mutex_unlock(&set_limit_mutex);
  3155. if (!ret)
  3156. break;
  3157. try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL, true);
  3158. curusage = res_counter_read_u64(&memcg->res, RES_USAGE);
  3159. /* Usage is reduced ? */
  3160. if (curusage >= oldusage)
  3161. retry_count--;
  3162. else
  3163. oldusage = curusage;
  3164. }
  3165. if (!ret && enlarge)
  3166. memcg_oom_recover(memcg);
  3167. return ret;
  3168. }
  3169. static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
  3170. unsigned long long val)
  3171. {
  3172. int retry_count;
  3173. u64 oldusage, curusage;
  3174. int children = mem_cgroup_count_children(memcg);
  3175. int ret = -EBUSY;
  3176. int enlarge = 0;
  3177. /* see mem_cgroup_resize_res_limit */
  3178. retry_count = children * MEM_CGROUP_RECLAIM_RETRIES;
  3179. oldusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
  3180. while (retry_count) {
  3181. if (signal_pending(current)) {
  3182. ret = -EINTR;
  3183. break;
  3184. }
  3185. /*
  3186. * Rather than hide all in some function, I do this in
  3187. * open coded manner. You see what this really does.
  3188. * We have to guarantee memcg->res.limit <= memcg->memsw.limit.
  3189. */
  3190. mutex_lock(&set_limit_mutex);
  3191. if (res_counter_read_u64(&memcg->res, RES_LIMIT) > val) {
  3192. ret = -EINVAL;
  3193. mutex_unlock(&set_limit_mutex);
  3194. break;
  3195. }
  3196. if (res_counter_read_u64(&memcg->memsw, RES_LIMIT) < val)
  3197. enlarge = 1;
  3198. ret = res_counter_set_limit(&memcg->memsw, val);
  3199. mutex_unlock(&set_limit_mutex);
  3200. if (!ret)
  3201. break;
  3202. try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL, false);
  3203. curusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
  3204. /* Usage is reduced ? */
  3205. if (curusage >= oldusage)
  3206. retry_count--;
  3207. else
  3208. oldusage = curusage;
  3209. }
  3210. if (!ret && enlarge)
  3211. memcg_oom_recover(memcg);
  3212. return ret;
  3213. }
  3214. unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
  3215. gfp_t gfp_mask,
  3216. unsigned long *total_scanned)
  3217. {
  3218. unsigned long nr_reclaimed = 0;
  3219. struct mem_cgroup_per_zone *mz, *next_mz = NULL;
  3220. unsigned long reclaimed;
  3221. int loop = 0;
  3222. struct mem_cgroup_tree_per_zone *mctz;
  3223. unsigned long long excess;
  3224. unsigned long nr_scanned;
  3225. if (order > 0)
  3226. return 0;
  3227. mctz = soft_limit_tree_node_zone(zone_to_nid(zone), zone_idx(zone));
  3228. /*
  3229. * This loop can run a while, specially if mem_cgroup's continuously
  3230. * keep exceeding their soft limit and putting the system under
  3231. * pressure
  3232. */
  3233. do {
  3234. if (next_mz)
  3235. mz = next_mz;
  3236. else
  3237. mz = mem_cgroup_largest_soft_limit_node(mctz);
  3238. if (!mz)
  3239. break;
  3240. nr_scanned = 0;
  3241. reclaimed = mem_cgroup_soft_reclaim(mz->memcg, zone,
  3242. gfp_mask, &nr_scanned);
  3243. nr_reclaimed += reclaimed;
  3244. *total_scanned += nr_scanned;
  3245. spin_lock_irq(&mctz->lock);
  3246. /*
  3247. * If we failed to reclaim anything from this memory cgroup
  3248. * it is time to move on to the next cgroup
  3249. */
  3250. next_mz = NULL;
  3251. if (!reclaimed) {
  3252. do {
  3253. /*
  3254. * Loop until we find yet another one.
  3255. *
  3256. * By the time we get the soft_limit lock
  3257. * again, someone might have aded the
  3258. * group back on the RB tree. Iterate to
  3259. * make sure we get a different mem.
  3260. * mem_cgroup_largest_soft_limit_node returns
  3261. * NULL if no other cgroup is present on
  3262. * the tree
  3263. */
  3264. next_mz =
  3265. __mem_cgroup_largest_soft_limit_node(mctz);
  3266. if (next_mz == mz)
  3267. css_put(&next_mz->memcg->css);
  3268. else /* next_mz == NULL or other memcg */
  3269. break;
  3270. } while (1);
  3271. }
  3272. __mem_cgroup_remove_exceeded(mz, mctz);
  3273. excess = res_counter_soft_limit_excess(&mz->memcg->res);
  3274. /*
  3275. * One school of thought says that we should not add
  3276. * back the node to the tree if reclaim returns 0.
  3277. * But our reclaim could return 0, simply because due
  3278. * to priority we are exposing a smaller subset of
  3279. * memory to reclaim from. Consider this as a longer
  3280. * term TODO.
  3281. */
  3282. /* If excess == 0, no tree ops */
  3283. __mem_cgroup_insert_exceeded(mz, mctz, excess);
  3284. spin_unlock_irq(&mctz->lock);
  3285. css_put(&mz->memcg->css);
  3286. loop++;
  3287. /*
  3288. * Could not reclaim anything and there are no more
  3289. * mem cgroups to try or we seem to be looping without
  3290. * reclaiming anything.
  3291. */
  3292. if (!nr_reclaimed &&
  3293. (next_mz == NULL ||
  3294. loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
  3295. break;
  3296. } while (!nr_reclaimed);
  3297. if (next_mz)
  3298. css_put(&next_mz->memcg->css);
  3299. return nr_reclaimed;
  3300. }
  3301. /**
  3302. * mem_cgroup_force_empty_list - clears LRU of a group
  3303. * @memcg: group to clear
  3304. * @node: NUMA node
  3305. * @zid: zone id
  3306. * @lru: lru to to clear
  3307. *
  3308. * Traverse a specified page_cgroup list and try to drop them all. This doesn't
  3309. * reclaim the pages page themselves - pages are moved to the parent (or root)
  3310. * group.
  3311. */
  3312. static void mem_cgroup_force_empty_list(struct mem_cgroup *memcg,
  3313. int node, int zid, enum lru_list lru)
  3314. {
  3315. struct lruvec *lruvec;
  3316. unsigned long flags;
  3317. struct list_head *list;
  3318. struct page *busy;
  3319. struct zone *zone;
  3320. zone = &NODE_DATA(node)->node_zones[zid];
  3321. lruvec = mem_cgroup_zone_lruvec(zone, memcg);
  3322. list = &lruvec->lists[lru];
  3323. busy = NULL;
  3324. do {
  3325. struct page_cgroup *pc;
  3326. struct page *page;
  3327. spin_lock_irqsave(&zone->lru_lock, flags);
  3328. if (list_empty(list)) {
  3329. spin_unlock_irqrestore(&zone->lru_lock, flags);
  3330. break;
  3331. }
  3332. page = list_entry(list->prev, struct page, lru);
  3333. if (busy == page) {
  3334. list_move(&page->lru, list);
  3335. busy = NULL;
  3336. spin_unlock_irqrestore(&zone->lru_lock, flags);
  3337. continue;
  3338. }
  3339. spin_unlock_irqrestore(&zone->lru_lock, flags);
  3340. pc = lookup_page_cgroup(page);
  3341. if (mem_cgroup_move_parent(page, pc, memcg)) {
  3342. /* found lock contention or "pc" is obsolete. */
  3343. busy = page;
  3344. } else
  3345. busy = NULL;
  3346. cond_resched();
  3347. } while (!list_empty(list));
  3348. }
  3349. /*
  3350. * make mem_cgroup's charge to be 0 if there is no task by moving
  3351. * all the charges and pages to the parent.
  3352. * This enables deleting this mem_cgroup.
  3353. *
  3354. * Caller is responsible for holding css reference on the memcg.
  3355. */
  3356. static void mem_cgroup_reparent_charges(struct mem_cgroup *memcg)
  3357. {
  3358. int node, zid;
  3359. u64 usage;
  3360. do {
  3361. /* This is for making all *used* pages to be on LRU. */
  3362. lru_add_drain_all();
  3363. drain_all_stock_sync(memcg);
  3364. mem_cgroup_start_move(memcg);
  3365. for_each_node_state(node, N_MEMORY) {
  3366. for (zid = 0; zid < MAX_NR_ZONES; zid++) {
  3367. enum lru_list lru;
  3368. for_each_lru(lru) {
  3369. mem_cgroup_force_empty_list(memcg,
  3370. node, zid, lru);
  3371. }
  3372. }
  3373. }
  3374. mem_cgroup_end_move(memcg);
  3375. memcg_oom_recover(memcg);
  3376. cond_resched();
  3377. /*
  3378. * Kernel memory may not necessarily be trackable to a specific
  3379. * process. So they are not migrated, and therefore we can't
  3380. * expect their value to drop to 0 here.
  3381. * Having res filled up with kmem only is enough.
  3382. *
  3383. * This is a safety check because mem_cgroup_force_empty_list
  3384. * could have raced with mem_cgroup_replace_page_cache callers
  3385. * so the lru seemed empty but the page could have been added
  3386. * right after the check. RES_USAGE should be safe as we always
  3387. * charge before adding to the LRU.
  3388. */
  3389. usage = res_counter_read_u64(&memcg->res, RES_USAGE) -
  3390. res_counter_read_u64(&memcg->kmem, RES_USAGE);
  3391. } while (usage > 0);
  3392. }
  3393. /*
  3394. * Test whether @memcg has children, dead or alive. Note that this
  3395. * function doesn't care whether @memcg has use_hierarchy enabled and
  3396. * returns %true if there are child csses according to the cgroup
  3397. * hierarchy. Testing use_hierarchy is the caller's responsiblity.
  3398. */
  3399. static inline bool memcg_has_children(struct mem_cgroup *memcg)
  3400. {
  3401. bool ret;
  3402. /*
  3403. * The lock does not prevent addition or deletion of children, but
  3404. * it prevents a new child from being initialized based on this
  3405. * parent in css_online(), so it's enough to decide whether
  3406. * hierarchically inherited attributes can still be changed or not.
  3407. */
  3408. lockdep_assert_held(&memcg_create_mutex);
  3409. rcu_read_lock();
  3410. ret = css_next_child(NULL, &memcg->css);
  3411. rcu_read_unlock();
  3412. return ret;
  3413. }
  3414. /*
  3415. * Reclaims as many pages from the given memcg as possible and moves
  3416. * the rest to the parent.
  3417. *
  3418. * Caller is responsible for holding css reference for memcg.
  3419. */
  3420. static int mem_cgroup_force_empty(struct mem_cgroup *memcg)
  3421. {
  3422. int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
  3423. /* we call try-to-free pages for make this cgroup empty */
  3424. lru_add_drain_all();
  3425. /* try to free all pages in this cgroup */
  3426. while (nr_retries && res_counter_read_u64(&memcg->res, RES_USAGE) > 0) {
  3427. int progress;
  3428. if (signal_pending(current))
  3429. return -EINTR;
  3430. progress = try_to_free_mem_cgroup_pages(memcg, 1,
  3431. GFP_KERNEL, true);
  3432. if (!progress) {
  3433. nr_retries--;
  3434. /* maybe some writeback is necessary */
  3435. congestion_wait(BLK_RW_ASYNC, HZ/10);
  3436. }
  3437. }
  3438. return 0;
  3439. }
  3440. static ssize_t mem_cgroup_force_empty_write(struct kernfs_open_file *of,
  3441. char *buf, size_t nbytes,
  3442. loff_t off)
  3443. {
  3444. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  3445. if (mem_cgroup_is_root(memcg))
  3446. return -EINVAL;
  3447. return mem_cgroup_force_empty(memcg) ?: nbytes;
  3448. }
  3449. static u64 mem_cgroup_hierarchy_read(struct cgroup_subsys_state *css,
  3450. struct cftype *cft)
  3451. {
  3452. return mem_cgroup_from_css(css)->use_hierarchy;
  3453. }
  3454. static int mem_cgroup_hierarchy_write(struct cgroup_subsys_state *css,
  3455. struct cftype *cft, u64 val)
  3456. {
  3457. int retval = 0;
  3458. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3459. struct mem_cgroup *parent_memcg = mem_cgroup_from_css(memcg->css.parent);
  3460. mutex_lock(&memcg_create_mutex);
  3461. if (memcg->use_hierarchy == val)
  3462. goto out;
  3463. /*
  3464. * If parent's use_hierarchy is set, we can't make any modifications
  3465. * in the child subtrees. If it is unset, then the change can
  3466. * occur, provided the current cgroup has no children.
  3467. *
  3468. * For the root cgroup, parent_mem is NULL, we allow value to be
  3469. * set if there are no children.
  3470. */
  3471. if ((!parent_memcg || !parent_memcg->use_hierarchy) &&
  3472. (val == 1 || val == 0)) {
  3473. if (!memcg_has_children(memcg))
  3474. memcg->use_hierarchy = val;
  3475. else
  3476. retval = -EBUSY;
  3477. } else
  3478. retval = -EINVAL;
  3479. out:
  3480. mutex_unlock(&memcg_create_mutex);
  3481. return retval;
  3482. }
  3483. static unsigned long mem_cgroup_recursive_stat(struct mem_cgroup *memcg,
  3484. enum mem_cgroup_stat_index idx)
  3485. {
  3486. struct mem_cgroup *iter;
  3487. long val = 0;
  3488. /* Per-cpu values can be negative, use a signed accumulator */
  3489. for_each_mem_cgroup_tree(iter, memcg)
  3490. val += mem_cgroup_read_stat(iter, idx);
  3491. if (val < 0) /* race ? */
  3492. val = 0;
  3493. return val;
  3494. }
  3495. static inline u64 mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
  3496. {
  3497. u64 val;
  3498. if (!mem_cgroup_is_root(memcg)) {
  3499. if (!swap)
  3500. return res_counter_read_u64(&memcg->res, RES_USAGE);
  3501. else
  3502. return res_counter_read_u64(&memcg->memsw, RES_USAGE);
  3503. }
  3504. /*
  3505. * Transparent hugepages are still accounted for in MEM_CGROUP_STAT_RSS
  3506. * as well as in MEM_CGROUP_STAT_RSS_HUGE.
  3507. */
  3508. val = mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_CACHE);
  3509. val += mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_RSS);
  3510. if (swap)
  3511. val += mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_SWAP);
  3512. return val << PAGE_SHIFT;
  3513. }
  3514. static u64 mem_cgroup_read_u64(struct cgroup_subsys_state *css,
  3515. struct cftype *cft)
  3516. {
  3517. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3518. enum res_type type = MEMFILE_TYPE(cft->private);
  3519. int name = MEMFILE_ATTR(cft->private);
  3520. switch (type) {
  3521. case _MEM:
  3522. if (name == RES_USAGE)
  3523. return mem_cgroup_usage(memcg, false);
  3524. return res_counter_read_u64(&memcg->res, name);
  3525. case _MEMSWAP:
  3526. if (name == RES_USAGE)
  3527. return mem_cgroup_usage(memcg, true);
  3528. return res_counter_read_u64(&memcg->memsw, name);
  3529. case _KMEM:
  3530. return res_counter_read_u64(&memcg->kmem, name);
  3531. break;
  3532. default:
  3533. BUG();
  3534. }
  3535. }
  3536. #ifdef CONFIG_MEMCG_KMEM
  3537. /* should be called with activate_kmem_mutex held */
  3538. static int __memcg_activate_kmem(struct mem_cgroup *memcg,
  3539. unsigned long long limit)
  3540. {
  3541. int err = 0;
  3542. int memcg_id;
  3543. if (memcg_kmem_is_active(memcg))
  3544. return 0;
  3545. /*
  3546. * We are going to allocate memory for data shared by all memory
  3547. * cgroups so let's stop accounting here.
  3548. */
  3549. memcg_stop_kmem_account();
  3550. /*
  3551. * For simplicity, we won't allow this to be disabled. It also can't
  3552. * be changed if the cgroup has children already, or if tasks had
  3553. * already joined.
  3554. *
  3555. * If tasks join before we set the limit, a person looking at
  3556. * kmem.usage_in_bytes will have no way to determine when it took
  3557. * place, which makes the value quite meaningless.
  3558. *
  3559. * After it first became limited, changes in the value of the limit are
  3560. * of course permitted.
  3561. */
  3562. mutex_lock(&memcg_create_mutex);
  3563. if (cgroup_has_tasks(memcg->css.cgroup) ||
  3564. (memcg->use_hierarchy && memcg_has_children(memcg)))
  3565. err = -EBUSY;
  3566. mutex_unlock(&memcg_create_mutex);
  3567. if (err)
  3568. goto out;
  3569. memcg_id = memcg_alloc_cache_id();
  3570. if (memcg_id < 0) {
  3571. err = memcg_id;
  3572. goto out;
  3573. }
  3574. memcg->kmemcg_id = memcg_id;
  3575. INIT_LIST_HEAD(&memcg->memcg_slab_caches);
  3576. /*
  3577. * We couldn't have accounted to this cgroup, because it hasn't got the
  3578. * active bit set yet, so this should succeed.
  3579. */
  3580. err = res_counter_set_limit(&memcg->kmem, limit);
  3581. VM_BUG_ON(err);
  3582. static_key_slow_inc(&memcg_kmem_enabled_key);
  3583. /*
  3584. * Setting the active bit after enabling static branching will
  3585. * guarantee no one starts accounting before all call sites are
  3586. * patched.
  3587. */
  3588. memcg_kmem_set_active(memcg);
  3589. out:
  3590. memcg_resume_kmem_account();
  3591. return err;
  3592. }
  3593. static int memcg_activate_kmem(struct mem_cgroup *memcg,
  3594. unsigned long long limit)
  3595. {
  3596. int ret;
  3597. mutex_lock(&activate_kmem_mutex);
  3598. ret = __memcg_activate_kmem(memcg, limit);
  3599. mutex_unlock(&activate_kmem_mutex);
  3600. return ret;
  3601. }
  3602. static int memcg_update_kmem_limit(struct mem_cgroup *memcg,
  3603. unsigned long long val)
  3604. {
  3605. int ret;
  3606. if (!memcg_kmem_is_active(memcg))
  3607. ret = memcg_activate_kmem(memcg, val);
  3608. else
  3609. ret = res_counter_set_limit(&memcg->kmem, val);
  3610. return ret;
  3611. }
  3612. static int memcg_propagate_kmem(struct mem_cgroup *memcg)
  3613. {
  3614. int ret = 0;
  3615. struct mem_cgroup *parent = parent_mem_cgroup(memcg);
  3616. if (!parent)
  3617. return 0;
  3618. mutex_lock(&activate_kmem_mutex);
  3619. /*
  3620. * If the parent cgroup is not kmem-active now, it cannot be activated
  3621. * after this point, because it has at least one child already.
  3622. */
  3623. if (memcg_kmem_is_active(parent))
  3624. ret = __memcg_activate_kmem(memcg, RES_COUNTER_MAX);
  3625. mutex_unlock(&activate_kmem_mutex);
  3626. return ret;
  3627. }
  3628. #else
  3629. static int memcg_update_kmem_limit(struct mem_cgroup *memcg,
  3630. unsigned long long val)
  3631. {
  3632. return -EINVAL;
  3633. }
  3634. #endif /* CONFIG_MEMCG_KMEM */
  3635. /*
  3636. * The user of this function is...
  3637. * RES_LIMIT.
  3638. */
  3639. static ssize_t mem_cgroup_write(struct kernfs_open_file *of,
  3640. char *buf, size_t nbytes, loff_t off)
  3641. {
  3642. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  3643. enum res_type type;
  3644. int name;
  3645. unsigned long long val;
  3646. int ret;
  3647. buf = strstrip(buf);
  3648. type = MEMFILE_TYPE(of_cft(of)->private);
  3649. name = MEMFILE_ATTR(of_cft(of)->private);
  3650. switch (name) {
  3651. case RES_LIMIT:
  3652. if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
  3653. ret = -EINVAL;
  3654. break;
  3655. }
  3656. /* This function does all necessary parse...reuse it */
  3657. ret = res_counter_memparse_write_strategy(buf, &val);
  3658. if (ret)
  3659. break;
  3660. if (type == _MEM)
  3661. ret = mem_cgroup_resize_limit(memcg, val);
  3662. else if (type == _MEMSWAP)
  3663. ret = mem_cgroup_resize_memsw_limit(memcg, val);
  3664. else if (type == _KMEM)
  3665. ret = memcg_update_kmem_limit(memcg, val);
  3666. else
  3667. return -EINVAL;
  3668. break;
  3669. case RES_SOFT_LIMIT:
  3670. ret = res_counter_memparse_write_strategy(buf, &val);
  3671. if (ret)
  3672. break;
  3673. /*
  3674. * For memsw, soft limits are hard to implement in terms
  3675. * of semantics, for now, we support soft limits for
  3676. * control without swap
  3677. */
  3678. if (type == _MEM)
  3679. ret = res_counter_set_soft_limit(&memcg->res, val);
  3680. else
  3681. ret = -EINVAL;
  3682. break;
  3683. default:
  3684. ret = -EINVAL; /* should be BUG() ? */
  3685. break;
  3686. }
  3687. return ret ?: nbytes;
  3688. }
  3689. static void memcg_get_hierarchical_limit(struct mem_cgroup *memcg,
  3690. unsigned long long *mem_limit, unsigned long long *memsw_limit)
  3691. {
  3692. unsigned long long min_limit, min_memsw_limit, tmp;
  3693. min_limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
  3694. min_memsw_limit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
  3695. if (!memcg->use_hierarchy)
  3696. goto out;
  3697. while (memcg->css.parent) {
  3698. memcg = mem_cgroup_from_css(memcg->css.parent);
  3699. if (!memcg->use_hierarchy)
  3700. break;
  3701. tmp = res_counter_read_u64(&memcg->res, RES_LIMIT);
  3702. min_limit = min(min_limit, tmp);
  3703. tmp = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
  3704. min_memsw_limit = min(min_memsw_limit, tmp);
  3705. }
  3706. out:
  3707. *mem_limit = min_limit;
  3708. *memsw_limit = min_memsw_limit;
  3709. }
  3710. static ssize_t mem_cgroup_reset(struct kernfs_open_file *of, char *buf,
  3711. size_t nbytes, loff_t off)
  3712. {
  3713. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  3714. int name;
  3715. enum res_type type;
  3716. type = MEMFILE_TYPE(of_cft(of)->private);
  3717. name = MEMFILE_ATTR(of_cft(of)->private);
  3718. switch (name) {
  3719. case RES_MAX_USAGE:
  3720. if (type == _MEM)
  3721. res_counter_reset_max(&memcg->res);
  3722. else if (type == _MEMSWAP)
  3723. res_counter_reset_max(&memcg->memsw);
  3724. else if (type == _KMEM)
  3725. res_counter_reset_max(&memcg->kmem);
  3726. else
  3727. return -EINVAL;
  3728. break;
  3729. case RES_FAILCNT:
  3730. if (type == _MEM)
  3731. res_counter_reset_failcnt(&memcg->res);
  3732. else if (type == _MEMSWAP)
  3733. res_counter_reset_failcnt(&memcg->memsw);
  3734. else if (type == _KMEM)
  3735. res_counter_reset_failcnt(&memcg->kmem);
  3736. else
  3737. return -EINVAL;
  3738. break;
  3739. }
  3740. return nbytes;
  3741. }
  3742. static u64 mem_cgroup_move_charge_read(struct cgroup_subsys_state *css,
  3743. struct cftype *cft)
  3744. {
  3745. return mem_cgroup_from_css(css)->move_charge_at_immigrate;
  3746. }
  3747. #ifdef CONFIG_MMU
  3748. static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
  3749. struct cftype *cft, u64 val)
  3750. {
  3751. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3752. if (val >= (1 << NR_MOVE_TYPE))
  3753. return -EINVAL;
  3754. /*
  3755. * No kind of locking is needed in here, because ->can_attach() will
  3756. * check this value once in the beginning of the process, and then carry
  3757. * on with stale data. This means that changes to this value will only
  3758. * affect task migrations starting after the change.
  3759. */
  3760. memcg->move_charge_at_immigrate = val;
  3761. return 0;
  3762. }
  3763. #else
  3764. static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
  3765. struct cftype *cft, u64 val)
  3766. {
  3767. return -ENOSYS;
  3768. }
  3769. #endif
  3770. #ifdef CONFIG_NUMA
  3771. static int memcg_numa_stat_show(struct seq_file *m, void *v)
  3772. {
  3773. struct numa_stat {
  3774. const char *name;
  3775. unsigned int lru_mask;
  3776. };
  3777. static const struct numa_stat stats[] = {
  3778. { "total", LRU_ALL },
  3779. { "file", LRU_ALL_FILE },
  3780. { "anon", LRU_ALL_ANON },
  3781. { "unevictable", BIT(LRU_UNEVICTABLE) },
  3782. };
  3783. const struct numa_stat *stat;
  3784. int nid;
  3785. unsigned long nr;
  3786. struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
  3787. for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
  3788. nr = mem_cgroup_nr_lru_pages(memcg, stat->lru_mask);
  3789. seq_printf(m, "%s=%lu", stat->name, nr);
  3790. for_each_node_state(nid, N_MEMORY) {
  3791. nr = mem_cgroup_node_nr_lru_pages(memcg, nid,
  3792. stat->lru_mask);
  3793. seq_printf(m, " N%d=%lu", nid, nr);
  3794. }
  3795. seq_putc(m, '\n');
  3796. }
  3797. for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
  3798. struct mem_cgroup *iter;
  3799. nr = 0;
  3800. for_each_mem_cgroup_tree(iter, memcg)
  3801. nr += mem_cgroup_nr_lru_pages(iter, stat->lru_mask);
  3802. seq_printf(m, "hierarchical_%s=%lu", stat->name, nr);
  3803. for_each_node_state(nid, N_MEMORY) {
  3804. nr = 0;
  3805. for_each_mem_cgroup_tree(iter, memcg)
  3806. nr += mem_cgroup_node_nr_lru_pages(
  3807. iter, nid, stat->lru_mask);
  3808. seq_printf(m, " N%d=%lu", nid, nr);
  3809. }
  3810. seq_putc(m, '\n');
  3811. }
  3812. return 0;
  3813. }
  3814. #endif /* CONFIG_NUMA */
  3815. static inline void mem_cgroup_lru_names_not_uptodate(void)
  3816. {
  3817. BUILD_BUG_ON(ARRAY_SIZE(mem_cgroup_lru_names) != NR_LRU_LISTS);
  3818. }
  3819. static int memcg_stat_show(struct seq_file *m, void *v)
  3820. {
  3821. struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
  3822. struct mem_cgroup *mi;
  3823. unsigned int i;
  3824. for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
  3825. if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
  3826. continue;
  3827. seq_printf(m, "%s %ld\n", mem_cgroup_stat_names[i],
  3828. mem_cgroup_read_stat(memcg, i) * PAGE_SIZE);
  3829. }
  3830. for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++)
  3831. seq_printf(m, "%s %lu\n", mem_cgroup_events_names[i],
  3832. mem_cgroup_read_events(memcg, i));
  3833. for (i = 0; i < NR_LRU_LISTS; i++)
  3834. seq_printf(m, "%s %lu\n", mem_cgroup_lru_names[i],
  3835. mem_cgroup_nr_lru_pages(memcg, BIT(i)) * PAGE_SIZE);
  3836. /* Hierarchical information */
  3837. {
  3838. unsigned long long limit, memsw_limit;
  3839. memcg_get_hierarchical_limit(memcg, &limit, &memsw_limit);
  3840. seq_printf(m, "hierarchical_memory_limit %llu\n", limit);
  3841. if (do_swap_account)
  3842. seq_printf(m, "hierarchical_memsw_limit %llu\n",
  3843. memsw_limit);
  3844. }
  3845. for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
  3846. long long val = 0;
  3847. if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
  3848. continue;
  3849. for_each_mem_cgroup_tree(mi, memcg)
  3850. val += mem_cgroup_read_stat(mi, i) * PAGE_SIZE;
  3851. seq_printf(m, "total_%s %lld\n", mem_cgroup_stat_names[i], val);
  3852. }
  3853. for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
  3854. unsigned long long val = 0;
  3855. for_each_mem_cgroup_tree(mi, memcg)
  3856. val += mem_cgroup_read_events(mi, i);
  3857. seq_printf(m, "total_%s %llu\n",
  3858. mem_cgroup_events_names[i], val);
  3859. }
  3860. for (i = 0; i < NR_LRU_LISTS; i++) {
  3861. unsigned long long val = 0;
  3862. for_each_mem_cgroup_tree(mi, memcg)
  3863. val += mem_cgroup_nr_lru_pages(mi, BIT(i)) * PAGE_SIZE;
  3864. seq_printf(m, "total_%s %llu\n", mem_cgroup_lru_names[i], val);
  3865. }
  3866. #ifdef CONFIG_DEBUG_VM
  3867. {
  3868. int nid, zid;
  3869. struct mem_cgroup_per_zone *mz;
  3870. struct zone_reclaim_stat *rstat;
  3871. unsigned long recent_rotated[2] = {0, 0};
  3872. unsigned long recent_scanned[2] = {0, 0};
  3873. for_each_online_node(nid)
  3874. for (zid = 0; zid < MAX_NR_ZONES; zid++) {
  3875. mz = &memcg->nodeinfo[nid]->zoneinfo[zid];
  3876. rstat = &mz->lruvec.reclaim_stat;
  3877. recent_rotated[0] += rstat->recent_rotated[0];
  3878. recent_rotated[1] += rstat->recent_rotated[1];
  3879. recent_scanned[0] += rstat->recent_scanned[0];
  3880. recent_scanned[1] += rstat->recent_scanned[1];
  3881. }
  3882. seq_printf(m, "recent_rotated_anon %lu\n", recent_rotated[0]);
  3883. seq_printf(m, "recent_rotated_file %lu\n", recent_rotated[1]);
  3884. seq_printf(m, "recent_scanned_anon %lu\n", recent_scanned[0]);
  3885. seq_printf(m, "recent_scanned_file %lu\n", recent_scanned[1]);
  3886. }
  3887. #endif
  3888. return 0;
  3889. }
  3890. static u64 mem_cgroup_swappiness_read(struct cgroup_subsys_state *css,
  3891. struct cftype *cft)
  3892. {
  3893. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3894. return mem_cgroup_swappiness(memcg);
  3895. }
  3896. static int mem_cgroup_swappiness_write(struct cgroup_subsys_state *css,
  3897. struct cftype *cft, u64 val)
  3898. {
  3899. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3900. if (val > 100)
  3901. return -EINVAL;
  3902. if (css->parent)
  3903. memcg->swappiness = val;
  3904. else
  3905. vm_swappiness = val;
  3906. return 0;
  3907. }
  3908. static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
  3909. {
  3910. struct mem_cgroup_threshold_ary *t;
  3911. u64 usage;
  3912. int i;
  3913. rcu_read_lock();
  3914. if (!swap)
  3915. t = rcu_dereference(memcg->thresholds.primary);
  3916. else
  3917. t = rcu_dereference(memcg->memsw_thresholds.primary);
  3918. if (!t)
  3919. goto unlock;
  3920. usage = mem_cgroup_usage(memcg, swap);
  3921. /*
  3922. * current_threshold points to threshold just below or equal to usage.
  3923. * If it's not true, a threshold was crossed after last
  3924. * call of __mem_cgroup_threshold().
  3925. */
  3926. i = t->current_threshold;
  3927. /*
  3928. * Iterate backward over array of thresholds starting from
  3929. * current_threshold and check if a threshold is crossed.
  3930. * If none of thresholds below usage is crossed, we read
  3931. * only one element of the array here.
  3932. */
  3933. for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
  3934. eventfd_signal(t->entries[i].eventfd, 1);
  3935. /* i = current_threshold + 1 */
  3936. i++;
  3937. /*
  3938. * Iterate forward over array of thresholds starting from
  3939. * current_threshold+1 and check if a threshold is crossed.
  3940. * If none of thresholds above usage is crossed, we read
  3941. * only one element of the array here.
  3942. */
  3943. for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
  3944. eventfd_signal(t->entries[i].eventfd, 1);
  3945. /* Update current_threshold */
  3946. t->current_threshold = i - 1;
  3947. unlock:
  3948. rcu_read_unlock();
  3949. }
  3950. static void mem_cgroup_threshold(struct mem_cgroup *memcg)
  3951. {
  3952. while (memcg) {
  3953. __mem_cgroup_threshold(memcg, false);
  3954. if (do_swap_account)
  3955. __mem_cgroup_threshold(memcg, true);
  3956. memcg = parent_mem_cgroup(memcg);
  3957. }
  3958. }
  3959. static int compare_thresholds(const void *a, const void *b)
  3960. {
  3961. const struct mem_cgroup_threshold *_a = a;
  3962. const struct mem_cgroup_threshold *_b = b;
  3963. if (_a->threshold > _b->threshold)
  3964. return 1;
  3965. if (_a->threshold < _b->threshold)
  3966. return -1;
  3967. return 0;
  3968. }
  3969. static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
  3970. {
  3971. struct mem_cgroup_eventfd_list *ev;
  3972. spin_lock(&memcg_oom_lock);
  3973. list_for_each_entry(ev, &memcg->oom_notify, list)
  3974. eventfd_signal(ev->eventfd, 1);
  3975. spin_unlock(&memcg_oom_lock);
  3976. return 0;
  3977. }
  3978. static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
  3979. {
  3980. struct mem_cgroup *iter;
  3981. for_each_mem_cgroup_tree(iter, memcg)
  3982. mem_cgroup_oom_notify_cb(iter);
  3983. }
  3984. static int __mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
  3985. struct eventfd_ctx *eventfd, const char *args, enum res_type type)
  3986. {
  3987. struct mem_cgroup_thresholds *thresholds;
  3988. struct mem_cgroup_threshold_ary *new;
  3989. u64 threshold, usage;
  3990. int i, size, ret;
  3991. ret = res_counter_memparse_write_strategy(args, &threshold);
  3992. if (ret)
  3993. return ret;
  3994. mutex_lock(&memcg->thresholds_lock);
  3995. if (type == _MEM) {
  3996. thresholds = &memcg->thresholds;
  3997. usage = mem_cgroup_usage(memcg, false);
  3998. } else if (type == _MEMSWAP) {
  3999. thresholds = &memcg->memsw_thresholds;
  4000. usage = mem_cgroup_usage(memcg, true);
  4001. } else
  4002. BUG();
  4003. /* Check if a threshold crossed before adding a new one */
  4004. if (thresholds->primary)
  4005. __mem_cgroup_threshold(memcg, type == _MEMSWAP);
  4006. size = thresholds->primary ? thresholds->primary->size + 1 : 1;
  4007. /* Allocate memory for new array of thresholds */
  4008. new = kmalloc(sizeof(*new) + size * sizeof(struct mem_cgroup_threshold),
  4009. GFP_KERNEL);
  4010. if (!new) {
  4011. ret = -ENOMEM;
  4012. goto unlock;
  4013. }
  4014. new->size = size;
  4015. /* Copy thresholds (if any) to new array */
  4016. if (thresholds->primary) {
  4017. memcpy(new->entries, thresholds->primary->entries, (size - 1) *
  4018. sizeof(struct mem_cgroup_threshold));
  4019. }
  4020. /* Add new threshold */
  4021. new->entries[size - 1].eventfd = eventfd;
  4022. new->entries[size - 1].threshold = threshold;
  4023. /* Sort thresholds. Registering of new threshold isn't time-critical */
  4024. sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
  4025. compare_thresholds, NULL);
  4026. /* Find current threshold */
  4027. new->current_threshold = -1;
  4028. for (i = 0; i < size; i++) {
  4029. if (new->entries[i].threshold <= usage) {
  4030. /*
  4031. * new->current_threshold will not be used until
  4032. * rcu_assign_pointer(), so it's safe to increment
  4033. * it here.
  4034. */
  4035. ++new->current_threshold;
  4036. } else
  4037. break;
  4038. }
  4039. /* Free old spare buffer and save old primary buffer as spare */
  4040. kfree(thresholds->spare);
  4041. thresholds->spare = thresholds->primary;
  4042. rcu_assign_pointer(thresholds->primary, new);
  4043. /* To be sure that nobody uses thresholds */
  4044. synchronize_rcu();
  4045. unlock:
  4046. mutex_unlock(&memcg->thresholds_lock);
  4047. return ret;
  4048. }
  4049. static int mem_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, _MEM);
  4053. }
  4054. static int memsw_cgroup_usage_register_event(struct mem_cgroup *memcg,
  4055. struct eventfd_ctx *eventfd, const char *args)
  4056. {
  4057. return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEMSWAP);
  4058. }
  4059. static void __mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
  4060. struct eventfd_ctx *eventfd, enum res_type type)
  4061. {
  4062. struct mem_cgroup_thresholds *thresholds;
  4063. struct mem_cgroup_threshold_ary *new;
  4064. u64 usage;
  4065. int i, j, size;
  4066. mutex_lock(&memcg->thresholds_lock);
  4067. if (type == _MEM) {
  4068. thresholds = &memcg->thresholds;
  4069. usage = mem_cgroup_usage(memcg, false);
  4070. } else if (type == _MEMSWAP) {
  4071. thresholds = &memcg->memsw_thresholds;
  4072. usage = mem_cgroup_usage(memcg, true);
  4073. } else
  4074. BUG();
  4075. if (!thresholds->primary)
  4076. goto unlock;
  4077. /* Check if a threshold crossed before removing */
  4078. __mem_cgroup_threshold(memcg, type == _MEMSWAP);
  4079. /* Calculate new number of threshold */
  4080. size = 0;
  4081. for (i = 0; i < thresholds->primary->size; i++) {
  4082. if (thresholds->primary->entries[i].eventfd != eventfd)
  4083. size++;
  4084. }
  4085. new = thresholds->spare;
  4086. /* Set thresholds array to NULL if we don't have thresholds */
  4087. if (!size) {
  4088. kfree(new);
  4089. new = NULL;
  4090. goto swap_buffers;
  4091. }
  4092. new->size = size;
  4093. /* Copy thresholds and find current threshold */
  4094. new->current_threshold = -1;
  4095. for (i = 0, j = 0; i < thresholds->primary->size; i++) {
  4096. if (thresholds->primary->entries[i].eventfd == eventfd)
  4097. continue;
  4098. new->entries[j] = thresholds->primary->entries[i];
  4099. if (new->entries[j].threshold <= usage) {
  4100. /*
  4101. * new->current_threshold will not be used
  4102. * until rcu_assign_pointer(), so it's safe to increment
  4103. * it here.
  4104. */
  4105. ++new->current_threshold;
  4106. }
  4107. j++;
  4108. }
  4109. swap_buffers:
  4110. /* Swap primary and spare array */
  4111. thresholds->spare = thresholds->primary;
  4112. /* If all events are unregistered, free the spare array */
  4113. if (!new) {
  4114. kfree(thresholds->spare);
  4115. thresholds->spare = NULL;
  4116. }
  4117. rcu_assign_pointer(thresholds->primary, new);
  4118. /* To be sure that nobody uses thresholds */
  4119. synchronize_rcu();
  4120. unlock:
  4121. mutex_unlock(&memcg->thresholds_lock);
  4122. }
  4123. static void mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
  4124. struct eventfd_ctx *eventfd)
  4125. {
  4126. return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEM);
  4127. }
  4128. static void memsw_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
  4129. struct eventfd_ctx *eventfd)
  4130. {
  4131. return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEMSWAP);
  4132. }
  4133. static int mem_cgroup_oom_register_event(struct mem_cgroup *memcg,
  4134. struct eventfd_ctx *eventfd, const char *args)
  4135. {
  4136. struct mem_cgroup_eventfd_list *event;
  4137. event = kmalloc(sizeof(*event), GFP_KERNEL);
  4138. if (!event)
  4139. return -ENOMEM;
  4140. spin_lock(&memcg_oom_lock);
  4141. event->eventfd = eventfd;
  4142. list_add(&event->list, &memcg->oom_notify);
  4143. /* already in OOM ? */
  4144. if (atomic_read(&memcg->under_oom))
  4145. eventfd_signal(eventfd, 1);
  4146. spin_unlock(&memcg_oom_lock);
  4147. return 0;
  4148. }
  4149. static void mem_cgroup_oom_unregister_event(struct mem_cgroup *memcg,
  4150. struct eventfd_ctx *eventfd)
  4151. {
  4152. struct mem_cgroup_eventfd_list *ev, *tmp;
  4153. spin_lock(&memcg_oom_lock);
  4154. list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
  4155. if (ev->eventfd == eventfd) {
  4156. list_del(&ev->list);
  4157. kfree(ev);
  4158. }
  4159. }
  4160. spin_unlock(&memcg_oom_lock);
  4161. }
  4162. static int mem_cgroup_oom_control_read(struct seq_file *sf, void *v)
  4163. {
  4164. struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(sf));
  4165. seq_printf(sf, "oom_kill_disable %d\n", memcg->oom_kill_disable);
  4166. seq_printf(sf, "under_oom %d\n", (bool)atomic_read(&memcg->under_oom));
  4167. return 0;
  4168. }
  4169. static int mem_cgroup_oom_control_write(struct cgroup_subsys_state *css,
  4170. struct cftype *cft, u64 val)
  4171. {
  4172. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  4173. /* cannot set to root cgroup and only 0 and 1 are allowed */
  4174. if (!css->parent || !((val == 0) || (val == 1)))
  4175. return -EINVAL;
  4176. memcg->oom_kill_disable = val;
  4177. if (!val)
  4178. memcg_oom_recover(memcg);
  4179. return 0;
  4180. }
  4181. #ifdef CONFIG_MEMCG_KMEM
  4182. static int memcg_init_kmem(struct mem_cgroup *memcg, struct cgroup_subsys *ss)
  4183. {
  4184. int ret;
  4185. memcg->kmemcg_id = -1;
  4186. ret = memcg_propagate_kmem(memcg);
  4187. if (ret)
  4188. return ret;
  4189. return mem_cgroup_sockets_init(memcg, ss);
  4190. }
  4191. static void memcg_destroy_kmem(struct mem_cgroup *memcg)
  4192. {
  4193. mem_cgroup_sockets_destroy(memcg);
  4194. }
  4195. static void kmem_cgroup_css_offline(struct mem_cgroup *memcg)
  4196. {
  4197. if (!memcg_kmem_is_active(memcg))
  4198. return;
  4199. /*
  4200. * kmem charges can outlive the cgroup. In the case of slab
  4201. * pages, for instance, a page contain objects from various
  4202. * processes. As we prevent from taking a reference for every
  4203. * such allocation we have to be careful when doing uncharge
  4204. * (see memcg_uncharge_kmem) and here during offlining.
  4205. *
  4206. * The idea is that that only the _last_ uncharge which sees
  4207. * the dead memcg will drop the last reference. An additional
  4208. * reference is taken here before the group is marked dead
  4209. * which is then paired with css_put during uncharge resp. here.
  4210. *
  4211. * Although this might sound strange as this path is called from
  4212. * css_offline() when the referencemight have dropped down to 0 and
  4213. * shouldn't be incremented anymore (css_tryget_online() would
  4214. * fail) we do not have other options because of the kmem
  4215. * allocations lifetime.
  4216. */
  4217. css_get(&memcg->css);
  4218. memcg_kmem_mark_dead(memcg);
  4219. if (res_counter_read_u64(&memcg->kmem, RES_USAGE) != 0)
  4220. return;
  4221. if (memcg_kmem_test_and_clear_dead(memcg))
  4222. css_put(&memcg->css);
  4223. }
  4224. #else
  4225. static int memcg_init_kmem(struct mem_cgroup *memcg, struct cgroup_subsys *ss)
  4226. {
  4227. return 0;
  4228. }
  4229. static void memcg_destroy_kmem(struct mem_cgroup *memcg)
  4230. {
  4231. }
  4232. static void kmem_cgroup_css_offline(struct mem_cgroup *memcg)
  4233. {
  4234. }
  4235. #endif
  4236. /*
  4237. * DO NOT USE IN NEW FILES.
  4238. *
  4239. * "cgroup.event_control" implementation.
  4240. *
  4241. * This is way over-engineered. It tries to support fully configurable
  4242. * events for each user. Such level of flexibility is completely
  4243. * unnecessary especially in the light of the planned unified hierarchy.
  4244. *
  4245. * Please deprecate this and replace with something simpler if at all
  4246. * possible.
  4247. */
  4248. /*
  4249. * Unregister event and free resources.
  4250. *
  4251. * Gets called from workqueue.
  4252. */
  4253. static void memcg_event_remove(struct work_struct *work)
  4254. {
  4255. struct mem_cgroup_event *event =
  4256. container_of(work, struct mem_cgroup_event, remove);
  4257. struct mem_cgroup *memcg = event->memcg;
  4258. remove_wait_queue(event->wqh, &event->wait);
  4259. event->unregister_event(memcg, event->eventfd);
  4260. /* Notify userspace the event is going away. */
  4261. eventfd_signal(event->eventfd, 1);
  4262. eventfd_ctx_put(event->eventfd);
  4263. kfree(event);
  4264. css_put(&memcg->css);
  4265. }
  4266. /*
  4267. * Gets called on POLLHUP on eventfd when user closes it.
  4268. *
  4269. * Called with wqh->lock held and interrupts disabled.
  4270. */
  4271. static int memcg_event_wake(wait_queue_t *wait, unsigned mode,
  4272. int sync, void *key)
  4273. {
  4274. struct mem_cgroup_event *event =
  4275. container_of(wait, struct mem_cgroup_event, wait);
  4276. struct mem_cgroup *memcg = event->memcg;
  4277. unsigned long flags = (unsigned long)key;
  4278. if (flags & POLLHUP) {
  4279. /*
  4280. * If the event has been detached at cgroup removal, we
  4281. * can simply return knowing the other side will cleanup
  4282. * for us.
  4283. *
  4284. * We can't race against event freeing since the other
  4285. * side will require wqh->lock via remove_wait_queue(),
  4286. * which we hold.
  4287. */
  4288. spin_lock(&memcg->event_list_lock);
  4289. if (!list_empty(&event->list)) {
  4290. list_del_init(&event->list);
  4291. /*
  4292. * We are in atomic context, but cgroup_event_remove()
  4293. * may sleep, so we have to call it in workqueue.
  4294. */
  4295. schedule_work(&event->remove);
  4296. }
  4297. spin_unlock(&memcg->event_list_lock);
  4298. }
  4299. return 0;
  4300. }
  4301. static void memcg_event_ptable_queue_proc(struct file *file,
  4302. wait_queue_head_t *wqh, poll_table *pt)
  4303. {
  4304. struct mem_cgroup_event *event =
  4305. container_of(pt, struct mem_cgroup_event, pt);
  4306. event->wqh = wqh;
  4307. add_wait_queue(wqh, &event->wait);
  4308. }
  4309. /*
  4310. * DO NOT USE IN NEW FILES.
  4311. *
  4312. * Parse input and register new cgroup event handler.
  4313. *
  4314. * Input must be in format '<event_fd> <control_fd> <args>'.
  4315. * Interpretation of args is defined by control file implementation.
  4316. */
  4317. static ssize_t memcg_write_event_control(struct kernfs_open_file *of,
  4318. char *buf, size_t nbytes, loff_t off)
  4319. {
  4320. struct cgroup_subsys_state *css = of_css(of);
  4321. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  4322. struct mem_cgroup_event *event;
  4323. struct cgroup_subsys_state *cfile_css;
  4324. unsigned int efd, cfd;
  4325. struct fd efile;
  4326. struct fd cfile;
  4327. const char *name;
  4328. char *endp;
  4329. int ret;
  4330. buf = strstrip(buf);
  4331. efd = simple_strtoul(buf, &endp, 10);
  4332. if (*endp != ' ')
  4333. return -EINVAL;
  4334. buf = endp + 1;
  4335. cfd = simple_strtoul(buf, &endp, 10);
  4336. if ((*endp != ' ') && (*endp != '\0'))
  4337. return -EINVAL;
  4338. buf = endp + 1;
  4339. event = kzalloc(sizeof(*event), GFP_KERNEL);
  4340. if (!event)
  4341. return -ENOMEM;
  4342. event->memcg = memcg;
  4343. INIT_LIST_HEAD(&event->list);
  4344. init_poll_funcptr(&event->pt, memcg_event_ptable_queue_proc);
  4345. init_waitqueue_func_entry(&event->wait, memcg_event_wake);
  4346. INIT_WORK(&event->remove, memcg_event_remove);
  4347. efile = fdget(efd);
  4348. if (!efile.file) {
  4349. ret = -EBADF;
  4350. goto out_kfree;
  4351. }
  4352. event->eventfd = eventfd_ctx_fileget(efile.file);
  4353. if (IS_ERR(event->eventfd)) {
  4354. ret = PTR_ERR(event->eventfd);
  4355. goto out_put_efile;
  4356. }
  4357. cfile = fdget(cfd);
  4358. if (!cfile.file) {
  4359. ret = -EBADF;
  4360. goto out_put_eventfd;
  4361. }
  4362. /* the process need read permission on control file */
  4363. /* AV: shouldn't we check that it's been opened for read instead? */
  4364. ret = inode_permission(file_inode(cfile.file), MAY_READ);
  4365. if (ret < 0)
  4366. goto out_put_cfile;
  4367. /*
  4368. * Determine the event callbacks and set them in @event. This used
  4369. * to be done via struct cftype but cgroup core no longer knows
  4370. * about these events. The following is crude but the whole thing
  4371. * is for compatibility anyway.
  4372. *
  4373. * DO NOT ADD NEW FILES.
  4374. */
  4375. name = cfile.file->f_dentry->d_name.name;
  4376. if (!strcmp(name, "memory.usage_in_bytes")) {
  4377. event->register_event = mem_cgroup_usage_register_event;
  4378. event->unregister_event = mem_cgroup_usage_unregister_event;
  4379. } else if (!strcmp(name, "memory.oom_control")) {
  4380. event->register_event = mem_cgroup_oom_register_event;
  4381. event->unregister_event = mem_cgroup_oom_unregister_event;
  4382. } else if (!strcmp(name, "memory.pressure_level")) {
  4383. event->register_event = vmpressure_register_event;
  4384. event->unregister_event = vmpressure_unregister_event;
  4385. } else if (!strcmp(name, "memory.memsw.usage_in_bytes")) {
  4386. event->register_event = memsw_cgroup_usage_register_event;
  4387. event->unregister_event = memsw_cgroup_usage_unregister_event;
  4388. } else {
  4389. ret = -EINVAL;
  4390. goto out_put_cfile;
  4391. }
  4392. /*
  4393. * Verify @cfile should belong to @css. Also, remaining events are
  4394. * automatically removed on cgroup destruction but the removal is
  4395. * asynchronous, so take an extra ref on @css.
  4396. */
  4397. cfile_css = css_tryget_online_from_dir(cfile.file->f_dentry->d_parent,
  4398. &memory_cgrp_subsys);
  4399. ret = -EINVAL;
  4400. if (IS_ERR(cfile_css))
  4401. goto out_put_cfile;
  4402. if (cfile_css != css) {
  4403. css_put(cfile_css);
  4404. goto out_put_cfile;
  4405. }
  4406. ret = event->register_event(memcg, event->eventfd, buf);
  4407. if (ret)
  4408. goto out_put_css;
  4409. efile.file->f_op->poll(efile.file, &event->pt);
  4410. spin_lock(&memcg->event_list_lock);
  4411. list_add(&event->list, &memcg->event_list);
  4412. spin_unlock(&memcg->event_list_lock);
  4413. fdput(cfile);
  4414. fdput(efile);
  4415. return nbytes;
  4416. out_put_css:
  4417. css_put(css);
  4418. out_put_cfile:
  4419. fdput(cfile);
  4420. out_put_eventfd:
  4421. eventfd_ctx_put(event->eventfd);
  4422. out_put_efile:
  4423. fdput(efile);
  4424. out_kfree:
  4425. kfree(event);
  4426. return ret;
  4427. }
  4428. static struct cftype mem_cgroup_files[] = {
  4429. {
  4430. .name = "usage_in_bytes",
  4431. .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
  4432. .read_u64 = mem_cgroup_read_u64,
  4433. },
  4434. {
  4435. .name = "max_usage_in_bytes",
  4436. .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
  4437. .write = mem_cgroup_reset,
  4438. .read_u64 = mem_cgroup_read_u64,
  4439. },
  4440. {
  4441. .name = "limit_in_bytes",
  4442. .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
  4443. .write = mem_cgroup_write,
  4444. .read_u64 = mem_cgroup_read_u64,
  4445. },
  4446. {
  4447. .name = "soft_limit_in_bytes",
  4448. .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
  4449. .write = mem_cgroup_write,
  4450. .read_u64 = mem_cgroup_read_u64,
  4451. },
  4452. {
  4453. .name = "failcnt",
  4454. .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
  4455. .write = mem_cgroup_reset,
  4456. .read_u64 = mem_cgroup_read_u64,
  4457. },
  4458. {
  4459. .name = "stat",
  4460. .seq_show = memcg_stat_show,
  4461. },
  4462. {
  4463. .name = "force_empty",
  4464. .write = mem_cgroup_force_empty_write,
  4465. },
  4466. {
  4467. .name = "use_hierarchy",
  4468. .write_u64 = mem_cgroup_hierarchy_write,
  4469. .read_u64 = mem_cgroup_hierarchy_read,
  4470. },
  4471. {
  4472. .name = "cgroup.event_control", /* XXX: for compat */
  4473. .write = memcg_write_event_control,
  4474. .flags = CFTYPE_NO_PREFIX,
  4475. .mode = S_IWUGO,
  4476. },
  4477. {
  4478. .name = "swappiness",
  4479. .read_u64 = mem_cgroup_swappiness_read,
  4480. .write_u64 = mem_cgroup_swappiness_write,
  4481. },
  4482. {
  4483. .name = "move_charge_at_immigrate",
  4484. .read_u64 = mem_cgroup_move_charge_read,
  4485. .write_u64 = mem_cgroup_move_charge_write,
  4486. },
  4487. {
  4488. .name = "oom_control",
  4489. .seq_show = mem_cgroup_oom_control_read,
  4490. .write_u64 = mem_cgroup_oom_control_write,
  4491. .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
  4492. },
  4493. {
  4494. .name = "pressure_level",
  4495. },
  4496. #ifdef CONFIG_NUMA
  4497. {
  4498. .name = "numa_stat",
  4499. .seq_show = memcg_numa_stat_show,
  4500. },
  4501. #endif
  4502. #ifdef CONFIG_MEMCG_KMEM
  4503. {
  4504. .name = "kmem.limit_in_bytes",
  4505. .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
  4506. .write = mem_cgroup_write,
  4507. .read_u64 = mem_cgroup_read_u64,
  4508. },
  4509. {
  4510. .name = "kmem.usage_in_bytes",
  4511. .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
  4512. .read_u64 = mem_cgroup_read_u64,
  4513. },
  4514. {
  4515. .name = "kmem.failcnt",
  4516. .private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
  4517. .write = mem_cgroup_reset,
  4518. .read_u64 = mem_cgroup_read_u64,
  4519. },
  4520. {
  4521. .name = "kmem.max_usage_in_bytes",
  4522. .private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
  4523. .write = mem_cgroup_reset,
  4524. .read_u64 = mem_cgroup_read_u64,
  4525. },
  4526. #ifdef CONFIG_SLABINFO
  4527. {
  4528. .name = "kmem.slabinfo",
  4529. .seq_show = mem_cgroup_slabinfo_read,
  4530. },
  4531. #endif
  4532. #endif
  4533. { }, /* terminate */
  4534. };
  4535. #ifdef CONFIG_MEMCG_SWAP
  4536. static struct cftype memsw_cgroup_files[] = {
  4537. {
  4538. .name = "memsw.usage_in_bytes",
  4539. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
  4540. .read_u64 = mem_cgroup_read_u64,
  4541. },
  4542. {
  4543. .name = "memsw.max_usage_in_bytes",
  4544. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
  4545. .write = mem_cgroup_reset,
  4546. .read_u64 = mem_cgroup_read_u64,
  4547. },
  4548. {
  4549. .name = "memsw.limit_in_bytes",
  4550. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
  4551. .write = mem_cgroup_write,
  4552. .read_u64 = mem_cgroup_read_u64,
  4553. },
  4554. {
  4555. .name = "memsw.failcnt",
  4556. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
  4557. .write = mem_cgroup_reset,
  4558. .read_u64 = mem_cgroup_read_u64,
  4559. },
  4560. { }, /* terminate */
  4561. };
  4562. #endif
  4563. static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
  4564. {
  4565. struct mem_cgroup_per_node *pn;
  4566. struct mem_cgroup_per_zone *mz;
  4567. int zone, tmp = node;
  4568. /*
  4569. * This routine is called against possible nodes.
  4570. * But it's BUG to call kmalloc() against offline node.
  4571. *
  4572. * TODO: this routine can waste much memory for nodes which will
  4573. * never be onlined. It's better to use memory hotplug callback
  4574. * function.
  4575. */
  4576. if (!node_state(node, N_NORMAL_MEMORY))
  4577. tmp = -1;
  4578. pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
  4579. if (!pn)
  4580. return 1;
  4581. for (zone = 0; zone < MAX_NR_ZONES; zone++) {
  4582. mz = &pn->zoneinfo[zone];
  4583. lruvec_init(&mz->lruvec);
  4584. mz->usage_in_excess = 0;
  4585. mz->on_tree = false;
  4586. mz->memcg = memcg;
  4587. }
  4588. memcg->nodeinfo[node] = pn;
  4589. return 0;
  4590. }
  4591. static void free_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
  4592. {
  4593. kfree(memcg->nodeinfo[node]);
  4594. }
  4595. static struct mem_cgroup *mem_cgroup_alloc(void)
  4596. {
  4597. struct mem_cgroup *memcg;
  4598. size_t size;
  4599. size = sizeof(struct mem_cgroup);
  4600. size += nr_node_ids * sizeof(struct mem_cgroup_per_node *);
  4601. memcg = kzalloc(size, GFP_KERNEL);
  4602. if (!memcg)
  4603. return NULL;
  4604. memcg->stat = alloc_percpu(struct mem_cgroup_stat_cpu);
  4605. if (!memcg->stat)
  4606. goto out_free;
  4607. spin_lock_init(&memcg->pcp_counter_lock);
  4608. return memcg;
  4609. out_free:
  4610. kfree(memcg);
  4611. return NULL;
  4612. }
  4613. /*
  4614. * At destroying mem_cgroup, references from swap_cgroup can remain.
  4615. * (scanning all at force_empty is too costly...)
  4616. *
  4617. * Instead of clearing all references at force_empty, we remember
  4618. * the number of reference from swap_cgroup and free mem_cgroup when
  4619. * it goes down to 0.
  4620. *
  4621. * Removal of cgroup itself succeeds regardless of refs from swap.
  4622. */
  4623. static void __mem_cgroup_free(struct mem_cgroup *memcg)
  4624. {
  4625. int node;
  4626. mem_cgroup_remove_from_trees(memcg);
  4627. for_each_node(node)
  4628. free_mem_cgroup_per_zone_info(memcg, node);
  4629. free_percpu(memcg->stat);
  4630. /*
  4631. * We need to make sure that (at least for now), the jump label
  4632. * destruction code runs outside of the cgroup lock. This is because
  4633. * get_online_cpus(), which is called from the static_branch update,
  4634. * can't be called inside the cgroup_lock. cpusets are the ones
  4635. * enforcing this dependency, so if they ever change, we might as well.
  4636. *
  4637. * schedule_work() will guarantee this happens. Be careful if you need
  4638. * to move this code around, and make sure it is outside
  4639. * the cgroup_lock.
  4640. */
  4641. disarm_static_keys(memcg);
  4642. kfree(memcg);
  4643. }
  4644. /*
  4645. * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
  4646. */
  4647. struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *memcg)
  4648. {
  4649. if (!memcg->res.parent)
  4650. return NULL;
  4651. return mem_cgroup_from_res_counter(memcg->res.parent, res);
  4652. }
  4653. EXPORT_SYMBOL(parent_mem_cgroup);
  4654. static void __init mem_cgroup_soft_limit_tree_init(void)
  4655. {
  4656. struct mem_cgroup_tree_per_node *rtpn;
  4657. struct mem_cgroup_tree_per_zone *rtpz;
  4658. int tmp, node, zone;
  4659. for_each_node(node) {
  4660. tmp = node;
  4661. if (!node_state(node, N_NORMAL_MEMORY))
  4662. tmp = -1;
  4663. rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, tmp);
  4664. BUG_ON(!rtpn);
  4665. soft_limit_tree.rb_tree_per_node[node] = rtpn;
  4666. for (zone = 0; zone < MAX_NR_ZONES; zone++) {
  4667. rtpz = &rtpn->rb_tree_per_zone[zone];
  4668. rtpz->rb_root = RB_ROOT;
  4669. spin_lock_init(&rtpz->lock);
  4670. }
  4671. }
  4672. }
  4673. static struct cgroup_subsys_state * __ref
  4674. mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
  4675. {
  4676. struct mem_cgroup *memcg;
  4677. long error = -ENOMEM;
  4678. int node;
  4679. memcg = mem_cgroup_alloc();
  4680. if (!memcg)
  4681. return ERR_PTR(error);
  4682. for_each_node(node)
  4683. if (alloc_mem_cgroup_per_zone_info(memcg, node))
  4684. goto free_out;
  4685. /* root ? */
  4686. if (parent_css == NULL) {
  4687. root_mem_cgroup = memcg;
  4688. res_counter_init(&memcg->res, NULL);
  4689. res_counter_init(&memcg->memsw, NULL);
  4690. res_counter_init(&memcg->kmem, NULL);
  4691. }
  4692. memcg->last_scanned_node = MAX_NUMNODES;
  4693. INIT_LIST_HEAD(&memcg->oom_notify);
  4694. memcg->move_charge_at_immigrate = 0;
  4695. mutex_init(&memcg->thresholds_lock);
  4696. spin_lock_init(&memcg->move_lock);
  4697. vmpressure_init(&memcg->vmpressure);
  4698. INIT_LIST_HEAD(&memcg->event_list);
  4699. spin_lock_init(&memcg->event_list_lock);
  4700. return &memcg->css;
  4701. free_out:
  4702. __mem_cgroup_free(memcg);
  4703. return ERR_PTR(error);
  4704. }
  4705. static int
  4706. mem_cgroup_css_online(struct cgroup_subsys_state *css)
  4707. {
  4708. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  4709. struct mem_cgroup *parent = mem_cgroup_from_css(css->parent);
  4710. int ret;
  4711. if (css->id > MEM_CGROUP_ID_MAX)
  4712. return -ENOSPC;
  4713. if (!parent)
  4714. return 0;
  4715. mutex_lock(&memcg_create_mutex);
  4716. memcg->use_hierarchy = parent->use_hierarchy;
  4717. memcg->oom_kill_disable = parent->oom_kill_disable;
  4718. memcg->swappiness = mem_cgroup_swappiness(parent);
  4719. if (parent->use_hierarchy) {
  4720. res_counter_init(&memcg->res, &parent->res);
  4721. res_counter_init(&memcg->memsw, &parent->memsw);
  4722. res_counter_init(&memcg->kmem, &parent->kmem);
  4723. /*
  4724. * No need to take a reference to the parent because cgroup
  4725. * core guarantees its existence.
  4726. */
  4727. } else {
  4728. res_counter_init(&memcg->res, NULL);
  4729. res_counter_init(&memcg->memsw, NULL);
  4730. res_counter_init(&memcg->kmem, NULL);
  4731. /*
  4732. * Deeper hierachy with use_hierarchy == false doesn't make
  4733. * much sense so let cgroup subsystem know about this
  4734. * unfortunate state in our controller.
  4735. */
  4736. if (parent != root_mem_cgroup)
  4737. memory_cgrp_subsys.broken_hierarchy = true;
  4738. }
  4739. mutex_unlock(&memcg_create_mutex);
  4740. ret = memcg_init_kmem(memcg, &memory_cgrp_subsys);
  4741. if (ret)
  4742. return ret;
  4743. /*
  4744. * Make sure the memcg is initialized: mem_cgroup_iter()
  4745. * orders reading memcg->initialized against its callers
  4746. * reading the memcg members.
  4747. */
  4748. smp_store_release(&memcg->initialized, 1);
  4749. return 0;
  4750. }
  4751. /*
  4752. * Announce all parents that a group from their hierarchy is gone.
  4753. */
  4754. static void mem_cgroup_invalidate_reclaim_iterators(struct mem_cgroup *memcg)
  4755. {
  4756. struct mem_cgroup *parent = memcg;
  4757. while ((parent = parent_mem_cgroup(parent)))
  4758. mem_cgroup_iter_invalidate(parent);
  4759. /*
  4760. * if the root memcg is not hierarchical we have to check it
  4761. * explicitely.
  4762. */
  4763. if (!root_mem_cgroup->use_hierarchy)
  4764. mem_cgroup_iter_invalidate(root_mem_cgroup);
  4765. }
  4766. static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
  4767. {
  4768. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  4769. struct mem_cgroup_event *event, *tmp;
  4770. struct cgroup_subsys_state *iter;
  4771. /*
  4772. * Unregister events and notify userspace.
  4773. * Notify userspace about cgroup removing only after rmdir of cgroup
  4774. * directory to avoid race between userspace and kernelspace.
  4775. */
  4776. spin_lock(&memcg->event_list_lock);
  4777. list_for_each_entry_safe(event, tmp, &memcg->event_list, list) {
  4778. list_del_init(&event->list);
  4779. schedule_work(&event->remove);
  4780. }
  4781. spin_unlock(&memcg->event_list_lock);
  4782. kmem_cgroup_css_offline(memcg);
  4783. mem_cgroup_invalidate_reclaim_iterators(memcg);
  4784. /*
  4785. * This requires that offlining is serialized. Right now that is
  4786. * guaranteed because css_killed_work_fn() holds the cgroup_mutex.
  4787. */
  4788. css_for_each_descendant_post(iter, css)
  4789. mem_cgroup_reparent_charges(mem_cgroup_from_css(iter));
  4790. memcg_unregister_all_caches(memcg);
  4791. vmpressure_cleanup(&memcg->vmpressure);
  4792. }
  4793. static void mem_cgroup_css_free(struct cgroup_subsys_state *css)
  4794. {
  4795. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  4796. /*
  4797. * XXX: css_offline() would be where we should reparent all
  4798. * memory to prepare the cgroup for destruction. However,
  4799. * memcg does not do css_tryget_online() and res_counter charging
  4800. * under the same RCU lock region, which means that charging
  4801. * could race with offlining. Offlining only happens to
  4802. * cgroups with no tasks in them but charges can show up
  4803. * without any tasks from the swapin path when the target
  4804. * memcg is looked up from the swapout record and not from the
  4805. * current task as it usually is. A race like this can leak
  4806. * charges and put pages with stale cgroup pointers into
  4807. * circulation:
  4808. *
  4809. * #0 #1
  4810. * lookup_swap_cgroup_id()
  4811. * rcu_read_lock()
  4812. * mem_cgroup_lookup()
  4813. * css_tryget_online()
  4814. * rcu_read_unlock()
  4815. * disable css_tryget_online()
  4816. * call_rcu()
  4817. * offline_css()
  4818. * reparent_charges()
  4819. * res_counter_charge()
  4820. * css_put()
  4821. * css_free()
  4822. * pc->mem_cgroup = dead memcg
  4823. * add page to lru
  4824. *
  4825. * The bulk of the charges are still moved in offline_css() to
  4826. * avoid pinning a lot of pages in case a long-term reference
  4827. * like a swapout record is deferring the css_free() to long
  4828. * after offlining. But this makes sure we catch any charges
  4829. * made after offlining:
  4830. */
  4831. mem_cgroup_reparent_charges(memcg);
  4832. memcg_destroy_kmem(memcg);
  4833. __mem_cgroup_free(memcg);
  4834. }
  4835. /**
  4836. * mem_cgroup_css_reset - reset the states of a mem_cgroup
  4837. * @css: the target css
  4838. *
  4839. * Reset the states of the mem_cgroup associated with @css. This is
  4840. * invoked when the userland requests disabling on the default hierarchy
  4841. * but the memcg is pinned through dependency. The memcg should stop
  4842. * applying policies and should revert to the vanilla state as it may be
  4843. * made visible again.
  4844. *
  4845. * The current implementation only resets the essential configurations.
  4846. * This needs to be expanded to cover all the visible parts.
  4847. */
  4848. static void mem_cgroup_css_reset(struct cgroup_subsys_state *css)
  4849. {
  4850. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  4851. mem_cgroup_resize_limit(memcg, ULLONG_MAX);
  4852. mem_cgroup_resize_memsw_limit(memcg, ULLONG_MAX);
  4853. memcg_update_kmem_limit(memcg, ULLONG_MAX);
  4854. res_counter_set_soft_limit(&memcg->res, ULLONG_MAX);
  4855. }
  4856. #ifdef CONFIG_MMU
  4857. /* Handlers for move charge at task migration. */
  4858. static int mem_cgroup_do_precharge(unsigned long count)
  4859. {
  4860. int ret;
  4861. /* Try a single bulk charge without reclaim first */
  4862. ret = try_charge(mc.to, GFP_KERNEL & ~__GFP_WAIT, count);
  4863. if (!ret) {
  4864. mc.precharge += count;
  4865. return ret;
  4866. }
  4867. if (ret == -EINTR) {
  4868. cancel_charge(root_mem_cgroup, count);
  4869. return ret;
  4870. }
  4871. /* Try charges one by one with reclaim */
  4872. while (count--) {
  4873. ret = try_charge(mc.to, GFP_KERNEL & ~__GFP_NORETRY, 1);
  4874. /*
  4875. * In case of failure, any residual charges against
  4876. * mc.to will be dropped by mem_cgroup_clear_mc()
  4877. * later on. However, cancel any charges that are
  4878. * bypassed to root right away or they'll be lost.
  4879. */
  4880. if (ret == -EINTR)
  4881. cancel_charge(root_mem_cgroup, 1);
  4882. if (ret)
  4883. return ret;
  4884. mc.precharge++;
  4885. cond_resched();
  4886. }
  4887. return 0;
  4888. }
  4889. /**
  4890. * get_mctgt_type - get target type of moving charge
  4891. * @vma: the vma the pte to be checked belongs
  4892. * @addr: the address corresponding to the pte to be checked
  4893. * @ptent: the pte to be checked
  4894. * @target: the pointer the target page or swap ent will be stored(can be NULL)
  4895. *
  4896. * Returns
  4897. * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
  4898. * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
  4899. * move charge. if @target is not NULL, the page is stored in target->page
  4900. * with extra refcnt got(Callers should handle it).
  4901. * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
  4902. * target for charge migration. if @target is not NULL, the entry is stored
  4903. * in target->ent.
  4904. *
  4905. * Called with pte lock held.
  4906. */
  4907. union mc_target {
  4908. struct page *page;
  4909. swp_entry_t ent;
  4910. };
  4911. enum mc_target_type {
  4912. MC_TARGET_NONE = 0,
  4913. MC_TARGET_PAGE,
  4914. MC_TARGET_SWAP,
  4915. };
  4916. static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
  4917. unsigned long addr, pte_t ptent)
  4918. {
  4919. struct page *page = vm_normal_page(vma, addr, ptent);
  4920. if (!page || !page_mapped(page))
  4921. return NULL;
  4922. if (PageAnon(page)) {
  4923. /* we don't move shared anon */
  4924. if (!move_anon())
  4925. return NULL;
  4926. } else if (!move_file())
  4927. /* we ignore mapcount for file pages */
  4928. return NULL;
  4929. if (!get_page_unless_zero(page))
  4930. return NULL;
  4931. return page;
  4932. }
  4933. #ifdef CONFIG_SWAP
  4934. static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
  4935. unsigned long addr, pte_t ptent, swp_entry_t *entry)
  4936. {
  4937. struct page *page = NULL;
  4938. swp_entry_t ent = pte_to_swp_entry(ptent);
  4939. if (!move_anon() || non_swap_entry(ent))
  4940. return NULL;
  4941. /*
  4942. * Because lookup_swap_cache() updates some statistics counter,
  4943. * we call find_get_page() with swapper_space directly.
  4944. */
  4945. page = find_get_page(swap_address_space(ent), ent.val);
  4946. if (do_swap_account)
  4947. entry->val = ent.val;
  4948. return page;
  4949. }
  4950. #else
  4951. static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
  4952. unsigned long addr, pte_t ptent, swp_entry_t *entry)
  4953. {
  4954. return NULL;
  4955. }
  4956. #endif
  4957. static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
  4958. unsigned long addr, pte_t ptent, swp_entry_t *entry)
  4959. {
  4960. struct page *page = NULL;
  4961. struct address_space *mapping;
  4962. pgoff_t pgoff;
  4963. if (!vma->vm_file) /* anonymous vma */
  4964. return NULL;
  4965. if (!move_file())
  4966. return NULL;
  4967. mapping = vma->vm_file->f_mapping;
  4968. if (pte_none(ptent))
  4969. pgoff = linear_page_index(vma, addr);
  4970. else /* pte_file(ptent) is true */
  4971. pgoff = pte_to_pgoff(ptent);
  4972. /* page is moved even if it's not RSS of this task(page-faulted). */
  4973. #ifdef CONFIG_SWAP
  4974. /* shmem/tmpfs may report page out on swap: account for that too. */
  4975. if (shmem_mapping(mapping)) {
  4976. page = find_get_entry(mapping, pgoff);
  4977. if (radix_tree_exceptional_entry(page)) {
  4978. swp_entry_t swp = radix_to_swp_entry(page);
  4979. if (do_swap_account)
  4980. *entry = swp;
  4981. page = find_get_page(swap_address_space(swp), swp.val);
  4982. }
  4983. } else
  4984. page = find_get_page(mapping, pgoff);
  4985. #else
  4986. page = find_get_page(mapping, pgoff);
  4987. #endif
  4988. return page;
  4989. }
  4990. static enum mc_target_type get_mctgt_type(struct vm_area_struct *vma,
  4991. unsigned long addr, pte_t ptent, union mc_target *target)
  4992. {
  4993. struct page *page = NULL;
  4994. struct page_cgroup *pc;
  4995. enum mc_target_type ret = MC_TARGET_NONE;
  4996. swp_entry_t ent = { .val = 0 };
  4997. if (pte_present(ptent))
  4998. page = mc_handle_present_pte(vma, addr, ptent);
  4999. else if (is_swap_pte(ptent))
  5000. page = mc_handle_swap_pte(vma, addr, ptent, &ent);
  5001. else if (pte_none(ptent) || pte_file(ptent))
  5002. page = mc_handle_file_pte(vma, addr, ptent, &ent);
  5003. if (!page && !ent.val)
  5004. return ret;
  5005. if (page) {
  5006. pc = lookup_page_cgroup(page);
  5007. /*
  5008. * Do only loose check w/o serialization.
  5009. * mem_cgroup_move_account() checks the pc is valid or
  5010. * not under LRU exclusion.
  5011. */
  5012. if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
  5013. ret = MC_TARGET_PAGE;
  5014. if (target)
  5015. target->page = page;
  5016. }
  5017. if (!ret || !target)
  5018. put_page(page);
  5019. }
  5020. /* There is a swap entry and a page doesn't exist or isn't charged */
  5021. if (ent.val && !ret &&
  5022. mem_cgroup_id(mc.from) == lookup_swap_cgroup_id(ent)) {
  5023. ret = MC_TARGET_SWAP;
  5024. if (target)
  5025. target->ent = ent;
  5026. }
  5027. return ret;
  5028. }
  5029. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  5030. /*
  5031. * We don't consider swapping or file mapped pages because THP does not
  5032. * support them for now.
  5033. * Caller should make sure that pmd_trans_huge(pmd) is true.
  5034. */
  5035. static enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
  5036. unsigned long addr, pmd_t pmd, union mc_target *target)
  5037. {
  5038. struct page *page = NULL;
  5039. struct page_cgroup *pc;
  5040. enum mc_target_type ret = MC_TARGET_NONE;
  5041. page = pmd_page(pmd);
  5042. VM_BUG_ON_PAGE(!page || !PageHead(page), page);
  5043. if (!move_anon())
  5044. return ret;
  5045. pc = lookup_page_cgroup(page);
  5046. if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
  5047. ret = MC_TARGET_PAGE;
  5048. if (target) {
  5049. get_page(page);
  5050. target->page = page;
  5051. }
  5052. }
  5053. return ret;
  5054. }
  5055. #else
  5056. static inline enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
  5057. unsigned long addr, pmd_t pmd, union mc_target *target)
  5058. {
  5059. return MC_TARGET_NONE;
  5060. }
  5061. #endif
  5062. static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
  5063. unsigned long addr, unsigned long end,
  5064. struct mm_walk *walk)
  5065. {
  5066. struct vm_area_struct *vma = walk->private;
  5067. pte_t *pte;
  5068. spinlock_t *ptl;
  5069. if (pmd_trans_huge_lock(pmd, vma, &ptl) == 1) {
  5070. if (get_mctgt_type_thp(vma, addr, *pmd, NULL) == MC_TARGET_PAGE)
  5071. mc.precharge += HPAGE_PMD_NR;
  5072. spin_unlock(ptl);
  5073. return 0;
  5074. }
  5075. if (pmd_trans_unstable(pmd))
  5076. return 0;
  5077. pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
  5078. for (; addr != end; pte++, addr += PAGE_SIZE)
  5079. if (get_mctgt_type(vma, addr, *pte, NULL))
  5080. mc.precharge++; /* increment precharge temporarily */
  5081. pte_unmap_unlock(pte - 1, ptl);
  5082. cond_resched();
  5083. return 0;
  5084. }
  5085. static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
  5086. {
  5087. unsigned long precharge;
  5088. struct vm_area_struct *vma;
  5089. down_read(&mm->mmap_sem);
  5090. for (vma = mm->mmap; vma; vma = vma->vm_next) {
  5091. struct mm_walk mem_cgroup_count_precharge_walk = {
  5092. .pmd_entry = mem_cgroup_count_precharge_pte_range,
  5093. .mm = mm,
  5094. .private = vma,
  5095. };
  5096. if (is_vm_hugetlb_page(vma))
  5097. continue;
  5098. walk_page_range(vma->vm_start, vma->vm_end,
  5099. &mem_cgroup_count_precharge_walk);
  5100. }
  5101. up_read(&mm->mmap_sem);
  5102. precharge = mc.precharge;
  5103. mc.precharge = 0;
  5104. return precharge;
  5105. }
  5106. static int mem_cgroup_precharge_mc(struct mm_struct *mm)
  5107. {
  5108. unsigned long precharge = mem_cgroup_count_precharge(mm);
  5109. VM_BUG_ON(mc.moving_task);
  5110. mc.moving_task = current;
  5111. return mem_cgroup_do_precharge(precharge);
  5112. }
  5113. /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
  5114. static void __mem_cgroup_clear_mc(void)
  5115. {
  5116. struct mem_cgroup *from = mc.from;
  5117. struct mem_cgroup *to = mc.to;
  5118. int i;
  5119. /* we must uncharge all the leftover precharges from mc.to */
  5120. if (mc.precharge) {
  5121. cancel_charge(mc.to, mc.precharge);
  5122. mc.precharge = 0;
  5123. }
  5124. /*
  5125. * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
  5126. * we must uncharge here.
  5127. */
  5128. if (mc.moved_charge) {
  5129. cancel_charge(mc.from, mc.moved_charge);
  5130. mc.moved_charge = 0;
  5131. }
  5132. /* we must fixup refcnts and charges */
  5133. if (mc.moved_swap) {
  5134. /* uncharge swap account from the old cgroup */
  5135. if (!mem_cgroup_is_root(mc.from))
  5136. res_counter_uncharge(&mc.from->memsw,
  5137. PAGE_SIZE * mc.moved_swap);
  5138. for (i = 0; i < mc.moved_swap; i++)
  5139. css_put(&mc.from->css);
  5140. /*
  5141. * we charged both to->res and to->memsw, so we should
  5142. * uncharge to->res.
  5143. */
  5144. if (!mem_cgroup_is_root(mc.to))
  5145. res_counter_uncharge(&mc.to->res,
  5146. PAGE_SIZE * mc.moved_swap);
  5147. /* we've already done css_get(mc.to) */
  5148. mc.moved_swap = 0;
  5149. }
  5150. memcg_oom_recover(from);
  5151. memcg_oom_recover(to);
  5152. wake_up_all(&mc.waitq);
  5153. }
  5154. static void mem_cgroup_clear_mc(void)
  5155. {
  5156. struct mem_cgroup *from = mc.from;
  5157. /*
  5158. * we must clear moving_task before waking up waiters at the end of
  5159. * task migration.
  5160. */
  5161. mc.moving_task = NULL;
  5162. __mem_cgroup_clear_mc();
  5163. spin_lock(&mc.lock);
  5164. mc.from = NULL;
  5165. mc.to = NULL;
  5166. spin_unlock(&mc.lock);
  5167. mem_cgroup_end_move(from);
  5168. }
  5169. static int mem_cgroup_can_attach(struct cgroup_subsys_state *css,
  5170. struct cgroup_taskset *tset)
  5171. {
  5172. struct task_struct *p = cgroup_taskset_first(tset);
  5173. int ret = 0;
  5174. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  5175. unsigned long move_charge_at_immigrate;
  5176. /*
  5177. * We are now commited to this value whatever it is. Changes in this
  5178. * tunable will only affect upcoming migrations, not the current one.
  5179. * So we need to save it, and keep it going.
  5180. */
  5181. move_charge_at_immigrate = memcg->move_charge_at_immigrate;
  5182. if (move_charge_at_immigrate) {
  5183. struct mm_struct *mm;
  5184. struct mem_cgroup *from = mem_cgroup_from_task(p);
  5185. VM_BUG_ON(from == memcg);
  5186. mm = get_task_mm(p);
  5187. if (!mm)
  5188. return 0;
  5189. /* We move charges only when we move a owner of the mm */
  5190. if (mm->owner == p) {
  5191. VM_BUG_ON(mc.from);
  5192. VM_BUG_ON(mc.to);
  5193. VM_BUG_ON(mc.precharge);
  5194. VM_BUG_ON(mc.moved_charge);
  5195. VM_BUG_ON(mc.moved_swap);
  5196. mem_cgroup_start_move(from);
  5197. spin_lock(&mc.lock);
  5198. mc.from = from;
  5199. mc.to = memcg;
  5200. mc.immigrate_flags = move_charge_at_immigrate;
  5201. spin_unlock(&mc.lock);
  5202. /* We set mc.moving_task later */
  5203. ret = mem_cgroup_precharge_mc(mm);
  5204. if (ret)
  5205. mem_cgroup_clear_mc();
  5206. }
  5207. mmput(mm);
  5208. }
  5209. return ret;
  5210. }
  5211. static void mem_cgroup_cancel_attach(struct cgroup_subsys_state *css,
  5212. struct cgroup_taskset *tset)
  5213. {
  5214. mem_cgroup_clear_mc();
  5215. }
  5216. static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
  5217. unsigned long addr, unsigned long end,
  5218. struct mm_walk *walk)
  5219. {
  5220. int ret = 0;
  5221. struct vm_area_struct *vma = walk->private;
  5222. pte_t *pte;
  5223. spinlock_t *ptl;
  5224. enum mc_target_type target_type;
  5225. union mc_target target;
  5226. struct page *page;
  5227. struct page_cgroup *pc;
  5228. /*
  5229. * We don't take compound_lock() here but no race with splitting thp
  5230. * happens because:
  5231. * - if pmd_trans_huge_lock() returns 1, the relevant thp is not
  5232. * under splitting, which means there's no concurrent thp split,
  5233. * - if another thread runs into split_huge_page() just after we
  5234. * entered this if-block, the thread must wait for page table lock
  5235. * to be unlocked in __split_huge_page_splitting(), where the main
  5236. * part of thp split is not executed yet.
  5237. */
  5238. if (pmd_trans_huge_lock(pmd, vma, &ptl) == 1) {
  5239. if (mc.precharge < HPAGE_PMD_NR) {
  5240. spin_unlock(ptl);
  5241. return 0;
  5242. }
  5243. target_type = get_mctgt_type_thp(vma, addr, *pmd, &target);
  5244. if (target_type == MC_TARGET_PAGE) {
  5245. page = target.page;
  5246. if (!isolate_lru_page(page)) {
  5247. pc = lookup_page_cgroup(page);
  5248. if (!mem_cgroup_move_account(page, HPAGE_PMD_NR,
  5249. pc, mc.from, mc.to)) {
  5250. mc.precharge -= HPAGE_PMD_NR;
  5251. mc.moved_charge += HPAGE_PMD_NR;
  5252. }
  5253. putback_lru_page(page);
  5254. }
  5255. put_page(page);
  5256. }
  5257. spin_unlock(ptl);
  5258. return 0;
  5259. }
  5260. if (pmd_trans_unstable(pmd))
  5261. return 0;
  5262. retry:
  5263. pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
  5264. for (; addr != end; addr += PAGE_SIZE) {
  5265. pte_t ptent = *(pte++);
  5266. swp_entry_t ent;
  5267. if (!mc.precharge)
  5268. break;
  5269. switch (get_mctgt_type(vma, addr, ptent, &target)) {
  5270. case MC_TARGET_PAGE:
  5271. page = target.page;
  5272. if (isolate_lru_page(page))
  5273. goto put;
  5274. pc = lookup_page_cgroup(page);
  5275. if (!mem_cgroup_move_account(page, 1, pc,
  5276. mc.from, mc.to)) {
  5277. mc.precharge--;
  5278. /* we uncharge from mc.from later. */
  5279. mc.moved_charge++;
  5280. }
  5281. putback_lru_page(page);
  5282. put: /* get_mctgt_type() gets the page */
  5283. put_page(page);
  5284. break;
  5285. case MC_TARGET_SWAP:
  5286. ent = target.ent;
  5287. if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to)) {
  5288. mc.precharge--;
  5289. /* we fixup refcnts and charges later. */
  5290. mc.moved_swap++;
  5291. }
  5292. break;
  5293. default:
  5294. break;
  5295. }
  5296. }
  5297. pte_unmap_unlock(pte - 1, ptl);
  5298. cond_resched();
  5299. if (addr != end) {
  5300. /*
  5301. * We have consumed all precharges we got in can_attach().
  5302. * We try charge one by one, but don't do any additional
  5303. * charges to mc.to if we have failed in charge once in attach()
  5304. * phase.
  5305. */
  5306. ret = mem_cgroup_do_precharge(1);
  5307. if (!ret)
  5308. goto retry;
  5309. }
  5310. return ret;
  5311. }
  5312. static void mem_cgroup_move_charge(struct mm_struct *mm)
  5313. {
  5314. struct vm_area_struct *vma;
  5315. lru_add_drain_all();
  5316. retry:
  5317. if (unlikely(!down_read_trylock(&mm->mmap_sem))) {
  5318. /*
  5319. * Someone who are holding the mmap_sem might be waiting in
  5320. * waitq. So we cancel all extra charges, wake up all waiters,
  5321. * and retry. Because we cancel precharges, we might not be able
  5322. * to move enough charges, but moving charge is a best-effort
  5323. * feature anyway, so it wouldn't be a big problem.
  5324. */
  5325. __mem_cgroup_clear_mc();
  5326. cond_resched();
  5327. goto retry;
  5328. }
  5329. for (vma = mm->mmap; vma; vma = vma->vm_next) {
  5330. int ret;
  5331. struct mm_walk mem_cgroup_move_charge_walk = {
  5332. .pmd_entry = mem_cgroup_move_charge_pte_range,
  5333. .mm = mm,
  5334. .private = vma,
  5335. };
  5336. if (is_vm_hugetlb_page(vma))
  5337. continue;
  5338. ret = walk_page_range(vma->vm_start, vma->vm_end,
  5339. &mem_cgroup_move_charge_walk);
  5340. if (ret)
  5341. /*
  5342. * means we have consumed all precharges and failed in
  5343. * doing additional charge. Just abandon here.
  5344. */
  5345. break;
  5346. }
  5347. up_read(&mm->mmap_sem);
  5348. }
  5349. static void mem_cgroup_move_task(struct cgroup_subsys_state *css,
  5350. struct cgroup_taskset *tset)
  5351. {
  5352. struct task_struct *p = cgroup_taskset_first(tset);
  5353. struct mm_struct *mm = get_task_mm(p);
  5354. if (mm) {
  5355. if (mc.to)
  5356. mem_cgroup_move_charge(mm);
  5357. mmput(mm);
  5358. }
  5359. if (mc.to)
  5360. mem_cgroup_clear_mc();
  5361. }
  5362. #else /* !CONFIG_MMU */
  5363. static int mem_cgroup_can_attach(struct cgroup_subsys_state *css,
  5364. struct cgroup_taskset *tset)
  5365. {
  5366. return 0;
  5367. }
  5368. static void mem_cgroup_cancel_attach(struct cgroup_subsys_state *css,
  5369. struct cgroup_taskset *tset)
  5370. {
  5371. }
  5372. static void mem_cgroup_move_task(struct cgroup_subsys_state *css,
  5373. struct cgroup_taskset *tset)
  5374. {
  5375. }
  5376. #endif
  5377. /*
  5378. * Cgroup retains root cgroups across [un]mount cycles making it necessary
  5379. * to verify whether we're attached to the default hierarchy on each mount
  5380. * attempt.
  5381. */
  5382. static void mem_cgroup_bind(struct cgroup_subsys_state *root_css)
  5383. {
  5384. /*
  5385. * use_hierarchy is forced on the default hierarchy. cgroup core
  5386. * guarantees that @root doesn't have any children, so turning it
  5387. * on for the root memcg is enough.
  5388. */
  5389. if (cgroup_on_dfl(root_css->cgroup))
  5390. mem_cgroup_from_css(root_css)->use_hierarchy = true;
  5391. }
  5392. struct cgroup_subsys memory_cgrp_subsys = {
  5393. .css_alloc = mem_cgroup_css_alloc,
  5394. .css_online = mem_cgroup_css_online,
  5395. .css_offline = mem_cgroup_css_offline,
  5396. .css_free = mem_cgroup_css_free,
  5397. .css_reset = mem_cgroup_css_reset,
  5398. .can_attach = mem_cgroup_can_attach,
  5399. .cancel_attach = mem_cgroup_cancel_attach,
  5400. .attach = mem_cgroup_move_task,
  5401. .bind = mem_cgroup_bind,
  5402. .legacy_cftypes = mem_cgroup_files,
  5403. .early_init = 0,
  5404. };
  5405. #ifdef CONFIG_MEMCG_SWAP
  5406. static int __init enable_swap_account(char *s)
  5407. {
  5408. if (!strcmp(s, "1"))
  5409. really_do_swap_account = 1;
  5410. else if (!strcmp(s, "0"))
  5411. really_do_swap_account = 0;
  5412. return 1;
  5413. }
  5414. __setup("swapaccount=", enable_swap_account);
  5415. static void __init memsw_file_init(void)
  5416. {
  5417. WARN_ON(cgroup_add_legacy_cftypes(&memory_cgrp_subsys,
  5418. memsw_cgroup_files));
  5419. }
  5420. static void __init enable_swap_cgroup(void)
  5421. {
  5422. if (!mem_cgroup_disabled() && really_do_swap_account) {
  5423. do_swap_account = 1;
  5424. memsw_file_init();
  5425. }
  5426. }
  5427. #else
  5428. static void __init enable_swap_cgroup(void)
  5429. {
  5430. }
  5431. #endif
  5432. #ifdef CONFIG_MEMCG_SWAP
  5433. /**
  5434. * mem_cgroup_swapout - transfer a memsw charge to swap
  5435. * @page: page whose memsw charge to transfer
  5436. * @entry: swap entry to move the charge to
  5437. *
  5438. * Transfer the memsw charge of @page to @entry.
  5439. */
  5440. void mem_cgroup_swapout(struct page *page, swp_entry_t entry)
  5441. {
  5442. struct page_cgroup *pc;
  5443. unsigned short oldid;
  5444. VM_BUG_ON_PAGE(PageLRU(page), page);
  5445. VM_BUG_ON_PAGE(page_count(page), page);
  5446. if (!do_swap_account)
  5447. return;
  5448. pc = lookup_page_cgroup(page);
  5449. /* Readahead page, never charged */
  5450. if (!PageCgroupUsed(pc))
  5451. return;
  5452. VM_BUG_ON_PAGE(!(pc->flags & PCG_MEMSW), page);
  5453. oldid = swap_cgroup_record(entry, mem_cgroup_id(pc->mem_cgroup));
  5454. VM_BUG_ON_PAGE(oldid, page);
  5455. pc->flags &= ~PCG_MEMSW;
  5456. css_get(&pc->mem_cgroup->css);
  5457. mem_cgroup_swap_statistics(pc->mem_cgroup, true);
  5458. }
  5459. /**
  5460. * mem_cgroup_uncharge_swap - uncharge a swap entry
  5461. * @entry: swap entry to uncharge
  5462. *
  5463. * Drop the memsw charge associated with @entry.
  5464. */
  5465. void mem_cgroup_uncharge_swap(swp_entry_t entry)
  5466. {
  5467. struct mem_cgroup *memcg;
  5468. unsigned short id;
  5469. if (!do_swap_account)
  5470. return;
  5471. id = swap_cgroup_record(entry, 0);
  5472. rcu_read_lock();
  5473. memcg = mem_cgroup_lookup(id);
  5474. if (memcg) {
  5475. if (!mem_cgroup_is_root(memcg))
  5476. res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
  5477. mem_cgroup_swap_statistics(memcg, false);
  5478. css_put(&memcg->css);
  5479. }
  5480. rcu_read_unlock();
  5481. }
  5482. #endif
  5483. /**
  5484. * mem_cgroup_try_charge - try charging a page
  5485. * @page: page to charge
  5486. * @mm: mm context of the victim
  5487. * @gfp_mask: reclaim mode
  5488. * @memcgp: charged memcg return
  5489. *
  5490. * Try to charge @page to the memcg that @mm belongs to, reclaiming
  5491. * pages according to @gfp_mask if necessary.
  5492. *
  5493. * Returns 0 on success, with *@memcgp pointing to the charged memcg.
  5494. * Otherwise, an error code is returned.
  5495. *
  5496. * After page->mapping has been set up, the caller must finalize the
  5497. * charge with mem_cgroup_commit_charge(). Or abort the transaction
  5498. * with mem_cgroup_cancel_charge() in case page instantiation fails.
  5499. */
  5500. int mem_cgroup_try_charge(struct page *page, struct mm_struct *mm,
  5501. gfp_t gfp_mask, struct mem_cgroup **memcgp)
  5502. {
  5503. struct mem_cgroup *memcg = NULL;
  5504. unsigned int nr_pages = 1;
  5505. int ret = 0;
  5506. if (mem_cgroup_disabled())
  5507. goto out;
  5508. if (PageSwapCache(page)) {
  5509. struct page_cgroup *pc = lookup_page_cgroup(page);
  5510. /*
  5511. * Every swap fault against a single page tries to charge the
  5512. * page, bail as early as possible. shmem_unuse() encounters
  5513. * already charged pages, too. The USED bit is protected by
  5514. * the page lock, which serializes swap cache removal, which
  5515. * in turn serializes uncharging.
  5516. */
  5517. if (PageCgroupUsed(pc))
  5518. goto out;
  5519. }
  5520. if (PageTransHuge(page)) {
  5521. nr_pages <<= compound_order(page);
  5522. VM_BUG_ON_PAGE(!PageTransHuge(page), page);
  5523. }
  5524. if (do_swap_account && PageSwapCache(page))
  5525. memcg = try_get_mem_cgroup_from_page(page);
  5526. if (!memcg)
  5527. memcg = get_mem_cgroup_from_mm(mm);
  5528. ret = try_charge(memcg, gfp_mask, nr_pages);
  5529. css_put(&memcg->css);
  5530. if (ret == -EINTR) {
  5531. memcg = root_mem_cgroup;
  5532. ret = 0;
  5533. }
  5534. out:
  5535. *memcgp = memcg;
  5536. return ret;
  5537. }
  5538. /**
  5539. * mem_cgroup_commit_charge - commit a page charge
  5540. * @page: page to charge
  5541. * @memcg: memcg to charge the page to
  5542. * @lrucare: page might be on LRU already
  5543. *
  5544. * Finalize a charge transaction started by mem_cgroup_try_charge(),
  5545. * after page->mapping has been set up. This must happen atomically
  5546. * as part of the page instantiation, i.e. under the page table lock
  5547. * for anonymous pages, under the page lock for page and swap cache.
  5548. *
  5549. * In addition, the page must not be on the LRU during the commit, to
  5550. * prevent racing with task migration. If it might be, use @lrucare.
  5551. *
  5552. * Use mem_cgroup_cancel_charge() to cancel the transaction instead.
  5553. */
  5554. void mem_cgroup_commit_charge(struct page *page, struct mem_cgroup *memcg,
  5555. bool lrucare)
  5556. {
  5557. unsigned int nr_pages = 1;
  5558. VM_BUG_ON_PAGE(!page->mapping, page);
  5559. VM_BUG_ON_PAGE(PageLRU(page) && !lrucare, page);
  5560. if (mem_cgroup_disabled())
  5561. return;
  5562. /*
  5563. * Swap faults will attempt to charge the same page multiple
  5564. * times. But reuse_swap_page() might have removed the page
  5565. * from swapcache already, so we can't check PageSwapCache().
  5566. */
  5567. if (!memcg)
  5568. return;
  5569. commit_charge(page, memcg, lrucare);
  5570. if (PageTransHuge(page)) {
  5571. nr_pages <<= compound_order(page);
  5572. VM_BUG_ON_PAGE(!PageTransHuge(page), page);
  5573. }
  5574. local_irq_disable();
  5575. mem_cgroup_charge_statistics(memcg, page, nr_pages);
  5576. memcg_check_events(memcg, page);
  5577. local_irq_enable();
  5578. if (do_swap_account && PageSwapCache(page)) {
  5579. swp_entry_t entry = { .val = page_private(page) };
  5580. /*
  5581. * The swap entry might not get freed for a long time,
  5582. * let's not wait for it. The page already received a
  5583. * memory+swap charge, drop the swap entry duplicate.
  5584. */
  5585. mem_cgroup_uncharge_swap(entry);
  5586. }
  5587. }
  5588. /**
  5589. * mem_cgroup_cancel_charge - cancel a page charge
  5590. * @page: page to charge
  5591. * @memcg: memcg to charge the page to
  5592. *
  5593. * Cancel a charge transaction started by mem_cgroup_try_charge().
  5594. */
  5595. void mem_cgroup_cancel_charge(struct page *page, struct mem_cgroup *memcg)
  5596. {
  5597. unsigned int nr_pages = 1;
  5598. if (mem_cgroup_disabled())
  5599. return;
  5600. /*
  5601. * Swap faults will attempt to charge the same page multiple
  5602. * times. But reuse_swap_page() might have removed the page
  5603. * from swapcache already, so we can't check PageSwapCache().
  5604. */
  5605. if (!memcg)
  5606. return;
  5607. if (PageTransHuge(page)) {
  5608. nr_pages <<= compound_order(page);
  5609. VM_BUG_ON_PAGE(!PageTransHuge(page), page);
  5610. }
  5611. cancel_charge(memcg, nr_pages);
  5612. }
  5613. static void uncharge_batch(struct mem_cgroup *memcg, unsigned long pgpgout,
  5614. unsigned long nr_mem, unsigned long nr_memsw,
  5615. unsigned long nr_anon, unsigned long nr_file,
  5616. unsigned long nr_huge, struct page *dummy_page)
  5617. {
  5618. unsigned long flags;
  5619. if (!mem_cgroup_is_root(memcg)) {
  5620. if (nr_mem)
  5621. res_counter_uncharge(&memcg->res,
  5622. nr_mem * PAGE_SIZE);
  5623. if (nr_memsw)
  5624. res_counter_uncharge(&memcg->memsw,
  5625. nr_memsw * PAGE_SIZE);
  5626. memcg_oom_recover(memcg);
  5627. }
  5628. local_irq_save(flags);
  5629. __this_cpu_sub(memcg->stat->count[MEM_CGROUP_STAT_RSS], nr_anon);
  5630. __this_cpu_sub(memcg->stat->count[MEM_CGROUP_STAT_CACHE], nr_file);
  5631. __this_cpu_sub(memcg->stat->count[MEM_CGROUP_STAT_RSS_HUGE], nr_huge);
  5632. __this_cpu_add(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGOUT], pgpgout);
  5633. __this_cpu_add(memcg->stat->nr_page_events, nr_anon + nr_file);
  5634. memcg_check_events(memcg, dummy_page);
  5635. local_irq_restore(flags);
  5636. }
  5637. static void uncharge_list(struct list_head *page_list)
  5638. {
  5639. struct mem_cgroup *memcg = NULL;
  5640. unsigned long nr_memsw = 0;
  5641. unsigned long nr_anon = 0;
  5642. unsigned long nr_file = 0;
  5643. unsigned long nr_huge = 0;
  5644. unsigned long pgpgout = 0;
  5645. unsigned long nr_mem = 0;
  5646. struct list_head *next;
  5647. struct page *page;
  5648. next = page_list->next;
  5649. do {
  5650. unsigned int nr_pages = 1;
  5651. struct page_cgroup *pc;
  5652. page = list_entry(next, struct page, lru);
  5653. next = page->lru.next;
  5654. VM_BUG_ON_PAGE(PageLRU(page), page);
  5655. VM_BUG_ON_PAGE(page_count(page), page);
  5656. pc = lookup_page_cgroup(page);
  5657. if (!PageCgroupUsed(pc))
  5658. continue;
  5659. /*
  5660. * Nobody should be changing or seriously looking at
  5661. * pc->mem_cgroup and pc->flags at this point, we have
  5662. * fully exclusive access to the page.
  5663. */
  5664. if (memcg != pc->mem_cgroup) {
  5665. if (memcg) {
  5666. uncharge_batch(memcg, pgpgout, nr_mem, nr_memsw,
  5667. nr_anon, nr_file, nr_huge, page);
  5668. pgpgout = nr_mem = nr_memsw = 0;
  5669. nr_anon = nr_file = nr_huge = 0;
  5670. }
  5671. memcg = pc->mem_cgroup;
  5672. }
  5673. if (PageTransHuge(page)) {
  5674. nr_pages <<= compound_order(page);
  5675. VM_BUG_ON_PAGE(!PageTransHuge(page), page);
  5676. nr_huge += nr_pages;
  5677. }
  5678. if (PageAnon(page))
  5679. nr_anon += nr_pages;
  5680. else
  5681. nr_file += nr_pages;
  5682. if (pc->flags & PCG_MEM)
  5683. nr_mem += nr_pages;
  5684. if (pc->flags & PCG_MEMSW)
  5685. nr_memsw += nr_pages;
  5686. pc->flags = 0;
  5687. pgpgout++;
  5688. } while (next != page_list);
  5689. if (memcg)
  5690. uncharge_batch(memcg, pgpgout, nr_mem, nr_memsw,
  5691. nr_anon, nr_file, nr_huge, page);
  5692. }
  5693. /**
  5694. * mem_cgroup_uncharge - uncharge a page
  5695. * @page: page to uncharge
  5696. *
  5697. * Uncharge a page previously charged with mem_cgroup_try_charge() and
  5698. * mem_cgroup_commit_charge().
  5699. */
  5700. void mem_cgroup_uncharge(struct page *page)
  5701. {
  5702. struct page_cgroup *pc;
  5703. if (mem_cgroup_disabled())
  5704. return;
  5705. /* Don't touch page->lru of any random page, pre-check: */
  5706. pc = lookup_page_cgroup(page);
  5707. if (!PageCgroupUsed(pc))
  5708. return;
  5709. INIT_LIST_HEAD(&page->lru);
  5710. uncharge_list(&page->lru);
  5711. }
  5712. /**
  5713. * mem_cgroup_uncharge_list - uncharge a list of page
  5714. * @page_list: list of pages to uncharge
  5715. *
  5716. * Uncharge a list of pages previously charged with
  5717. * mem_cgroup_try_charge() and mem_cgroup_commit_charge().
  5718. */
  5719. void mem_cgroup_uncharge_list(struct list_head *page_list)
  5720. {
  5721. if (mem_cgroup_disabled())
  5722. return;
  5723. if (!list_empty(page_list))
  5724. uncharge_list(page_list);
  5725. }
  5726. /**
  5727. * mem_cgroup_migrate - migrate a charge to another page
  5728. * @oldpage: currently charged page
  5729. * @newpage: page to transfer the charge to
  5730. * @lrucare: both pages might be on the LRU already
  5731. *
  5732. * Migrate the charge from @oldpage to @newpage.
  5733. *
  5734. * Both pages must be locked, @newpage->mapping must be set up.
  5735. */
  5736. void mem_cgroup_migrate(struct page *oldpage, struct page *newpage,
  5737. bool lrucare)
  5738. {
  5739. struct page_cgroup *pc;
  5740. int isolated;
  5741. VM_BUG_ON_PAGE(!PageLocked(oldpage), oldpage);
  5742. VM_BUG_ON_PAGE(!PageLocked(newpage), newpage);
  5743. VM_BUG_ON_PAGE(!lrucare && PageLRU(oldpage), oldpage);
  5744. VM_BUG_ON_PAGE(!lrucare && PageLRU(newpage), newpage);
  5745. VM_BUG_ON_PAGE(PageAnon(oldpage) != PageAnon(newpage), newpage);
  5746. VM_BUG_ON_PAGE(PageTransHuge(oldpage) != PageTransHuge(newpage),
  5747. newpage);
  5748. if (mem_cgroup_disabled())
  5749. return;
  5750. /* Page cache replacement: new page already charged? */
  5751. pc = lookup_page_cgroup(newpage);
  5752. if (PageCgroupUsed(pc))
  5753. return;
  5754. /* Re-entrant migration: old page already uncharged? */
  5755. pc = lookup_page_cgroup(oldpage);
  5756. if (!PageCgroupUsed(pc))
  5757. return;
  5758. VM_BUG_ON_PAGE(!(pc->flags & PCG_MEM), oldpage);
  5759. VM_BUG_ON_PAGE(do_swap_account && !(pc->flags & PCG_MEMSW), oldpage);
  5760. if (lrucare)
  5761. lock_page_lru(oldpage, &isolated);
  5762. pc->flags = 0;
  5763. if (lrucare)
  5764. unlock_page_lru(oldpage, isolated);
  5765. commit_charge(newpage, pc->mem_cgroup, lrucare);
  5766. }
  5767. /*
  5768. * subsys_initcall() for memory controller.
  5769. *
  5770. * Some parts like hotcpu_notifier() have to be initialized from this context
  5771. * because of lock dependencies (cgroup_lock -> cpu hotplug) but basically
  5772. * everything that doesn't depend on a specific mem_cgroup structure should
  5773. * be initialized from here.
  5774. */
  5775. static int __init mem_cgroup_init(void)
  5776. {
  5777. hotcpu_notifier(memcg_cpu_hotplug_callback, 0);
  5778. enable_swap_cgroup();
  5779. mem_cgroup_soft_limit_tree_init();
  5780. memcg_stock_init();
  5781. return 0;
  5782. }
  5783. subsys_initcall(mem_cgroup_init);