memcontrol.c 174 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655
  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. static void mem_cgroup_start_move(struct mem_cgroup *memcg)
  1347. {
  1348. atomic_inc(&memcg->moving_account);
  1349. synchronize_rcu();
  1350. }
  1351. static void mem_cgroup_end_move(struct mem_cgroup *memcg)
  1352. {
  1353. /*
  1354. * Now, mem_cgroup_clear_mc() may call this function with NULL.
  1355. * We check NULL in callee rather than caller.
  1356. */
  1357. if (memcg)
  1358. atomic_dec(&memcg->moving_account);
  1359. }
  1360. /*
  1361. * A routine for checking "mem" is under move_account() or not.
  1362. *
  1363. * Checking a cgroup is mc.from or mc.to or under hierarchy of
  1364. * moving cgroups. This is for waiting at high-memory pressure
  1365. * caused by "move".
  1366. */
  1367. static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
  1368. {
  1369. struct mem_cgroup *from;
  1370. struct mem_cgroup *to;
  1371. bool ret = false;
  1372. /*
  1373. * Unlike task_move routines, we access mc.to, mc.from not under
  1374. * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
  1375. */
  1376. spin_lock(&mc.lock);
  1377. from = mc.from;
  1378. to = mc.to;
  1379. if (!from)
  1380. goto unlock;
  1381. ret = mem_cgroup_same_or_subtree(memcg, from)
  1382. || mem_cgroup_same_or_subtree(memcg, to);
  1383. unlock:
  1384. spin_unlock(&mc.lock);
  1385. return ret;
  1386. }
  1387. static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
  1388. {
  1389. if (mc.moving_task && current != mc.moving_task) {
  1390. if (mem_cgroup_under_move(memcg)) {
  1391. DEFINE_WAIT(wait);
  1392. prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
  1393. /* moving charge context might have finished. */
  1394. if (mc.moving_task)
  1395. schedule();
  1396. finish_wait(&mc.waitq, &wait);
  1397. return true;
  1398. }
  1399. }
  1400. return false;
  1401. }
  1402. /*
  1403. * Take this lock when
  1404. * - a code tries to modify page's memcg while it's USED.
  1405. * - a code tries to modify page state accounting in a memcg.
  1406. */
  1407. static void move_lock_mem_cgroup(struct mem_cgroup *memcg,
  1408. unsigned long *flags)
  1409. {
  1410. spin_lock_irqsave(&memcg->move_lock, *flags);
  1411. }
  1412. static void move_unlock_mem_cgroup(struct mem_cgroup *memcg,
  1413. unsigned long *flags)
  1414. {
  1415. spin_unlock_irqrestore(&memcg->move_lock, *flags);
  1416. }
  1417. #define K(x) ((x) << (PAGE_SHIFT-10))
  1418. /**
  1419. * mem_cgroup_print_oom_info: Print OOM information relevant to memory controller.
  1420. * @memcg: The memory cgroup that went over limit
  1421. * @p: Task that is going to be killed
  1422. *
  1423. * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
  1424. * enabled
  1425. */
  1426. void mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p)
  1427. {
  1428. /* oom_info_lock ensures that parallel ooms do not interleave */
  1429. static DEFINE_MUTEX(oom_info_lock);
  1430. struct mem_cgroup *iter;
  1431. unsigned int i;
  1432. if (!p)
  1433. return;
  1434. mutex_lock(&oom_info_lock);
  1435. rcu_read_lock();
  1436. pr_info("Task in ");
  1437. pr_cont_cgroup_path(task_cgroup(p, memory_cgrp_id));
  1438. pr_info(" killed as a result of limit of ");
  1439. pr_cont_cgroup_path(memcg->css.cgroup);
  1440. pr_info("\n");
  1441. rcu_read_unlock();
  1442. pr_info("memory: usage %llukB, limit %llukB, failcnt %llu\n",
  1443. res_counter_read_u64(&memcg->res, RES_USAGE) >> 10,
  1444. res_counter_read_u64(&memcg->res, RES_LIMIT) >> 10,
  1445. res_counter_read_u64(&memcg->res, RES_FAILCNT));
  1446. pr_info("memory+swap: usage %llukB, limit %llukB, failcnt %llu\n",
  1447. res_counter_read_u64(&memcg->memsw, RES_USAGE) >> 10,
  1448. res_counter_read_u64(&memcg->memsw, RES_LIMIT) >> 10,
  1449. res_counter_read_u64(&memcg->memsw, RES_FAILCNT));
  1450. pr_info("kmem: usage %llukB, limit %llukB, failcnt %llu\n",
  1451. res_counter_read_u64(&memcg->kmem, RES_USAGE) >> 10,
  1452. res_counter_read_u64(&memcg->kmem, RES_LIMIT) >> 10,
  1453. res_counter_read_u64(&memcg->kmem, RES_FAILCNT));
  1454. for_each_mem_cgroup_tree(iter, memcg) {
  1455. pr_info("Memory cgroup stats for ");
  1456. pr_cont_cgroup_path(iter->css.cgroup);
  1457. pr_cont(":");
  1458. for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
  1459. if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
  1460. continue;
  1461. pr_cont(" %s:%ldKB", mem_cgroup_stat_names[i],
  1462. K(mem_cgroup_read_stat(iter, i)));
  1463. }
  1464. for (i = 0; i < NR_LRU_LISTS; i++)
  1465. pr_cont(" %s:%luKB", mem_cgroup_lru_names[i],
  1466. K(mem_cgroup_nr_lru_pages(iter, BIT(i))));
  1467. pr_cont("\n");
  1468. }
  1469. mutex_unlock(&oom_info_lock);
  1470. }
  1471. /*
  1472. * This function returns the number of memcg under hierarchy tree. Returns
  1473. * 1(self count) if no children.
  1474. */
  1475. static int mem_cgroup_count_children(struct mem_cgroup *memcg)
  1476. {
  1477. int num = 0;
  1478. struct mem_cgroup *iter;
  1479. for_each_mem_cgroup_tree(iter, memcg)
  1480. num++;
  1481. return num;
  1482. }
  1483. /*
  1484. * Return the memory (and swap, if configured) limit for a memcg.
  1485. */
  1486. static u64 mem_cgroup_get_limit(struct mem_cgroup *memcg)
  1487. {
  1488. u64 limit;
  1489. limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
  1490. /*
  1491. * Do not consider swap space if we cannot swap due to swappiness
  1492. */
  1493. if (mem_cgroup_swappiness(memcg)) {
  1494. u64 memsw;
  1495. limit += total_swap_pages << PAGE_SHIFT;
  1496. memsw = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
  1497. /*
  1498. * If memsw is finite and limits the amount of swap space
  1499. * available to this memcg, return that limit.
  1500. */
  1501. limit = min(limit, memsw);
  1502. }
  1503. return limit;
  1504. }
  1505. static void mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
  1506. int order)
  1507. {
  1508. struct mem_cgroup *iter;
  1509. unsigned long chosen_points = 0;
  1510. unsigned long totalpages;
  1511. unsigned int points = 0;
  1512. struct task_struct *chosen = NULL;
  1513. /*
  1514. * If current has a pending SIGKILL or is exiting, then automatically
  1515. * select it. The goal is to allow it to allocate so that it may
  1516. * quickly exit and free its memory.
  1517. */
  1518. if (fatal_signal_pending(current) || current->flags & PF_EXITING) {
  1519. set_thread_flag(TIF_MEMDIE);
  1520. return;
  1521. }
  1522. check_panic_on_oom(CONSTRAINT_MEMCG, gfp_mask, order, NULL);
  1523. totalpages = mem_cgroup_get_limit(memcg) >> PAGE_SHIFT ? : 1;
  1524. for_each_mem_cgroup_tree(iter, memcg) {
  1525. struct css_task_iter it;
  1526. struct task_struct *task;
  1527. css_task_iter_start(&iter->css, &it);
  1528. while ((task = css_task_iter_next(&it))) {
  1529. switch (oom_scan_process_thread(task, totalpages, NULL,
  1530. false)) {
  1531. case OOM_SCAN_SELECT:
  1532. if (chosen)
  1533. put_task_struct(chosen);
  1534. chosen = task;
  1535. chosen_points = ULONG_MAX;
  1536. get_task_struct(chosen);
  1537. /* fall through */
  1538. case OOM_SCAN_CONTINUE:
  1539. continue;
  1540. case OOM_SCAN_ABORT:
  1541. css_task_iter_end(&it);
  1542. mem_cgroup_iter_break(memcg, iter);
  1543. if (chosen)
  1544. put_task_struct(chosen);
  1545. return;
  1546. case OOM_SCAN_OK:
  1547. break;
  1548. };
  1549. points = oom_badness(task, memcg, NULL, totalpages);
  1550. if (!points || points < chosen_points)
  1551. continue;
  1552. /* Prefer thread group leaders for display purposes */
  1553. if (points == chosen_points &&
  1554. thread_group_leader(chosen))
  1555. continue;
  1556. if (chosen)
  1557. put_task_struct(chosen);
  1558. chosen = task;
  1559. chosen_points = points;
  1560. get_task_struct(chosen);
  1561. }
  1562. css_task_iter_end(&it);
  1563. }
  1564. if (!chosen)
  1565. return;
  1566. points = chosen_points * 1000 / totalpages;
  1567. oom_kill_process(chosen, gfp_mask, order, points, totalpages, memcg,
  1568. NULL, "Memory cgroup out of memory");
  1569. }
  1570. /**
  1571. * test_mem_cgroup_node_reclaimable
  1572. * @memcg: the target memcg
  1573. * @nid: the node ID to be checked.
  1574. * @noswap : specify true here if the user wants flle only information.
  1575. *
  1576. * This function returns whether the specified memcg contains any
  1577. * reclaimable pages on a node. Returns true if there are any reclaimable
  1578. * pages in the node.
  1579. */
  1580. static bool test_mem_cgroup_node_reclaimable(struct mem_cgroup *memcg,
  1581. int nid, bool noswap)
  1582. {
  1583. if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_FILE))
  1584. return true;
  1585. if (noswap || !total_swap_pages)
  1586. return false;
  1587. if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_ANON))
  1588. return true;
  1589. return false;
  1590. }
  1591. #if MAX_NUMNODES > 1
  1592. /*
  1593. * Always updating the nodemask is not very good - even if we have an empty
  1594. * list or the wrong list here, we can start from some node and traverse all
  1595. * nodes based on the zonelist. So update the list loosely once per 10 secs.
  1596. *
  1597. */
  1598. static void mem_cgroup_may_update_nodemask(struct mem_cgroup *memcg)
  1599. {
  1600. int nid;
  1601. /*
  1602. * numainfo_events > 0 means there was at least NUMAINFO_EVENTS_TARGET
  1603. * pagein/pageout changes since the last update.
  1604. */
  1605. if (!atomic_read(&memcg->numainfo_events))
  1606. return;
  1607. if (atomic_inc_return(&memcg->numainfo_updating) > 1)
  1608. return;
  1609. /* make a nodemask where this memcg uses memory from */
  1610. memcg->scan_nodes = node_states[N_MEMORY];
  1611. for_each_node_mask(nid, node_states[N_MEMORY]) {
  1612. if (!test_mem_cgroup_node_reclaimable(memcg, nid, false))
  1613. node_clear(nid, memcg->scan_nodes);
  1614. }
  1615. atomic_set(&memcg->numainfo_events, 0);
  1616. atomic_set(&memcg->numainfo_updating, 0);
  1617. }
  1618. /*
  1619. * Selecting a node where we start reclaim from. Because what we need is just
  1620. * reducing usage counter, start from anywhere is O,K. Considering
  1621. * memory reclaim from current node, there are pros. and cons.
  1622. *
  1623. * Freeing memory from current node means freeing memory from a node which
  1624. * we'll use or we've used. So, it may make LRU bad. And if several threads
  1625. * hit limits, it will see a contention on a node. But freeing from remote
  1626. * node means more costs for memory reclaim because of memory latency.
  1627. *
  1628. * Now, we use round-robin. Better algorithm is welcomed.
  1629. */
  1630. int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
  1631. {
  1632. int node;
  1633. mem_cgroup_may_update_nodemask(memcg);
  1634. node = memcg->last_scanned_node;
  1635. node = next_node(node, memcg->scan_nodes);
  1636. if (node == MAX_NUMNODES)
  1637. node = first_node(memcg->scan_nodes);
  1638. /*
  1639. * We call this when we hit limit, not when pages are added to LRU.
  1640. * No LRU may hold pages because all pages are UNEVICTABLE or
  1641. * memcg is too small and all pages are not on LRU. In that case,
  1642. * we use curret node.
  1643. */
  1644. if (unlikely(node == MAX_NUMNODES))
  1645. node = numa_node_id();
  1646. memcg->last_scanned_node = node;
  1647. return node;
  1648. }
  1649. /*
  1650. * Check all nodes whether it contains reclaimable pages or not.
  1651. * For quick scan, we make use of scan_nodes. This will allow us to skip
  1652. * unused nodes. But scan_nodes is lazily updated and may not cotain
  1653. * enough new information. We need to do double check.
  1654. */
  1655. static bool mem_cgroup_reclaimable(struct mem_cgroup *memcg, bool noswap)
  1656. {
  1657. int nid;
  1658. /*
  1659. * quick check...making use of scan_node.
  1660. * We can skip unused nodes.
  1661. */
  1662. if (!nodes_empty(memcg->scan_nodes)) {
  1663. for (nid = first_node(memcg->scan_nodes);
  1664. nid < MAX_NUMNODES;
  1665. nid = next_node(nid, memcg->scan_nodes)) {
  1666. if (test_mem_cgroup_node_reclaimable(memcg, nid, noswap))
  1667. return true;
  1668. }
  1669. }
  1670. /*
  1671. * Check rest of nodes.
  1672. */
  1673. for_each_node_state(nid, N_MEMORY) {
  1674. if (node_isset(nid, memcg->scan_nodes))
  1675. continue;
  1676. if (test_mem_cgroup_node_reclaimable(memcg, nid, noswap))
  1677. return true;
  1678. }
  1679. return false;
  1680. }
  1681. #else
  1682. int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
  1683. {
  1684. return 0;
  1685. }
  1686. static bool mem_cgroup_reclaimable(struct mem_cgroup *memcg, bool noswap)
  1687. {
  1688. return test_mem_cgroup_node_reclaimable(memcg, 0, noswap);
  1689. }
  1690. #endif
  1691. static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg,
  1692. struct zone *zone,
  1693. gfp_t gfp_mask,
  1694. unsigned long *total_scanned)
  1695. {
  1696. struct mem_cgroup *victim = NULL;
  1697. int total = 0;
  1698. int loop = 0;
  1699. unsigned long excess;
  1700. unsigned long nr_scanned;
  1701. struct mem_cgroup_reclaim_cookie reclaim = {
  1702. .zone = zone,
  1703. .priority = 0,
  1704. };
  1705. excess = res_counter_soft_limit_excess(&root_memcg->res) >> PAGE_SHIFT;
  1706. while (1) {
  1707. victim = mem_cgroup_iter(root_memcg, victim, &reclaim);
  1708. if (!victim) {
  1709. loop++;
  1710. if (loop >= 2) {
  1711. /*
  1712. * If we have not been able to reclaim
  1713. * anything, it might because there are
  1714. * no reclaimable pages under this hierarchy
  1715. */
  1716. if (!total)
  1717. break;
  1718. /*
  1719. * We want to do more targeted reclaim.
  1720. * excess >> 2 is not to excessive so as to
  1721. * reclaim too much, nor too less that we keep
  1722. * coming back to reclaim from this cgroup
  1723. */
  1724. if (total >= (excess >> 2) ||
  1725. (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS))
  1726. break;
  1727. }
  1728. continue;
  1729. }
  1730. if (!mem_cgroup_reclaimable(victim, false))
  1731. continue;
  1732. total += mem_cgroup_shrink_node_zone(victim, gfp_mask, false,
  1733. zone, &nr_scanned);
  1734. *total_scanned += nr_scanned;
  1735. if (!res_counter_soft_limit_excess(&root_memcg->res))
  1736. break;
  1737. }
  1738. mem_cgroup_iter_break(root_memcg, victim);
  1739. return total;
  1740. }
  1741. #ifdef CONFIG_LOCKDEP
  1742. static struct lockdep_map memcg_oom_lock_dep_map = {
  1743. .name = "memcg_oom_lock",
  1744. };
  1745. #endif
  1746. static DEFINE_SPINLOCK(memcg_oom_lock);
  1747. /*
  1748. * Check OOM-Killer is already running under our hierarchy.
  1749. * If someone is running, return false.
  1750. */
  1751. static bool mem_cgroup_oom_trylock(struct mem_cgroup *memcg)
  1752. {
  1753. struct mem_cgroup *iter, *failed = NULL;
  1754. spin_lock(&memcg_oom_lock);
  1755. for_each_mem_cgroup_tree(iter, memcg) {
  1756. if (iter->oom_lock) {
  1757. /*
  1758. * this subtree of our hierarchy is already locked
  1759. * so we cannot give a lock.
  1760. */
  1761. failed = iter;
  1762. mem_cgroup_iter_break(memcg, iter);
  1763. break;
  1764. } else
  1765. iter->oom_lock = true;
  1766. }
  1767. if (failed) {
  1768. /*
  1769. * OK, we failed to lock the whole subtree so we have
  1770. * to clean up what we set up to the failing subtree
  1771. */
  1772. for_each_mem_cgroup_tree(iter, memcg) {
  1773. if (iter == failed) {
  1774. mem_cgroup_iter_break(memcg, iter);
  1775. break;
  1776. }
  1777. iter->oom_lock = false;
  1778. }
  1779. } else
  1780. mutex_acquire(&memcg_oom_lock_dep_map, 0, 1, _RET_IP_);
  1781. spin_unlock(&memcg_oom_lock);
  1782. return !failed;
  1783. }
  1784. static void mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
  1785. {
  1786. struct mem_cgroup *iter;
  1787. spin_lock(&memcg_oom_lock);
  1788. mutex_release(&memcg_oom_lock_dep_map, 1, _RET_IP_);
  1789. for_each_mem_cgroup_tree(iter, memcg)
  1790. iter->oom_lock = false;
  1791. spin_unlock(&memcg_oom_lock);
  1792. }
  1793. static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
  1794. {
  1795. struct mem_cgroup *iter;
  1796. for_each_mem_cgroup_tree(iter, memcg)
  1797. atomic_inc(&iter->under_oom);
  1798. }
  1799. static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
  1800. {
  1801. struct mem_cgroup *iter;
  1802. /*
  1803. * When a new child is created while the hierarchy is under oom,
  1804. * mem_cgroup_oom_lock() may not be called. We have to use
  1805. * atomic_add_unless() here.
  1806. */
  1807. for_each_mem_cgroup_tree(iter, memcg)
  1808. atomic_add_unless(&iter->under_oom, -1, 0);
  1809. }
  1810. static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
  1811. struct oom_wait_info {
  1812. struct mem_cgroup *memcg;
  1813. wait_queue_t wait;
  1814. };
  1815. static int memcg_oom_wake_function(wait_queue_t *wait,
  1816. unsigned mode, int sync, void *arg)
  1817. {
  1818. struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg;
  1819. struct mem_cgroup *oom_wait_memcg;
  1820. struct oom_wait_info *oom_wait_info;
  1821. oom_wait_info = container_of(wait, struct oom_wait_info, wait);
  1822. oom_wait_memcg = oom_wait_info->memcg;
  1823. /*
  1824. * Both of oom_wait_info->memcg and wake_memcg are stable under us.
  1825. * Then we can use css_is_ancestor without taking care of RCU.
  1826. */
  1827. if (!mem_cgroup_same_or_subtree(oom_wait_memcg, wake_memcg)
  1828. && !mem_cgroup_same_or_subtree(wake_memcg, oom_wait_memcg))
  1829. return 0;
  1830. return autoremove_wake_function(wait, mode, sync, arg);
  1831. }
  1832. static void memcg_wakeup_oom(struct mem_cgroup *memcg)
  1833. {
  1834. atomic_inc(&memcg->oom_wakeups);
  1835. /* for filtering, pass "memcg" as argument. */
  1836. __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
  1837. }
  1838. static void memcg_oom_recover(struct mem_cgroup *memcg)
  1839. {
  1840. if (memcg && atomic_read(&memcg->under_oom))
  1841. memcg_wakeup_oom(memcg);
  1842. }
  1843. static void mem_cgroup_oom(struct mem_cgroup *memcg, gfp_t mask, int order)
  1844. {
  1845. if (!current->memcg_oom.may_oom)
  1846. return;
  1847. /*
  1848. * We are in the middle of the charge context here, so we
  1849. * don't want to block when potentially sitting on a callstack
  1850. * that holds all kinds of filesystem and mm locks.
  1851. *
  1852. * Also, the caller may handle a failed allocation gracefully
  1853. * (like optional page cache readahead) and so an OOM killer
  1854. * invocation might not even be necessary.
  1855. *
  1856. * That's why we don't do anything here except remember the
  1857. * OOM context and then deal with it at the end of the page
  1858. * fault when the stack is unwound, the locks are released,
  1859. * and when we know whether the fault was overall successful.
  1860. */
  1861. css_get(&memcg->css);
  1862. current->memcg_oom.memcg = memcg;
  1863. current->memcg_oom.gfp_mask = mask;
  1864. current->memcg_oom.order = order;
  1865. }
  1866. /**
  1867. * mem_cgroup_oom_synchronize - complete memcg OOM handling
  1868. * @handle: actually kill/wait or just clean up the OOM state
  1869. *
  1870. * This has to be called at the end of a page fault if the memcg OOM
  1871. * handler was enabled.
  1872. *
  1873. * Memcg supports userspace OOM handling where failed allocations must
  1874. * sleep on a waitqueue until the userspace task resolves the
  1875. * situation. Sleeping directly in the charge context with all kinds
  1876. * of locks held is not a good idea, instead we remember an OOM state
  1877. * in the task and mem_cgroup_oom_synchronize() has to be called at
  1878. * the end of the page fault to complete the OOM handling.
  1879. *
  1880. * Returns %true if an ongoing memcg OOM situation was detected and
  1881. * completed, %false otherwise.
  1882. */
  1883. bool mem_cgroup_oom_synchronize(bool handle)
  1884. {
  1885. struct mem_cgroup *memcg = current->memcg_oom.memcg;
  1886. struct oom_wait_info owait;
  1887. bool locked;
  1888. /* OOM is global, do not handle */
  1889. if (!memcg)
  1890. return false;
  1891. if (!handle)
  1892. goto cleanup;
  1893. owait.memcg = memcg;
  1894. owait.wait.flags = 0;
  1895. owait.wait.func = memcg_oom_wake_function;
  1896. owait.wait.private = current;
  1897. INIT_LIST_HEAD(&owait.wait.task_list);
  1898. prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
  1899. mem_cgroup_mark_under_oom(memcg);
  1900. locked = mem_cgroup_oom_trylock(memcg);
  1901. if (locked)
  1902. mem_cgroup_oom_notify(memcg);
  1903. if (locked && !memcg->oom_kill_disable) {
  1904. mem_cgroup_unmark_under_oom(memcg);
  1905. finish_wait(&memcg_oom_waitq, &owait.wait);
  1906. mem_cgroup_out_of_memory(memcg, current->memcg_oom.gfp_mask,
  1907. current->memcg_oom.order);
  1908. } else {
  1909. schedule();
  1910. mem_cgroup_unmark_under_oom(memcg);
  1911. finish_wait(&memcg_oom_waitq, &owait.wait);
  1912. }
  1913. if (locked) {
  1914. mem_cgroup_oom_unlock(memcg);
  1915. /*
  1916. * There is no guarantee that an OOM-lock contender
  1917. * sees the wakeups triggered by the OOM kill
  1918. * uncharges. Wake any sleepers explicitely.
  1919. */
  1920. memcg_oom_recover(memcg);
  1921. }
  1922. cleanup:
  1923. current->memcg_oom.memcg = NULL;
  1924. css_put(&memcg->css);
  1925. return true;
  1926. }
  1927. /**
  1928. * mem_cgroup_begin_page_stat - begin a page state statistics transaction
  1929. * @page: page that is going to change accounted state
  1930. * @locked: &memcg->move_lock slowpath was taken
  1931. * @flags: IRQ-state flags for &memcg->move_lock
  1932. *
  1933. * This function must mark the beginning of an accounted page state
  1934. * change to prevent double accounting when the page is concurrently
  1935. * being moved to another memcg:
  1936. *
  1937. * memcg = mem_cgroup_begin_page_stat(page, &locked, &flags);
  1938. * if (TestClearPageState(page))
  1939. * mem_cgroup_update_page_stat(memcg, state, -1);
  1940. * mem_cgroup_end_page_stat(memcg, locked, flags);
  1941. *
  1942. * The RCU lock is held throughout the transaction. The fast path can
  1943. * get away without acquiring the memcg->move_lock (@locked is false)
  1944. * because page moving starts with an RCU grace period.
  1945. *
  1946. * The RCU lock also protects the memcg from being freed when the page
  1947. * state that is going to change is the only thing preventing the page
  1948. * from being uncharged. E.g. end-writeback clearing PageWriteback(),
  1949. * which allows migration to go ahead and uncharge the page before the
  1950. * account transaction might be complete.
  1951. */
  1952. struct mem_cgroup *mem_cgroup_begin_page_stat(struct page *page,
  1953. bool *locked,
  1954. unsigned long *flags)
  1955. {
  1956. struct mem_cgroup *memcg;
  1957. struct page_cgroup *pc;
  1958. rcu_read_lock();
  1959. if (mem_cgroup_disabled())
  1960. return NULL;
  1961. pc = lookup_page_cgroup(page);
  1962. again:
  1963. memcg = pc->mem_cgroup;
  1964. if (unlikely(!memcg || !PageCgroupUsed(pc)))
  1965. return NULL;
  1966. *locked = false;
  1967. if (atomic_read(&memcg->moving_account) <= 0)
  1968. return memcg;
  1969. move_lock_mem_cgroup(memcg, flags);
  1970. if (memcg != pc->mem_cgroup || !PageCgroupUsed(pc)) {
  1971. move_unlock_mem_cgroup(memcg, flags);
  1972. goto again;
  1973. }
  1974. *locked = true;
  1975. return memcg;
  1976. }
  1977. /**
  1978. * mem_cgroup_end_page_stat - finish a page state statistics transaction
  1979. * @memcg: the memcg that was accounted against
  1980. * @locked: value received from mem_cgroup_begin_page_stat()
  1981. * @flags: value received from mem_cgroup_begin_page_stat()
  1982. */
  1983. void mem_cgroup_end_page_stat(struct mem_cgroup *memcg, bool locked,
  1984. unsigned long flags)
  1985. {
  1986. if (memcg && locked)
  1987. move_unlock_mem_cgroup(memcg, &flags);
  1988. rcu_read_unlock();
  1989. }
  1990. /**
  1991. * mem_cgroup_update_page_stat - update page state statistics
  1992. * @memcg: memcg to account against
  1993. * @idx: page state item to account
  1994. * @val: number of pages (positive or negative)
  1995. *
  1996. * See mem_cgroup_begin_page_stat() for locking requirements.
  1997. */
  1998. void mem_cgroup_update_page_stat(struct mem_cgroup *memcg,
  1999. enum mem_cgroup_stat_index idx, int val)
  2000. {
  2001. VM_BUG_ON(!rcu_read_lock_held());
  2002. if (memcg)
  2003. this_cpu_add(memcg->stat->count[idx], val);
  2004. }
  2005. /*
  2006. * size of first charge trial. "32" comes from vmscan.c's magic value.
  2007. * TODO: maybe necessary to use big numbers in big irons.
  2008. */
  2009. #define CHARGE_BATCH 32U
  2010. struct memcg_stock_pcp {
  2011. struct mem_cgroup *cached; /* this never be root cgroup */
  2012. unsigned int nr_pages;
  2013. struct work_struct work;
  2014. unsigned long flags;
  2015. #define FLUSHING_CACHED_CHARGE 0
  2016. };
  2017. static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
  2018. static DEFINE_MUTEX(percpu_charge_mutex);
  2019. /**
  2020. * consume_stock: Try to consume stocked charge on this cpu.
  2021. * @memcg: memcg to consume from.
  2022. * @nr_pages: how many pages to charge.
  2023. *
  2024. * The charges will only happen if @memcg matches the current cpu's memcg
  2025. * stock, and at least @nr_pages are available in that stock. Failure to
  2026. * service an allocation will refill the stock.
  2027. *
  2028. * returns true if successful, false otherwise.
  2029. */
  2030. static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
  2031. {
  2032. struct memcg_stock_pcp *stock;
  2033. bool ret = true;
  2034. if (nr_pages > CHARGE_BATCH)
  2035. return false;
  2036. stock = &get_cpu_var(memcg_stock);
  2037. if (memcg == stock->cached && stock->nr_pages >= nr_pages)
  2038. stock->nr_pages -= nr_pages;
  2039. else /* need to call res_counter_charge */
  2040. ret = false;
  2041. put_cpu_var(memcg_stock);
  2042. return ret;
  2043. }
  2044. /*
  2045. * Returns stocks cached in percpu to res_counter and reset cached information.
  2046. */
  2047. static void drain_stock(struct memcg_stock_pcp *stock)
  2048. {
  2049. struct mem_cgroup *old = stock->cached;
  2050. if (stock->nr_pages) {
  2051. unsigned long bytes = stock->nr_pages * PAGE_SIZE;
  2052. res_counter_uncharge(&old->res, bytes);
  2053. if (do_swap_account)
  2054. res_counter_uncharge(&old->memsw, bytes);
  2055. stock->nr_pages = 0;
  2056. }
  2057. stock->cached = NULL;
  2058. }
  2059. /*
  2060. * This must be called under preempt disabled or must be called by
  2061. * a thread which is pinned to local cpu.
  2062. */
  2063. static void drain_local_stock(struct work_struct *dummy)
  2064. {
  2065. struct memcg_stock_pcp *stock = this_cpu_ptr(&memcg_stock);
  2066. drain_stock(stock);
  2067. clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
  2068. }
  2069. static void __init memcg_stock_init(void)
  2070. {
  2071. int cpu;
  2072. for_each_possible_cpu(cpu) {
  2073. struct memcg_stock_pcp *stock =
  2074. &per_cpu(memcg_stock, cpu);
  2075. INIT_WORK(&stock->work, drain_local_stock);
  2076. }
  2077. }
  2078. /*
  2079. * Cache charges(val) which is from res_counter, to local per_cpu area.
  2080. * This will be consumed by consume_stock() function, later.
  2081. */
  2082. static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
  2083. {
  2084. struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock);
  2085. if (stock->cached != memcg) { /* reset if necessary */
  2086. drain_stock(stock);
  2087. stock->cached = memcg;
  2088. }
  2089. stock->nr_pages += nr_pages;
  2090. put_cpu_var(memcg_stock);
  2091. }
  2092. /*
  2093. * Drains all per-CPU charge caches for given root_memcg resp. subtree
  2094. * of the hierarchy under it. sync flag says whether we should block
  2095. * until the work is done.
  2096. */
  2097. static void drain_all_stock(struct mem_cgroup *root_memcg, bool sync)
  2098. {
  2099. int cpu, curcpu;
  2100. /* Notify other cpus that system-wide "drain" is running */
  2101. get_online_cpus();
  2102. curcpu = get_cpu();
  2103. for_each_online_cpu(cpu) {
  2104. struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
  2105. struct mem_cgroup *memcg;
  2106. memcg = stock->cached;
  2107. if (!memcg || !stock->nr_pages)
  2108. continue;
  2109. if (!mem_cgroup_same_or_subtree(root_memcg, memcg))
  2110. continue;
  2111. if (!test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
  2112. if (cpu == curcpu)
  2113. drain_local_stock(&stock->work);
  2114. else
  2115. schedule_work_on(cpu, &stock->work);
  2116. }
  2117. }
  2118. put_cpu();
  2119. if (!sync)
  2120. goto out;
  2121. for_each_online_cpu(cpu) {
  2122. struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
  2123. if (test_bit(FLUSHING_CACHED_CHARGE, &stock->flags))
  2124. flush_work(&stock->work);
  2125. }
  2126. out:
  2127. put_online_cpus();
  2128. }
  2129. /*
  2130. * Tries to drain stocked charges in other cpus. This function is asynchronous
  2131. * and just put a work per cpu for draining localy on each cpu. Caller can
  2132. * expects some charges will be back to res_counter later but cannot wait for
  2133. * it.
  2134. */
  2135. static void drain_all_stock_async(struct mem_cgroup *root_memcg)
  2136. {
  2137. /*
  2138. * If someone calls draining, avoid adding more kworker runs.
  2139. */
  2140. if (!mutex_trylock(&percpu_charge_mutex))
  2141. return;
  2142. drain_all_stock(root_memcg, false);
  2143. mutex_unlock(&percpu_charge_mutex);
  2144. }
  2145. /* This is a synchronous drain interface. */
  2146. static void drain_all_stock_sync(struct mem_cgroup *root_memcg)
  2147. {
  2148. /* called when force_empty is called */
  2149. mutex_lock(&percpu_charge_mutex);
  2150. drain_all_stock(root_memcg, true);
  2151. mutex_unlock(&percpu_charge_mutex);
  2152. }
  2153. /*
  2154. * This function drains percpu counter value from DEAD cpu and
  2155. * move it to local cpu. Note that this function can be preempted.
  2156. */
  2157. static void mem_cgroup_drain_pcp_counter(struct mem_cgroup *memcg, int cpu)
  2158. {
  2159. int i;
  2160. spin_lock(&memcg->pcp_counter_lock);
  2161. for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
  2162. long x = per_cpu(memcg->stat->count[i], cpu);
  2163. per_cpu(memcg->stat->count[i], cpu) = 0;
  2164. memcg->nocpu_base.count[i] += x;
  2165. }
  2166. for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
  2167. unsigned long x = per_cpu(memcg->stat->events[i], cpu);
  2168. per_cpu(memcg->stat->events[i], cpu) = 0;
  2169. memcg->nocpu_base.events[i] += x;
  2170. }
  2171. spin_unlock(&memcg->pcp_counter_lock);
  2172. }
  2173. static int memcg_cpu_hotplug_callback(struct notifier_block *nb,
  2174. unsigned long action,
  2175. void *hcpu)
  2176. {
  2177. int cpu = (unsigned long)hcpu;
  2178. struct memcg_stock_pcp *stock;
  2179. struct mem_cgroup *iter;
  2180. if (action == CPU_ONLINE)
  2181. return NOTIFY_OK;
  2182. if (action != CPU_DEAD && action != CPU_DEAD_FROZEN)
  2183. return NOTIFY_OK;
  2184. for_each_mem_cgroup(iter)
  2185. mem_cgroup_drain_pcp_counter(iter, cpu);
  2186. stock = &per_cpu(memcg_stock, cpu);
  2187. drain_stock(stock);
  2188. return NOTIFY_OK;
  2189. }
  2190. static int try_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
  2191. unsigned int nr_pages)
  2192. {
  2193. unsigned int batch = max(CHARGE_BATCH, nr_pages);
  2194. int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
  2195. struct mem_cgroup *mem_over_limit;
  2196. struct res_counter *fail_res;
  2197. unsigned long nr_reclaimed;
  2198. unsigned long long size;
  2199. bool may_swap = true;
  2200. bool drained = false;
  2201. int ret = 0;
  2202. if (mem_cgroup_is_root(memcg))
  2203. goto done;
  2204. retry:
  2205. if (consume_stock(memcg, nr_pages))
  2206. goto done;
  2207. size = batch * PAGE_SIZE;
  2208. if (!do_swap_account ||
  2209. !res_counter_charge(&memcg->memsw, size, &fail_res)) {
  2210. if (!res_counter_charge(&memcg->res, size, &fail_res))
  2211. goto done_restock;
  2212. if (do_swap_account)
  2213. res_counter_uncharge(&memcg->memsw, size);
  2214. mem_over_limit = mem_cgroup_from_res_counter(fail_res, res);
  2215. } else {
  2216. mem_over_limit = mem_cgroup_from_res_counter(fail_res, memsw);
  2217. may_swap = false;
  2218. }
  2219. if (batch > nr_pages) {
  2220. batch = nr_pages;
  2221. goto retry;
  2222. }
  2223. /*
  2224. * Unlike in global OOM situations, memcg is not in a physical
  2225. * memory shortage. Allow dying and OOM-killed tasks to
  2226. * bypass the last charges so that they can exit quickly and
  2227. * free their memory.
  2228. */
  2229. if (unlikely(test_thread_flag(TIF_MEMDIE) ||
  2230. fatal_signal_pending(current) ||
  2231. current->flags & PF_EXITING))
  2232. goto bypass;
  2233. if (unlikely(task_in_memcg_oom(current)))
  2234. goto nomem;
  2235. if (!(gfp_mask & __GFP_WAIT))
  2236. goto nomem;
  2237. nr_reclaimed = try_to_free_mem_cgroup_pages(mem_over_limit, nr_pages,
  2238. gfp_mask, may_swap);
  2239. if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
  2240. goto retry;
  2241. if (!drained) {
  2242. drain_all_stock_async(mem_over_limit);
  2243. drained = true;
  2244. goto retry;
  2245. }
  2246. if (gfp_mask & __GFP_NORETRY)
  2247. goto nomem;
  2248. /*
  2249. * Even though the limit is exceeded at this point, reclaim
  2250. * may have been able to free some pages. Retry the charge
  2251. * before killing the task.
  2252. *
  2253. * Only for regular pages, though: huge pages are rather
  2254. * unlikely to succeed so close to the limit, and we fall back
  2255. * to regular pages anyway in case of failure.
  2256. */
  2257. if (nr_reclaimed && nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER))
  2258. goto retry;
  2259. /*
  2260. * At task move, charge accounts can be doubly counted. So, it's
  2261. * better to wait until the end of task_move if something is going on.
  2262. */
  2263. if (mem_cgroup_wait_acct_move(mem_over_limit))
  2264. goto retry;
  2265. if (nr_retries--)
  2266. goto retry;
  2267. if (gfp_mask & __GFP_NOFAIL)
  2268. goto bypass;
  2269. if (fatal_signal_pending(current))
  2270. goto bypass;
  2271. mem_cgroup_oom(mem_over_limit, gfp_mask, get_order(nr_pages));
  2272. nomem:
  2273. if (!(gfp_mask & __GFP_NOFAIL))
  2274. return -ENOMEM;
  2275. bypass:
  2276. return -EINTR;
  2277. done_restock:
  2278. if (batch > nr_pages)
  2279. refill_stock(memcg, batch - nr_pages);
  2280. done:
  2281. return ret;
  2282. }
  2283. static void cancel_charge(struct mem_cgroup *memcg, unsigned int nr_pages)
  2284. {
  2285. unsigned long bytes = nr_pages * PAGE_SIZE;
  2286. if (mem_cgroup_is_root(memcg))
  2287. return;
  2288. res_counter_uncharge(&memcg->res, bytes);
  2289. if (do_swap_account)
  2290. res_counter_uncharge(&memcg->memsw, bytes);
  2291. }
  2292. /*
  2293. * Cancel chrages in this cgroup....doesn't propagate to parent cgroup.
  2294. * This is useful when moving usage to parent cgroup.
  2295. */
  2296. static void __mem_cgroup_cancel_local_charge(struct mem_cgroup *memcg,
  2297. unsigned int nr_pages)
  2298. {
  2299. unsigned long bytes = nr_pages * PAGE_SIZE;
  2300. if (mem_cgroup_is_root(memcg))
  2301. return;
  2302. res_counter_uncharge_until(&memcg->res, memcg->res.parent, bytes);
  2303. if (do_swap_account)
  2304. res_counter_uncharge_until(&memcg->memsw,
  2305. memcg->memsw.parent, bytes);
  2306. }
  2307. /*
  2308. * A helper function to get mem_cgroup from ID. must be called under
  2309. * rcu_read_lock(). The caller is responsible for calling
  2310. * css_tryget_online() if the mem_cgroup is used for charging. (dropping
  2311. * refcnt from swap can be called against removed memcg.)
  2312. */
  2313. static struct mem_cgroup *mem_cgroup_lookup(unsigned short id)
  2314. {
  2315. /* ID 0 is unused ID */
  2316. if (!id)
  2317. return NULL;
  2318. return mem_cgroup_from_id(id);
  2319. }
  2320. /*
  2321. * try_get_mem_cgroup_from_page - look up page's memcg association
  2322. * @page: the page
  2323. *
  2324. * Look up, get a css reference, and return the memcg that owns @page.
  2325. *
  2326. * The page must be locked to prevent racing with swap-in and page
  2327. * cache charges. If coming from an unlocked page table, the caller
  2328. * must ensure the page is on the LRU or this can race with charging.
  2329. */
  2330. struct mem_cgroup *try_get_mem_cgroup_from_page(struct page *page)
  2331. {
  2332. struct mem_cgroup *memcg = NULL;
  2333. struct page_cgroup *pc;
  2334. unsigned short id;
  2335. swp_entry_t ent;
  2336. VM_BUG_ON_PAGE(!PageLocked(page), page);
  2337. pc = lookup_page_cgroup(page);
  2338. if (PageCgroupUsed(pc)) {
  2339. memcg = pc->mem_cgroup;
  2340. if (memcg && !css_tryget_online(&memcg->css))
  2341. memcg = NULL;
  2342. } else if (PageSwapCache(page)) {
  2343. ent.val = page_private(page);
  2344. id = lookup_swap_cgroup_id(ent);
  2345. rcu_read_lock();
  2346. memcg = mem_cgroup_lookup(id);
  2347. if (memcg && !css_tryget_online(&memcg->css))
  2348. memcg = NULL;
  2349. rcu_read_unlock();
  2350. }
  2351. return memcg;
  2352. }
  2353. static void lock_page_lru(struct page *page, int *isolated)
  2354. {
  2355. struct zone *zone = page_zone(page);
  2356. spin_lock_irq(&zone->lru_lock);
  2357. if (PageLRU(page)) {
  2358. struct lruvec *lruvec;
  2359. lruvec = mem_cgroup_page_lruvec(page, zone);
  2360. ClearPageLRU(page);
  2361. del_page_from_lru_list(page, lruvec, page_lru(page));
  2362. *isolated = 1;
  2363. } else
  2364. *isolated = 0;
  2365. }
  2366. static void unlock_page_lru(struct page *page, int isolated)
  2367. {
  2368. struct zone *zone = page_zone(page);
  2369. if (isolated) {
  2370. struct lruvec *lruvec;
  2371. lruvec = mem_cgroup_page_lruvec(page, zone);
  2372. VM_BUG_ON_PAGE(PageLRU(page), page);
  2373. SetPageLRU(page);
  2374. add_page_to_lru_list(page, lruvec, page_lru(page));
  2375. }
  2376. spin_unlock_irq(&zone->lru_lock);
  2377. }
  2378. static void commit_charge(struct page *page, struct mem_cgroup *memcg,
  2379. bool lrucare)
  2380. {
  2381. struct page_cgroup *pc = lookup_page_cgroup(page);
  2382. int isolated;
  2383. VM_BUG_ON_PAGE(PageCgroupUsed(pc), page);
  2384. /*
  2385. * we don't need page_cgroup_lock about tail pages, becase they are not
  2386. * accessed by any other context at this point.
  2387. */
  2388. /*
  2389. * In some cases, SwapCache and FUSE(splice_buf->radixtree), the page
  2390. * may already be on some other mem_cgroup's LRU. Take care of it.
  2391. */
  2392. if (lrucare)
  2393. lock_page_lru(page, &isolated);
  2394. /*
  2395. * Nobody should be changing or seriously looking at
  2396. * pc->mem_cgroup and pc->flags at this point:
  2397. *
  2398. * - the page is uncharged
  2399. *
  2400. * - the page is off-LRU
  2401. *
  2402. * - an anonymous fault has exclusive page access, except for
  2403. * a locked page table
  2404. *
  2405. * - a page cache insertion, a swapin fault, or a migration
  2406. * have the page locked
  2407. */
  2408. pc->mem_cgroup = memcg;
  2409. pc->flags = PCG_USED | PCG_MEM | (do_swap_account ? PCG_MEMSW : 0);
  2410. if (lrucare)
  2411. unlock_page_lru(page, isolated);
  2412. }
  2413. static DEFINE_MUTEX(set_limit_mutex);
  2414. #ifdef CONFIG_MEMCG_KMEM
  2415. /*
  2416. * The memcg_slab_mutex is held whenever a per memcg kmem cache is created or
  2417. * destroyed. It protects memcg_caches arrays and memcg_slab_caches lists.
  2418. */
  2419. static DEFINE_MUTEX(memcg_slab_mutex);
  2420. static DEFINE_MUTEX(activate_kmem_mutex);
  2421. /*
  2422. * This is a bit cumbersome, but it is rarely used and avoids a backpointer
  2423. * in the memcg_cache_params struct.
  2424. */
  2425. static struct kmem_cache *memcg_params_to_cache(struct memcg_cache_params *p)
  2426. {
  2427. struct kmem_cache *cachep;
  2428. VM_BUG_ON(p->is_root_cache);
  2429. cachep = p->root_cache;
  2430. return cache_from_memcg_idx(cachep, memcg_cache_id(p->memcg));
  2431. }
  2432. #ifdef CONFIG_SLABINFO
  2433. static int mem_cgroup_slabinfo_read(struct seq_file *m, void *v)
  2434. {
  2435. struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
  2436. struct memcg_cache_params *params;
  2437. if (!memcg_kmem_is_active(memcg))
  2438. return -EIO;
  2439. print_slabinfo_header(m);
  2440. mutex_lock(&memcg_slab_mutex);
  2441. list_for_each_entry(params, &memcg->memcg_slab_caches, list)
  2442. cache_show(memcg_params_to_cache(params), m);
  2443. mutex_unlock(&memcg_slab_mutex);
  2444. return 0;
  2445. }
  2446. #endif
  2447. static int memcg_charge_kmem(struct mem_cgroup *memcg, gfp_t gfp, u64 size)
  2448. {
  2449. struct res_counter *fail_res;
  2450. int ret = 0;
  2451. ret = res_counter_charge(&memcg->kmem, size, &fail_res);
  2452. if (ret)
  2453. return ret;
  2454. ret = try_charge(memcg, gfp, size >> PAGE_SHIFT);
  2455. if (ret == -EINTR) {
  2456. /*
  2457. * try_charge() chose to bypass to root due to OOM kill or
  2458. * fatal signal. Since our only options are to either fail
  2459. * the allocation or charge it to this cgroup, do it as a
  2460. * temporary condition. But we can't fail. From a kmem/slab
  2461. * perspective, the cache has already been selected, by
  2462. * mem_cgroup_kmem_get_cache(), so it is too late to change
  2463. * our minds.
  2464. *
  2465. * This condition will only trigger if the task entered
  2466. * memcg_charge_kmem in a sane state, but was OOM-killed
  2467. * during try_charge() above. Tasks that were already dying
  2468. * when the allocation triggers should have been already
  2469. * directed to the root cgroup in memcontrol.h
  2470. */
  2471. res_counter_charge_nofail(&memcg->res, size, &fail_res);
  2472. if (do_swap_account)
  2473. res_counter_charge_nofail(&memcg->memsw, size,
  2474. &fail_res);
  2475. ret = 0;
  2476. } else if (ret)
  2477. res_counter_uncharge(&memcg->kmem, size);
  2478. return ret;
  2479. }
  2480. static void memcg_uncharge_kmem(struct mem_cgroup *memcg, u64 size)
  2481. {
  2482. res_counter_uncharge(&memcg->res, size);
  2483. if (do_swap_account)
  2484. res_counter_uncharge(&memcg->memsw, size);
  2485. /* Not down to 0 */
  2486. if (res_counter_uncharge(&memcg->kmem, size))
  2487. return;
  2488. /*
  2489. * Releases a reference taken in kmem_cgroup_css_offline in case
  2490. * this last uncharge is racing with the offlining code or it is
  2491. * outliving the memcg existence.
  2492. *
  2493. * The memory barrier imposed by test&clear is paired with the
  2494. * explicit one in memcg_kmem_mark_dead().
  2495. */
  2496. if (memcg_kmem_test_and_clear_dead(memcg))
  2497. css_put(&memcg->css);
  2498. }
  2499. /*
  2500. * helper for acessing a memcg's index. It will be used as an index in the
  2501. * child cache array in kmem_cache, and also to derive its name. This function
  2502. * will return -1 when this is not a kmem-limited memcg.
  2503. */
  2504. int memcg_cache_id(struct mem_cgroup *memcg)
  2505. {
  2506. return memcg ? memcg->kmemcg_id : -1;
  2507. }
  2508. static int memcg_alloc_cache_id(void)
  2509. {
  2510. int id, size;
  2511. int err;
  2512. id = ida_simple_get(&kmem_limited_groups,
  2513. 0, MEMCG_CACHES_MAX_SIZE, GFP_KERNEL);
  2514. if (id < 0)
  2515. return id;
  2516. if (id < memcg_limited_groups_array_size)
  2517. return id;
  2518. /*
  2519. * There's no space for the new id in memcg_caches arrays,
  2520. * so we have to grow them.
  2521. */
  2522. size = 2 * (id + 1);
  2523. if (size < MEMCG_CACHES_MIN_SIZE)
  2524. size = MEMCG_CACHES_MIN_SIZE;
  2525. else if (size > MEMCG_CACHES_MAX_SIZE)
  2526. size = MEMCG_CACHES_MAX_SIZE;
  2527. mutex_lock(&memcg_slab_mutex);
  2528. err = memcg_update_all_caches(size);
  2529. mutex_unlock(&memcg_slab_mutex);
  2530. if (err) {
  2531. ida_simple_remove(&kmem_limited_groups, id);
  2532. return err;
  2533. }
  2534. return id;
  2535. }
  2536. static void memcg_free_cache_id(int id)
  2537. {
  2538. ida_simple_remove(&kmem_limited_groups, id);
  2539. }
  2540. /*
  2541. * We should update the current array size iff all caches updates succeed. This
  2542. * can only be done from the slab side. The slab mutex needs to be held when
  2543. * calling this.
  2544. */
  2545. void memcg_update_array_size(int num)
  2546. {
  2547. memcg_limited_groups_array_size = num;
  2548. }
  2549. static void memcg_register_cache(struct mem_cgroup *memcg,
  2550. struct kmem_cache *root_cache)
  2551. {
  2552. static char memcg_name_buf[NAME_MAX + 1]; /* protected by
  2553. memcg_slab_mutex */
  2554. struct kmem_cache *cachep;
  2555. int id;
  2556. lockdep_assert_held(&memcg_slab_mutex);
  2557. id = memcg_cache_id(memcg);
  2558. /*
  2559. * Since per-memcg caches are created asynchronously on first
  2560. * allocation (see memcg_kmem_get_cache()), several threads can try to
  2561. * create the same cache, but only one of them may succeed.
  2562. */
  2563. if (cache_from_memcg_idx(root_cache, id))
  2564. return;
  2565. cgroup_name(memcg->css.cgroup, memcg_name_buf, NAME_MAX + 1);
  2566. cachep = memcg_create_kmem_cache(memcg, root_cache, memcg_name_buf);
  2567. /*
  2568. * If we could not create a memcg cache, do not complain, because
  2569. * that's not critical at all as we can always proceed with the root
  2570. * cache.
  2571. */
  2572. if (!cachep)
  2573. return;
  2574. css_get(&memcg->css);
  2575. list_add(&cachep->memcg_params->list, &memcg->memcg_slab_caches);
  2576. /*
  2577. * Since readers won't lock (see cache_from_memcg_idx()), we need a
  2578. * barrier here to ensure nobody will see the kmem_cache partially
  2579. * initialized.
  2580. */
  2581. smp_wmb();
  2582. BUG_ON(root_cache->memcg_params->memcg_caches[id]);
  2583. root_cache->memcg_params->memcg_caches[id] = cachep;
  2584. }
  2585. static void memcg_unregister_cache(struct kmem_cache *cachep)
  2586. {
  2587. struct kmem_cache *root_cache;
  2588. struct mem_cgroup *memcg;
  2589. int id;
  2590. lockdep_assert_held(&memcg_slab_mutex);
  2591. BUG_ON(is_root_cache(cachep));
  2592. root_cache = cachep->memcg_params->root_cache;
  2593. memcg = cachep->memcg_params->memcg;
  2594. id = memcg_cache_id(memcg);
  2595. BUG_ON(root_cache->memcg_params->memcg_caches[id] != cachep);
  2596. root_cache->memcg_params->memcg_caches[id] = NULL;
  2597. list_del(&cachep->memcg_params->list);
  2598. kmem_cache_destroy(cachep);
  2599. /* drop the reference taken in memcg_register_cache */
  2600. css_put(&memcg->css);
  2601. }
  2602. /*
  2603. * During the creation a new cache, we need to disable our accounting mechanism
  2604. * altogether. This is true even if we are not creating, but rather just
  2605. * enqueing new caches to be created.
  2606. *
  2607. * This is because that process will trigger allocations; some visible, like
  2608. * explicit kmallocs to auxiliary data structures, name strings and internal
  2609. * cache structures; some well concealed, like INIT_WORK() that can allocate
  2610. * objects during debug.
  2611. *
  2612. * If any allocation happens during memcg_kmem_get_cache, we will recurse back
  2613. * to it. This may not be a bounded recursion: since the first cache creation
  2614. * failed to complete (waiting on the allocation), we'll just try to create the
  2615. * cache again, failing at the same point.
  2616. *
  2617. * memcg_kmem_get_cache is prepared to abort after seeing a positive count of
  2618. * memcg_kmem_skip_account. So we enclose anything that might allocate memory
  2619. * inside the following two functions.
  2620. */
  2621. static inline void memcg_stop_kmem_account(void)
  2622. {
  2623. VM_BUG_ON(!current->mm);
  2624. current->memcg_kmem_skip_account++;
  2625. }
  2626. static inline void memcg_resume_kmem_account(void)
  2627. {
  2628. VM_BUG_ON(!current->mm);
  2629. current->memcg_kmem_skip_account--;
  2630. }
  2631. int __memcg_cleanup_cache_params(struct kmem_cache *s)
  2632. {
  2633. struct kmem_cache *c;
  2634. int i, failed = 0;
  2635. mutex_lock(&memcg_slab_mutex);
  2636. for_each_memcg_cache_index(i) {
  2637. c = cache_from_memcg_idx(s, i);
  2638. if (!c)
  2639. continue;
  2640. memcg_unregister_cache(c);
  2641. if (cache_from_memcg_idx(s, i))
  2642. failed++;
  2643. }
  2644. mutex_unlock(&memcg_slab_mutex);
  2645. return failed;
  2646. }
  2647. static void memcg_unregister_all_caches(struct mem_cgroup *memcg)
  2648. {
  2649. struct kmem_cache *cachep;
  2650. struct memcg_cache_params *params, *tmp;
  2651. if (!memcg_kmem_is_active(memcg))
  2652. return;
  2653. mutex_lock(&memcg_slab_mutex);
  2654. list_for_each_entry_safe(params, tmp, &memcg->memcg_slab_caches, list) {
  2655. cachep = memcg_params_to_cache(params);
  2656. kmem_cache_shrink(cachep);
  2657. if (atomic_read(&cachep->memcg_params->nr_pages) == 0)
  2658. memcg_unregister_cache(cachep);
  2659. }
  2660. mutex_unlock(&memcg_slab_mutex);
  2661. }
  2662. struct memcg_register_cache_work {
  2663. struct mem_cgroup *memcg;
  2664. struct kmem_cache *cachep;
  2665. struct work_struct work;
  2666. };
  2667. static void memcg_register_cache_func(struct work_struct *w)
  2668. {
  2669. struct memcg_register_cache_work *cw =
  2670. container_of(w, struct memcg_register_cache_work, work);
  2671. struct mem_cgroup *memcg = cw->memcg;
  2672. struct kmem_cache *cachep = cw->cachep;
  2673. mutex_lock(&memcg_slab_mutex);
  2674. memcg_register_cache(memcg, cachep);
  2675. mutex_unlock(&memcg_slab_mutex);
  2676. css_put(&memcg->css);
  2677. kfree(cw);
  2678. }
  2679. /*
  2680. * Enqueue the creation of a per-memcg kmem_cache.
  2681. */
  2682. static void __memcg_schedule_register_cache(struct mem_cgroup *memcg,
  2683. struct kmem_cache *cachep)
  2684. {
  2685. struct memcg_register_cache_work *cw;
  2686. cw = kmalloc(sizeof(*cw), GFP_NOWAIT);
  2687. if (cw == NULL) {
  2688. css_put(&memcg->css);
  2689. return;
  2690. }
  2691. cw->memcg = memcg;
  2692. cw->cachep = cachep;
  2693. INIT_WORK(&cw->work, memcg_register_cache_func);
  2694. schedule_work(&cw->work);
  2695. }
  2696. static void memcg_schedule_register_cache(struct mem_cgroup *memcg,
  2697. struct kmem_cache *cachep)
  2698. {
  2699. /*
  2700. * We need to stop accounting when we kmalloc, because if the
  2701. * corresponding kmalloc cache is not yet created, the first allocation
  2702. * in __memcg_schedule_register_cache will recurse.
  2703. *
  2704. * However, it is better to enclose the whole function. Depending on
  2705. * the debugging options enabled, INIT_WORK(), for instance, can
  2706. * trigger an allocation. This too, will make us recurse. Because at
  2707. * this point we can't allow ourselves back into memcg_kmem_get_cache,
  2708. * the safest choice is to do it like this, wrapping the whole function.
  2709. */
  2710. memcg_stop_kmem_account();
  2711. __memcg_schedule_register_cache(memcg, cachep);
  2712. memcg_resume_kmem_account();
  2713. }
  2714. int __memcg_charge_slab(struct kmem_cache *cachep, gfp_t gfp, int order)
  2715. {
  2716. int res;
  2717. res = memcg_charge_kmem(cachep->memcg_params->memcg, gfp,
  2718. PAGE_SIZE << order);
  2719. if (!res)
  2720. atomic_add(1 << order, &cachep->memcg_params->nr_pages);
  2721. return res;
  2722. }
  2723. void __memcg_uncharge_slab(struct kmem_cache *cachep, int order)
  2724. {
  2725. memcg_uncharge_kmem(cachep->memcg_params->memcg, PAGE_SIZE << order);
  2726. atomic_sub(1 << order, &cachep->memcg_params->nr_pages);
  2727. }
  2728. /*
  2729. * Return the kmem_cache we're supposed to use for a slab allocation.
  2730. * We try to use the current memcg's version of the cache.
  2731. *
  2732. * If the cache does not exist yet, if we are the first user of it,
  2733. * we either create it immediately, if possible, or create it asynchronously
  2734. * in a workqueue.
  2735. * In the latter case, we will let the current allocation go through with
  2736. * the original cache.
  2737. *
  2738. * Can't be called in interrupt context or from kernel threads.
  2739. * This function needs to be called with rcu_read_lock() held.
  2740. */
  2741. struct kmem_cache *__memcg_kmem_get_cache(struct kmem_cache *cachep,
  2742. gfp_t gfp)
  2743. {
  2744. struct mem_cgroup *memcg;
  2745. struct kmem_cache *memcg_cachep;
  2746. VM_BUG_ON(!cachep->memcg_params);
  2747. VM_BUG_ON(!cachep->memcg_params->is_root_cache);
  2748. if (!current->mm || current->memcg_kmem_skip_account)
  2749. return cachep;
  2750. rcu_read_lock();
  2751. memcg = mem_cgroup_from_task(rcu_dereference(current->mm->owner));
  2752. if (!memcg_kmem_is_active(memcg))
  2753. goto out;
  2754. memcg_cachep = cache_from_memcg_idx(cachep, memcg_cache_id(memcg));
  2755. if (likely(memcg_cachep)) {
  2756. cachep = memcg_cachep;
  2757. goto out;
  2758. }
  2759. /* The corresponding put will be done in the workqueue. */
  2760. if (!css_tryget_online(&memcg->css))
  2761. goto out;
  2762. rcu_read_unlock();
  2763. /*
  2764. * If we are in a safe context (can wait, and not in interrupt
  2765. * context), we could be be predictable and return right away.
  2766. * This would guarantee that the allocation being performed
  2767. * already belongs in the new cache.
  2768. *
  2769. * However, there are some clashes that can arrive from locking.
  2770. * For instance, because we acquire the slab_mutex while doing
  2771. * memcg_create_kmem_cache, this means no further allocation
  2772. * could happen with the slab_mutex held. So it's better to
  2773. * defer everything.
  2774. */
  2775. memcg_schedule_register_cache(memcg, cachep);
  2776. return cachep;
  2777. out:
  2778. rcu_read_unlock();
  2779. return cachep;
  2780. }
  2781. /*
  2782. * We need to verify if the allocation against current->mm->owner's memcg is
  2783. * possible for the given order. But the page is not allocated yet, so we'll
  2784. * need a further commit step to do the final arrangements.
  2785. *
  2786. * It is possible for the task to switch cgroups in this mean time, so at
  2787. * commit time, we can't rely on task conversion any longer. We'll then use
  2788. * the handle argument to return to the caller which cgroup we should commit
  2789. * against. We could also return the memcg directly and avoid the pointer
  2790. * passing, but a boolean return value gives better semantics considering
  2791. * the compiled-out case as well.
  2792. *
  2793. * Returning true means the allocation is possible.
  2794. */
  2795. bool
  2796. __memcg_kmem_newpage_charge(gfp_t gfp, struct mem_cgroup **_memcg, int order)
  2797. {
  2798. struct mem_cgroup *memcg;
  2799. int ret;
  2800. *_memcg = NULL;
  2801. /*
  2802. * Disabling accounting is only relevant for some specific memcg
  2803. * internal allocations. Therefore we would initially not have such
  2804. * check here, since direct calls to the page allocator that are
  2805. * accounted to kmemcg (alloc_kmem_pages and friends) only happen
  2806. * outside memcg core. We are mostly concerned with cache allocations,
  2807. * and by having this test at memcg_kmem_get_cache, we are already able
  2808. * to relay the allocation to the root cache and bypass the memcg cache
  2809. * altogether.
  2810. *
  2811. * There is one exception, though: the SLUB allocator does not create
  2812. * large order caches, but rather service large kmallocs directly from
  2813. * the page allocator. Therefore, the following sequence when backed by
  2814. * the SLUB allocator:
  2815. *
  2816. * memcg_stop_kmem_account();
  2817. * kmalloc(<large_number>)
  2818. * memcg_resume_kmem_account();
  2819. *
  2820. * would effectively ignore the fact that we should skip accounting,
  2821. * since it will drive us directly to this function without passing
  2822. * through the cache selector memcg_kmem_get_cache. Such large
  2823. * allocations are extremely rare but can happen, for instance, for the
  2824. * cache arrays. We bring this test here.
  2825. */
  2826. if (!current->mm || current->memcg_kmem_skip_account)
  2827. return true;
  2828. memcg = get_mem_cgroup_from_mm(current->mm);
  2829. if (!memcg_kmem_is_active(memcg)) {
  2830. css_put(&memcg->css);
  2831. return true;
  2832. }
  2833. ret = memcg_charge_kmem(memcg, gfp, PAGE_SIZE << order);
  2834. if (!ret)
  2835. *_memcg = memcg;
  2836. css_put(&memcg->css);
  2837. return (ret == 0);
  2838. }
  2839. void __memcg_kmem_commit_charge(struct page *page, struct mem_cgroup *memcg,
  2840. int order)
  2841. {
  2842. struct page_cgroup *pc;
  2843. VM_BUG_ON(mem_cgroup_is_root(memcg));
  2844. /* The page allocation failed. Revert */
  2845. if (!page) {
  2846. memcg_uncharge_kmem(memcg, PAGE_SIZE << order);
  2847. return;
  2848. }
  2849. /*
  2850. * The page is freshly allocated and not visible to any
  2851. * outside callers yet. Set up pc non-atomically.
  2852. */
  2853. pc = lookup_page_cgroup(page);
  2854. pc->mem_cgroup = memcg;
  2855. pc->flags = PCG_USED;
  2856. }
  2857. void __memcg_kmem_uncharge_pages(struct page *page, int order)
  2858. {
  2859. struct mem_cgroup *memcg = NULL;
  2860. struct page_cgroup *pc;
  2861. pc = lookup_page_cgroup(page);
  2862. if (!PageCgroupUsed(pc))
  2863. return;
  2864. memcg = pc->mem_cgroup;
  2865. pc->flags = 0;
  2866. /*
  2867. * We trust that only if there is a memcg associated with the page, it
  2868. * is a valid allocation
  2869. */
  2870. if (!memcg)
  2871. return;
  2872. VM_BUG_ON_PAGE(mem_cgroup_is_root(memcg), page);
  2873. memcg_uncharge_kmem(memcg, PAGE_SIZE << order);
  2874. }
  2875. #else
  2876. static inline void memcg_unregister_all_caches(struct mem_cgroup *memcg)
  2877. {
  2878. }
  2879. #endif /* CONFIG_MEMCG_KMEM */
  2880. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  2881. /*
  2882. * Because tail pages are not marked as "used", set it. We're under
  2883. * zone->lru_lock, 'splitting on pmd' and compound_lock.
  2884. * charge/uncharge will be never happen and move_account() is done under
  2885. * compound_lock(), so we don't have to take care of races.
  2886. */
  2887. void mem_cgroup_split_huge_fixup(struct page *head)
  2888. {
  2889. struct page_cgroup *head_pc = lookup_page_cgroup(head);
  2890. struct page_cgroup *pc;
  2891. struct mem_cgroup *memcg;
  2892. int i;
  2893. if (mem_cgroup_disabled())
  2894. return;
  2895. memcg = head_pc->mem_cgroup;
  2896. for (i = 1; i < HPAGE_PMD_NR; i++) {
  2897. pc = head_pc + i;
  2898. pc->mem_cgroup = memcg;
  2899. pc->flags = head_pc->flags;
  2900. }
  2901. __this_cpu_sub(memcg->stat->count[MEM_CGROUP_STAT_RSS_HUGE],
  2902. HPAGE_PMD_NR);
  2903. }
  2904. #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
  2905. /**
  2906. * mem_cgroup_move_account - move account of the page
  2907. * @page: the page
  2908. * @nr_pages: number of regular pages (>1 for huge pages)
  2909. * @pc: page_cgroup of the page.
  2910. * @from: mem_cgroup which the page is moved from.
  2911. * @to: mem_cgroup which the page is moved to. @from != @to.
  2912. *
  2913. * The caller must confirm following.
  2914. * - page is not on LRU (isolate_page() is useful.)
  2915. * - compound_lock is held when nr_pages > 1
  2916. *
  2917. * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
  2918. * from old cgroup.
  2919. */
  2920. static int mem_cgroup_move_account(struct page *page,
  2921. unsigned int nr_pages,
  2922. struct page_cgroup *pc,
  2923. struct mem_cgroup *from,
  2924. struct mem_cgroup *to)
  2925. {
  2926. unsigned long flags;
  2927. int ret;
  2928. VM_BUG_ON(from == to);
  2929. VM_BUG_ON_PAGE(PageLRU(page), page);
  2930. /*
  2931. * The page is isolated from LRU. So, collapse function
  2932. * will not handle this page. But page splitting can happen.
  2933. * Do this check under compound_page_lock(). The caller should
  2934. * hold it.
  2935. */
  2936. ret = -EBUSY;
  2937. if (nr_pages > 1 && !PageTransHuge(page))
  2938. goto out;
  2939. /*
  2940. * Prevent mem_cgroup_migrate() from looking at pc->mem_cgroup
  2941. * of its source page while we change it: page migration takes
  2942. * both pages off the LRU, but page cache replacement doesn't.
  2943. */
  2944. if (!trylock_page(page))
  2945. goto out;
  2946. ret = -EINVAL;
  2947. if (!PageCgroupUsed(pc) || pc->mem_cgroup != from)
  2948. goto out_unlock;
  2949. move_lock_mem_cgroup(from, &flags);
  2950. if (!PageAnon(page) && page_mapped(page)) {
  2951. __this_cpu_sub(from->stat->count[MEM_CGROUP_STAT_FILE_MAPPED],
  2952. nr_pages);
  2953. __this_cpu_add(to->stat->count[MEM_CGROUP_STAT_FILE_MAPPED],
  2954. nr_pages);
  2955. }
  2956. if (PageWriteback(page)) {
  2957. __this_cpu_sub(from->stat->count[MEM_CGROUP_STAT_WRITEBACK],
  2958. nr_pages);
  2959. __this_cpu_add(to->stat->count[MEM_CGROUP_STAT_WRITEBACK],
  2960. nr_pages);
  2961. }
  2962. /*
  2963. * It is safe to change pc->mem_cgroup here because the page
  2964. * is referenced, charged, and isolated - we can't race with
  2965. * uncharging, charging, migration, or LRU putback.
  2966. */
  2967. /* caller should have done css_get */
  2968. pc->mem_cgroup = to;
  2969. move_unlock_mem_cgroup(from, &flags);
  2970. ret = 0;
  2971. local_irq_disable();
  2972. mem_cgroup_charge_statistics(to, page, nr_pages);
  2973. memcg_check_events(to, page);
  2974. mem_cgroup_charge_statistics(from, page, -nr_pages);
  2975. memcg_check_events(from, page);
  2976. local_irq_enable();
  2977. out_unlock:
  2978. unlock_page(page);
  2979. out:
  2980. return ret;
  2981. }
  2982. /**
  2983. * mem_cgroup_move_parent - moves page to the parent group
  2984. * @page: the page to move
  2985. * @pc: page_cgroup of the page
  2986. * @child: page's cgroup
  2987. *
  2988. * move charges to its parent or the root cgroup if the group has no
  2989. * parent (aka use_hierarchy==0).
  2990. * Although this might fail (get_page_unless_zero, isolate_lru_page or
  2991. * mem_cgroup_move_account fails) the failure is always temporary and
  2992. * it signals a race with a page removal/uncharge or migration. In the
  2993. * first case the page is on the way out and it will vanish from the LRU
  2994. * on the next attempt and the call should be retried later.
  2995. * Isolation from the LRU fails only if page has been isolated from
  2996. * the LRU since we looked at it and that usually means either global
  2997. * reclaim or migration going on. The page will either get back to the
  2998. * LRU or vanish.
  2999. * Finaly mem_cgroup_move_account fails only if the page got uncharged
  3000. * (!PageCgroupUsed) or moved to a different group. The page will
  3001. * disappear in the next attempt.
  3002. */
  3003. static int mem_cgroup_move_parent(struct page *page,
  3004. struct page_cgroup *pc,
  3005. struct mem_cgroup *child)
  3006. {
  3007. struct mem_cgroup *parent;
  3008. unsigned int nr_pages;
  3009. unsigned long uninitialized_var(flags);
  3010. int ret;
  3011. VM_BUG_ON(mem_cgroup_is_root(child));
  3012. ret = -EBUSY;
  3013. if (!get_page_unless_zero(page))
  3014. goto out;
  3015. if (isolate_lru_page(page))
  3016. goto put;
  3017. nr_pages = hpage_nr_pages(page);
  3018. parent = parent_mem_cgroup(child);
  3019. /*
  3020. * If no parent, move charges to root cgroup.
  3021. */
  3022. if (!parent)
  3023. parent = root_mem_cgroup;
  3024. if (nr_pages > 1) {
  3025. VM_BUG_ON_PAGE(!PageTransHuge(page), page);
  3026. flags = compound_lock_irqsave(page);
  3027. }
  3028. ret = mem_cgroup_move_account(page, nr_pages,
  3029. pc, child, parent);
  3030. if (!ret)
  3031. __mem_cgroup_cancel_local_charge(child, nr_pages);
  3032. if (nr_pages > 1)
  3033. compound_unlock_irqrestore(page, flags);
  3034. putback_lru_page(page);
  3035. put:
  3036. put_page(page);
  3037. out:
  3038. return ret;
  3039. }
  3040. #ifdef CONFIG_MEMCG_SWAP
  3041. static void mem_cgroup_swap_statistics(struct mem_cgroup *memcg,
  3042. bool charge)
  3043. {
  3044. int val = (charge) ? 1 : -1;
  3045. this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_SWAP], val);
  3046. }
  3047. /**
  3048. * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
  3049. * @entry: swap entry to be moved
  3050. * @from: mem_cgroup which the entry is moved from
  3051. * @to: mem_cgroup which the entry is moved to
  3052. *
  3053. * It succeeds only when the swap_cgroup's record for this entry is the same
  3054. * as the mem_cgroup's id of @from.
  3055. *
  3056. * Returns 0 on success, -EINVAL on failure.
  3057. *
  3058. * The caller must have charged to @to, IOW, called res_counter_charge() about
  3059. * both res and memsw, and called css_get().
  3060. */
  3061. static int mem_cgroup_move_swap_account(swp_entry_t entry,
  3062. struct mem_cgroup *from, struct mem_cgroup *to)
  3063. {
  3064. unsigned short old_id, new_id;
  3065. old_id = mem_cgroup_id(from);
  3066. new_id = mem_cgroup_id(to);
  3067. if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
  3068. mem_cgroup_swap_statistics(from, false);
  3069. mem_cgroup_swap_statistics(to, true);
  3070. /*
  3071. * This function is only called from task migration context now.
  3072. * It postpones res_counter and refcount handling till the end
  3073. * of task migration(mem_cgroup_clear_mc()) for performance
  3074. * improvement. But we cannot postpone css_get(to) because if
  3075. * the process that has been moved to @to does swap-in, the
  3076. * refcount of @to might be decreased to 0.
  3077. *
  3078. * We are in attach() phase, so the cgroup is guaranteed to be
  3079. * alive, so we can just call css_get().
  3080. */
  3081. css_get(&to->css);
  3082. return 0;
  3083. }
  3084. return -EINVAL;
  3085. }
  3086. #else
  3087. static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
  3088. struct mem_cgroup *from, struct mem_cgroup *to)
  3089. {
  3090. return -EINVAL;
  3091. }
  3092. #endif
  3093. #ifdef CONFIG_DEBUG_VM
  3094. static struct page_cgroup *lookup_page_cgroup_used(struct page *page)
  3095. {
  3096. struct page_cgroup *pc;
  3097. pc = lookup_page_cgroup(page);
  3098. /*
  3099. * Can be NULL while feeding pages into the page allocator for
  3100. * the first time, i.e. during boot or memory hotplug;
  3101. * or when mem_cgroup_disabled().
  3102. */
  3103. if (likely(pc) && PageCgroupUsed(pc))
  3104. return pc;
  3105. return NULL;
  3106. }
  3107. bool mem_cgroup_bad_page_check(struct page *page)
  3108. {
  3109. if (mem_cgroup_disabled())
  3110. return false;
  3111. return lookup_page_cgroup_used(page) != NULL;
  3112. }
  3113. void mem_cgroup_print_bad_page(struct page *page)
  3114. {
  3115. struct page_cgroup *pc;
  3116. pc = lookup_page_cgroup_used(page);
  3117. if (pc) {
  3118. pr_alert("pc:%p pc->flags:%lx pc->mem_cgroup:%p\n",
  3119. pc, pc->flags, pc->mem_cgroup);
  3120. }
  3121. }
  3122. #endif
  3123. static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
  3124. unsigned long long val)
  3125. {
  3126. int retry_count;
  3127. int ret = 0;
  3128. int children = mem_cgroup_count_children(memcg);
  3129. u64 curusage, oldusage;
  3130. int enlarge;
  3131. /*
  3132. * For keeping hierarchical_reclaim simple, how long we should retry
  3133. * is depends on callers. We set our retry-count to be function
  3134. * of # of children which we should visit in this loop.
  3135. */
  3136. retry_count = MEM_CGROUP_RECLAIM_RETRIES * children;
  3137. oldusage = res_counter_read_u64(&memcg->res, RES_USAGE);
  3138. enlarge = 0;
  3139. while (retry_count) {
  3140. if (signal_pending(current)) {
  3141. ret = -EINTR;
  3142. break;
  3143. }
  3144. /*
  3145. * Rather than hide all in some function, I do this in
  3146. * open coded manner. You see what this really does.
  3147. * We have to guarantee memcg->res.limit <= memcg->memsw.limit.
  3148. */
  3149. mutex_lock(&set_limit_mutex);
  3150. if (res_counter_read_u64(&memcg->memsw, RES_LIMIT) < val) {
  3151. ret = -EINVAL;
  3152. mutex_unlock(&set_limit_mutex);
  3153. break;
  3154. }
  3155. if (res_counter_read_u64(&memcg->res, RES_LIMIT) < val)
  3156. enlarge = 1;
  3157. ret = res_counter_set_limit(&memcg->res, val);
  3158. mutex_unlock(&set_limit_mutex);
  3159. if (!ret)
  3160. break;
  3161. try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL, true);
  3162. curusage = res_counter_read_u64(&memcg->res, RES_USAGE);
  3163. /* Usage is reduced ? */
  3164. if (curusage >= oldusage)
  3165. retry_count--;
  3166. else
  3167. oldusage = curusage;
  3168. }
  3169. if (!ret && enlarge)
  3170. memcg_oom_recover(memcg);
  3171. return ret;
  3172. }
  3173. static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
  3174. unsigned long long val)
  3175. {
  3176. int retry_count;
  3177. u64 oldusage, curusage;
  3178. int children = mem_cgroup_count_children(memcg);
  3179. int ret = -EBUSY;
  3180. int enlarge = 0;
  3181. /* see mem_cgroup_resize_res_limit */
  3182. retry_count = children * MEM_CGROUP_RECLAIM_RETRIES;
  3183. oldusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
  3184. while (retry_count) {
  3185. if (signal_pending(current)) {
  3186. ret = -EINTR;
  3187. break;
  3188. }
  3189. /*
  3190. * Rather than hide all in some function, I do this in
  3191. * open coded manner. You see what this really does.
  3192. * We have to guarantee memcg->res.limit <= memcg->memsw.limit.
  3193. */
  3194. mutex_lock(&set_limit_mutex);
  3195. if (res_counter_read_u64(&memcg->res, RES_LIMIT) > val) {
  3196. ret = -EINVAL;
  3197. mutex_unlock(&set_limit_mutex);
  3198. break;
  3199. }
  3200. if (res_counter_read_u64(&memcg->memsw, RES_LIMIT) < val)
  3201. enlarge = 1;
  3202. ret = res_counter_set_limit(&memcg->memsw, val);
  3203. mutex_unlock(&set_limit_mutex);
  3204. if (!ret)
  3205. break;
  3206. try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL, false);
  3207. curusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
  3208. /* Usage is reduced ? */
  3209. if (curusage >= oldusage)
  3210. retry_count--;
  3211. else
  3212. oldusage = curusage;
  3213. }
  3214. if (!ret && enlarge)
  3215. memcg_oom_recover(memcg);
  3216. return ret;
  3217. }
  3218. unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
  3219. gfp_t gfp_mask,
  3220. unsigned long *total_scanned)
  3221. {
  3222. unsigned long nr_reclaimed = 0;
  3223. struct mem_cgroup_per_zone *mz, *next_mz = NULL;
  3224. unsigned long reclaimed;
  3225. int loop = 0;
  3226. struct mem_cgroup_tree_per_zone *mctz;
  3227. unsigned long long excess;
  3228. unsigned long nr_scanned;
  3229. if (order > 0)
  3230. return 0;
  3231. mctz = soft_limit_tree_node_zone(zone_to_nid(zone), zone_idx(zone));
  3232. /*
  3233. * This loop can run a while, specially if mem_cgroup's continuously
  3234. * keep exceeding their soft limit and putting the system under
  3235. * pressure
  3236. */
  3237. do {
  3238. if (next_mz)
  3239. mz = next_mz;
  3240. else
  3241. mz = mem_cgroup_largest_soft_limit_node(mctz);
  3242. if (!mz)
  3243. break;
  3244. nr_scanned = 0;
  3245. reclaimed = mem_cgroup_soft_reclaim(mz->memcg, zone,
  3246. gfp_mask, &nr_scanned);
  3247. nr_reclaimed += reclaimed;
  3248. *total_scanned += nr_scanned;
  3249. spin_lock_irq(&mctz->lock);
  3250. /*
  3251. * If we failed to reclaim anything from this memory cgroup
  3252. * it is time to move on to the next cgroup
  3253. */
  3254. next_mz = NULL;
  3255. if (!reclaimed) {
  3256. do {
  3257. /*
  3258. * Loop until we find yet another one.
  3259. *
  3260. * By the time we get the soft_limit lock
  3261. * again, someone might have aded the
  3262. * group back on the RB tree. Iterate to
  3263. * make sure we get a different mem.
  3264. * mem_cgroup_largest_soft_limit_node returns
  3265. * NULL if no other cgroup is present on
  3266. * the tree
  3267. */
  3268. next_mz =
  3269. __mem_cgroup_largest_soft_limit_node(mctz);
  3270. if (next_mz == mz)
  3271. css_put(&next_mz->memcg->css);
  3272. else /* next_mz == NULL or other memcg */
  3273. break;
  3274. } while (1);
  3275. }
  3276. __mem_cgroup_remove_exceeded(mz, mctz);
  3277. excess = res_counter_soft_limit_excess(&mz->memcg->res);
  3278. /*
  3279. * One school of thought says that we should not add
  3280. * back the node to the tree if reclaim returns 0.
  3281. * But our reclaim could return 0, simply because due
  3282. * to priority we are exposing a smaller subset of
  3283. * memory to reclaim from. Consider this as a longer
  3284. * term TODO.
  3285. */
  3286. /* If excess == 0, no tree ops */
  3287. __mem_cgroup_insert_exceeded(mz, mctz, excess);
  3288. spin_unlock_irq(&mctz->lock);
  3289. css_put(&mz->memcg->css);
  3290. loop++;
  3291. /*
  3292. * Could not reclaim anything and there are no more
  3293. * mem cgroups to try or we seem to be looping without
  3294. * reclaiming anything.
  3295. */
  3296. if (!nr_reclaimed &&
  3297. (next_mz == NULL ||
  3298. loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
  3299. break;
  3300. } while (!nr_reclaimed);
  3301. if (next_mz)
  3302. css_put(&next_mz->memcg->css);
  3303. return nr_reclaimed;
  3304. }
  3305. /**
  3306. * mem_cgroup_force_empty_list - clears LRU of a group
  3307. * @memcg: group to clear
  3308. * @node: NUMA node
  3309. * @zid: zone id
  3310. * @lru: lru to to clear
  3311. *
  3312. * Traverse a specified page_cgroup list and try to drop them all. This doesn't
  3313. * reclaim the pages page themselves - pages are moved to the parent (or root)
  3314. * group.
  3315. */
  3316. static void mem_cgroup_force_empty_list(struct mem_cgroup *memcg,
  3317. int node, int zid, enum lru_list lru)
  3318. {
  3319. struct lruvec *lruvec;
  3320. unsigned long flags;
  3321. struct list_head *list;
  3322. struct page *busy;
  3323. struct zone *zone;
  3324. zone = &NODE_DATA(node)->node_zones[zid];
  3325. lruvec = mem_cgroup_zone_lruvec(zone, memcg);
  3326. list = &lruvec->lists[lru];
  3327. busy = NULL;
  3328. do {
  3329. struct page_cgroup *pc;
  3330. struct page *page;
  3331. spin_lock_irqsave(&zone->lru_lock, flags);
  3332. if (list_empty(list)) {
  3333. spin_unlock_irqrestore(&zone->lru_lock, flags);
  3334. break;
  3335. }
  3336. page = list_entry(list->prev, struct page, lru);
  3337. if (busy == page) {
  3338. list_move(&page->lru, list);
  3339. busy = NULL;
  3340. spin_unlock_irqrestore(&zone->lru_lock, flags);
  3341. continue;
  3342. }
  3343. spin_unlock_irqrestore(&zone->lru_lock, flags);
  3344. pc = lookup_page_cgroup(page);
  3345. if (mem_cgroup_move_parent(page, pc, memcg)) {
  3346. /* found lock contention or "pc" is obsolete. */
  3347. busy = page;
  3348. } else
  3349. busy = NULL;
  3350. cond_resched();
  3351. } while (!list_empty(list));
  3352. }
  3353. /*
  3354. * make mem_cgroup's charge to be 0 if there is no task by moving
  3355. * all the charges and pages to the parent.
  3356. * This enables deleting this mem_cgroup.
  3357. *
  3358. * Caller is responsible for holding css reference on the memcg.
  3359. */
  3360. static void mem_cgroup_reparent_charges(struct mem_cgroup *memcg)
  3361. {
  3362. int node, zid;
  3363. u64 usage;
  3364. do {
  3365. /* This is for making all *used* pages to be on LRU. */
  3366. lru_add_drain_all();
  3367. drain_all_stock_sync(memcg);
  3368. mem_cgroup_start_move(memcg);
  3369. for_each_node_state(node, N_MEMORY) {
  3370. for (zid = 0; zid < MAX_NR_ZONES; zid++) {
  3371. enum lru_list lru;
  3372. for_each_lru(lru) {
  3373. mem_cgroup_force_empty_list(memcg,
  3374. node, zid, lru);
  3375. }
  3376. }
  3377. }
  3378. mem_cgroup_end_move(memcg);
  3379. memcg_oom_recover(memcg);
  3380. cond_resched();
  3381. /*
  3382. * Kernel memory may not necessarily be trackable to a specific
  3383. * process. So they are not migrated, and therefore we can't
  3384. * expect their value to drop to 0 here.
  3385. * Having res filled up with kmem only is enough.
  3386. *
  3387. * This is a safety check because mem_cgroup_force_empty_list
  3388. * could have raced with mem_cgroup_replace_page_cache callers
  3389. * so the lru seemed empty but the page could have been added
  3390. * right after the check. RES_USAGE should be safe as we always
  3391. * charge before adding to the LRU.
  3392. */
  3393. usage = res_counter_read_u64(&memcg->res, RES_USAGE) -
  3394. res_counter_read_u64(&memcg->kmem, RES_USAGE);
  3395. } while (usage > 0);
  3396. }
  3397. /*
  3398. * Test whether @memcg has children, dead or alive. Note that this
  3399. * function doesn't care whether @memcg has use_hierarchy enabled and
  3400. * returns %true if there are child csses according to the cgroup
  3401. * hierarchy. Testing use_hierarchy is the caller's responsiblity.
  3402. */
  3403. static inline bool memcg_has_children(struct mem_cgroup *memcg)
  3404. {
  3405. bool ret;
  3406. /*
  3407. * The lock does not prevent addition or deletion of children, but
  3408. * it prevents a new child from being initialized based on this
  3409. * parent in css_online(), so it's enough to decide whether
  3410. * hierarchically inherited attributes can still be changed or not.
  3411. */
  3412. lockdep_assert_held(&memcg_create_mutex);
  3413. rcu_read_lock();
  3414. ret = css_next_child(NULL, &memcg->css);
  3415. rcu_read_unlock();
  3416. return ret;
  3417. }
  3418. /*
  3419. * Reclaims as many pages from the given memcg as possible and moves
  3420. * the rest to the parent.
  3421. *
  3422. * Caller is responsible for holding css reference for memcg.
  3423. */
  3424. static int mem_cgroup_force_empty(struct mem_cgroup *memcg)
  3425. {
  3426. int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
  3427. /* we call try-to-free pages for make this cgroup empty */
  3428. lru_add_drain_all();
  3429. /* try to free all pages in this cgroup */
  3430. while (nr_retries && res_counter_read_u64(&memcg->res, RES_USAGE) > 0) {
  3431. int progress;
  3432. if (signal_pending(current))
  3433. return -EINTR;
  3434. progress = try_to_free_mem_cgroup_pages(memcg, 1,
  3435. GFP_KERNEL, true);
  3436. if (!progress) {
  3437. nr_retries--;
  3438. /* maybe some writeback is necessary */
  3439. congestion_wait(BLK_RW_ASYNC, HZ/10);
  3440. }
  3441. }
  3442. return 0;
  3443. }
  3444. static ssize_t mem_cgroup_force_empty_write(struct kernfs_open_file *of,
  3445. char *buf, size_t nbytes,
  3446. loff_t off)
  3447. {
  3448. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  3449. if (mem_cgroup_is_root(memcg))
  3450. return -EINVAL;
  3451. return mem_cgroup_force_empty(memcg) ?: nbytes;
  3452. }
  3453. static u64 mem_cgroup_hierarchy_read(struct cgroup_subsys_state *css,
  3454. struct cftype *cft)
  3455. {
  3456. return mem_cgroup_from_css(css)->use_hierarchy;
  3457. }
  3458. static int mem_cgroup_hierarchy_write(struct cgroup_subsys_state *css,
  3459. struct cftype *cft, u64 val)
  3460. {
  3461. int retval = 0;
  3462. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3463. struct mem_cgroup *parent_memcg = mem_cgroup_from_css(memcg->css.parent);
  3464. mutex_lock(&memcg_create_mutex);
  3465. if (memcg->use_hierarchy == val)
  3466. goto out;
  3467. /*
  3468. * If parent's use_hierarchy is set, we can't make any modifications
  3469. * in the child subtrees. If it is unset, then the change can
  3470. * occur, provided the current cgroup has no children.
  3471. *
  3472. * For the root cgroup, parent_mem is NULL, we allow value to be
  3473. * set if there are no children.
  3474. */
  3475. if ((!parent_memcg || !parent_memcg->use_hierarchy) &&
  3476. (val == 1 || val == 0)) {
  3477. if (!memcg_has_children(memcg))
  3478. memcg->use_hierarchy = val;
  3479. else
  3480. retval = -EBUSY;
  3481. } else
  3482. retval = -EINVAL;
  3483. out:
  3484. mutex_unlock(&memcg_create_mutex);
  3485. return retval;
  3486. }
  3487. static unsigned long mem_cgroup_recursive_stat(struct mem_cgroup *memcg,
  3488. enum mem_cgroup_stat_index idx)
  3489. {
  3490. struct mem_cgroup *iter;
  3491. long val = 0;
  3492. /* Per-cpu values can be negative, use a signed accumulator */
  3493. for_each_mem_cgroup_tree(iter, memcg)
  3494. val += mem_cgroup_read_stat(iter, idx);
  3495. if (val < 0) /* race ? */
  3496. val = 0;
  3497. return val;
  3498. }
  3499. static inline u64 mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
  3500. {
  3501. u64 val;
  3502. if (!mem_cgroup_is_root(memcg)) {
  3503. if (!swap)
  3504. return res_counter_read_u64(&memcg->res, RES_USAGE);
  3505. else
  3506. return res_counter_read_u64(&memcg->memsw, RES_USAGE);
  3507. }
  3508. /*
  3509. * Transparent hugepages are still accounted for in MEM_CGROUP_STAT_RSS
  3510. * as well as in MEM_CGROUP_STAT_RSS_HUGE.
  3511. */
  3512. val = mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_CACHE);
  3513. val += mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_RSS);
  3514. if (swap)
  3515. val += mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_SWAP);
  3516. return val << PAGE_SHIFT;
  3517. }
  3518. static u64 mem_cgroup_read_u64(struct cgroup_subsys_state *css,
  3519. struct cftype *cft)
  3520. {
  3521. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3522. enum res_type type = MEMFILE_TYPE(cft->private);
  3523. int name = MEMFILE_ATTR(cft->private);
  3524. switch (type) {
  3525. case _MEM:
  3526. if (name == RES_USAGE)
  3527. return mem_cgroup_usage(memcg, false);
  3528. return res_counter_read_u64(&memcg->res, name);
  3529. case _MEMSWAP:
  3530. if (name == RES_USAGE)
  3531. return mem_cgroup_usage(memcg, true);
  3532. return res_counter_read_u64(&memcg->memsw, name);
  3533. case _KMEM:
  3534. return res_counter_read_u64(&memcg->kmem, name);
  3535. break;
  3536. default:
  3537. BUG();
  3538. }
  3539. }
  3540. #ifdef CONFIG_MEMCG_KMEM
  3541. /* should be called with activate_kmem_mutex held */
  3542. static int __memcg_activate_kmem(struct mem_cgroup *memcg,
  3543. unsigned long long limit)
  3544. {
  3545. int err = 0;
  3546. int memcg_id;
  3547. if (memcg_kmem_is_active(memcg))
  3548. return 0;
  3549. /*
  3550. * We are going to allocate memory for data shared by all memory
  3551. * cgroups so let's stop accounting here.
  3552. */
  3553. memcg_stop_kmem_account();
  3554. /*
  3555. * For simplicity, we won't allow this to be disabled. It also can't
  3556. * be changed if the cgroup has children already, or if tasks had
  3557. * already joined.
  3558. *
  3559. * If tasks join before we set the limit, a person looking at
  3560. * kmem.usage_in_bytes will have no way to determine when it took
  3561. * place, which makes the value quite meaningless.
  3562. *
  3563. * After it first became limited, changes in the value of the limit are
  3564. * of course permitted.
  3565. */
  3566. mutex_lock(&memcg_create_mutex);
  3567. if (cgroup_has_tasks(memcg->css.cgroup) ||
  3568. (memcg->use_hierarchy && memcg_has_children(memcg)))
  3569. err = -EBUSY;
  3570. mutex_unlock(&memcg_create_mutex);
  3571. if (err)
  3572. goto out;
  3573. memcg_id = memcg_alloc_cache_id();
  3574. if (memcg_id < 0) {
  3575. err = memcg_id;
  3576. goto out;
  3577. }
  3578. memcg->kmemcg_id = memcg_id;
  3579. INIT_LIST_HEAD(&memcg->memcg_slab_caches);
  3580. /*
  3581. * We couldn't have accounted to this cgroup, because it hasn't got the
  3582. * active bit set yet, so this should succeed.
  3583. */
  3584. err = res_counter_set_limit(&memcg->kmem, limit);
  3585. VM_BUG_ON(err);
  3586. static_key_slow_inc(&memcg_kmem_enabled_key);
  3587. /*
  3588. * Setting the active bit after enabling static branching will
  3589. * guarantee no one starts accounting before all call sites are
  3590. * patched.
  3591. */
  3592. memcg_kmem_set_active(memcg);
  3593. out:
  3594. memcg_resume_kmem_account();
  3595. return err;
  3596. }
  3597. static int memcg_activate_kmem(struct mem_cgroup *memcg,
  3598. unsigned long long limit)
  3599. {
  3600. int ret;
  3601. mutex_lock(&activate_kmem_mutex);
  3602. ret = __memcg_activate_kmem(memcg, limit);
  3603. mutex_unlock(&activate_kmem_mutex);
  3604. return ret;
  3605. }
  3606. static int memcg_update_kmem_limit(struct mem_cgroup *memcg,
  3607. unsigned long long val)
  3608. {
  3609. int ret;
  3610. if (!memcg_kmem_is_active(memcg))
  3611. ret = memcg_activate_kmem(memcg, val);
  3612. else
  3613. ret = res_counter_set_limit(&memcg->kmem, val);
  3614. return ret;
  3615. }
  3616. static int memcg_propagate_kmem(struct mem_cgroup *memcg)
  3617. {
  3618. int ret = 0;
  3619. struct mem_cgroup *parent = parent_mem_cgroup(memcg);
  3620. if (!parent)
  3621. return 0;
  3622. mutex_lock(&activate_kmem_mutex);
  3623. /*
  3624. * If the parent cgroup is not kmem-active now, it cannot be activated
  3625. * after this point, because it has at least one child already.
  3626. */
  3627. if (memcg_kmem_is_active(parent))
  3628. ret = __memcg_activate_kmem(memcg, RES_COUNTER_MAX);
  3629. mutex_unlock(&activate_kmem_mutex);
  3630. return ret;
  3631. }
  3632. #else
  3633. static int memcg_update_kmem_limit(struct mem_cgroup *memcg,
  3634. unsigned long long val)
  3635. {
  3636. return -EINVAL;
  3637. }
  3638. #endif /* CONFIG_MEMCG_KMEM */
  3639. /*
  3640. * The user of this function is...
  3641. * RES_LIMIT.
  3642. */
  3643. static ssize_t mem_cgroup_write(struct kernfs_open_file *of,
  3644. char *buf, size_t nbytes, loff_t off)
  3645. {
  3646. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  3647. enum res_type type;
  3648. int name;
  3649. unsigned long long val;
  3650. int ret;
  3651. buf = strstrip(buf);
  3652. type = MEMFILE_TYPE(of_cft(of)->private);
  3653. name = MEMFILE_ATTR(of_cft(of)->private);
  3654. switch (name) {
  3655. case RES_LIMIT:
  3656. if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
  3657. ret = -EINVAL;
  3658. break;
  3659. }
  3660. /* This function does all necessary parse...reuse it */
  3661. ret = res_counter_memparse_write_strategy(buf, &val);
  3662. if (ret)
  3663. break;
  3664. if (type == _MEM)
  3665. ret = mem_cgroup_resize_limit(memcg, val);
  3666. else if (type == _MEMSWAP)
  3667. ret = mem_cgroup_resize_memsw_limit(memcg, val);
  3668. else if (type == _KMEM)
  3669. ret = memcg_update_kmem_limit(memcg, val);
  3670. else
  3671. return -EINVAL;
  3672. break;
  3673. case RES_SOFT_LIMIT:
  3674. ret = res_counter_memparse_write_strategy(buf, &val);
  3675. if (ret)
  3676. break;
  3677. /*
  3678. * For memsw, soft limits are hard to implement in terms
  3679. * of semantics, for now, we support soft limits for
  3680. * control without swap
  3681. */
  3682. if (type == _MEM)
  3683. ret = res_counter_set_soft_limit(&memcg->res, val);
  3684. else
  3685. ret = -EINVAL;
  3686. break;
  3687. default:
  3688. ret = -EINVAL; /* should be BUG() ? */
  3689. break;
  3690. }
  3691. return ret ?: nbytes;
  3692. }
  3693. static void memcg_get_hierarchical_limit(struct mem_cgroup *memcg,
  3694. unsigned long long *mem_limit, unsigned long long *memsw_limit)
  3695. {
  3696. unsigned long long min_limit, min_memsw_limit, tmp;
  3697. min_limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
  3698. min_memsw_limit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
  3699. if (!memcg->use_hierarchy)
  3700. goto out;
  3701. while (memcg->css.parent) {
  3702. memcg = mem_cgroup_from_css(memcg->css.parent);
  3703. if (!memcg->use_hierarchy)
  3704. break;
  3705. tmp = res_counter_read_u64(&memcg->res, RES_LIMIT);
  3706. min_limit = min(min_limit, tmp);
  3707. tmp = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
  3708. min_memsw_limit = min(min_memsw_limit, tmp);
  3709. }
  3710. out:
  3711. *mem_limit = min_limit;
  3712. *memsw_limit = min_memsw_limit;
  3713. }
  3714. static ssize_t mem_cgroup_reset(struct kernfs_open_file *of, char *buf,
  3715. size_t nbytes, loff_t off)
  3716. {
  3717. struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
  3718. int name;
  3719. enum res_type type;
  3720. type = MEMFILE_TYPE(of_cft(of)->private);
  3721. name = MEMFILE_ATTR(of_cft(of)->private);
  3722. switch (name) {
  3723. case RES_MAX_USAGE:
  3724. if (type == _MEM)
  3725. res_counter_reset_max(&memcg->res);
  3726. else if (type == _MEMSWAP)
  3727. res_counter_reset_max(&memcg->memsw);
  3728. else if (type == _KMEM)
  3729. res_counter_reset_max(&memcg->kmem);
  3730. else
  3731. return -EINVAL;
  3732. break;
  3733. case RES_FAILCNT:
  3734. if (type == _MEM)
  3735. res_counter_reset_failcnt(&memcg->res);
  3736. else if (type == _MEMSWAP)
  3737. res_counter_reset_failcnt(&memcg->memsw);
  3738. else if (type == _KMEM)
  3739. res_counter_reset_failcnt(&memcg->kmem);
  3740. else
  3741. return -EINVAL;
  3742. break;
  3743. }
  3744. return nbytes;
  3745. }
  3746. static u64 mem_cgroup_move_charge_read(struct cgroup_subsys_state *css,
  3747. struct cftype *cft)
  3748. {
  3749. return mem_cgroup_from_css(css)->move_charge_at_immigrate;
  3750. }
  3751. #ifdef CONFIG_MMU
  3752. static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
  3753. struct cftype *cft, u64 val)
  3754. {
  3755. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3756. if (val >= (1 << NR_MOVE_TYPE))
  3757. return -EINVAL;
  3758. /*
  3759. * No kind of locking is needed in here, because ->can_attach() will
  3760. * check this value once in the beginning of the process, and then carry
  3761. * on with stale data. This means that changes to this value will only
  3762. * affect task migrations starting after the change.
  3763. */
  3764. memcg->move_charge_at_immigrate = val;
  3765. return 0;
  3766. }
  3767. #else
  3768. static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
  3769. struct cftype *cft, u64 val)
  3770. {
  3771. return -ENOSYS;
  3772. }
  3773. #endif
  3774. #ifdef CONFIG_NUMA
  3775. static int memcg_numa_stat_show(struct seq_file *m, void *v)
  3776. {
  3777. struct numa_stat {
  3778. const char *name;
  3779. unsigned int lru_mask;
  3780. };
  3781. static const struct numa_stat stats[] = {
  3782. { "total", LRU_ALL },
  3783. { "file", LRU_ALL_FILE },
  3784. { "anon", LRU_ALL_ANON },
  3785. { "unevictable", BIT(LRU_UNEVICTABLE) },
  3786. };
  3787. const struct numa_stat *stat;
  3788. int nid;
  3789. unsigned long nr;
  3790. struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
  3791. for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
  3792. nr = mem_cgroup_nr_lru_pages(memcg, stat->lru_mask);
  3793. seq_printf(m, "%s=%lu", stat->name, nr);
  3794. for_each_node_state(nid, N_MEMORY) {
  3795. nr = mem_cgroup_node_nr_lru_pages(memcg, nid,
  3796. stat->lru_mask);
  3797. seq_printf(m, " N%d=%lu", nid, nr);
  3798. }
  3799. seq_putc(m, '\n');
  3800. }
  3801. for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
  3802. struct mem_cgroup *iter;
  3803. nr = 0;
  3804. for_each_mem_cgroup_tree(iter, memcg)
  3805. nr += mem_cgroup_nr_lru_pages(iter, stat->lru_mask);
  3806. seq_printf(m, "hierarchical_%s=%lu", stat->name, nr);
  3807. for_each_node_state(nid, N_MEMORY) {
  3808. nr = 0;
  3809. for_each_mem_cgroup_tree(iter, memcg)
  3810. nr += mem_cgroup_node_nr_lru_pages(
  3811. iter, nid, stat->lru_mask);
  3812. seq_printf(m, " N%d=%lu", nid, nr);
  3813. }
  3814. seq_putc(m, '\n');
  3815. }
  3816. return 0;
  3817. }
  3818. #endif /* CONFIG_NUMA */
  3819. static inline void mem_cgroup_lru_names_not_uptodate(void)
  3820. {
  3821. BUILD_BUG_ON(ARRAY_SIZE(mem_cgroup_lru_names) != NR_LRU_LISTS);
  3822. }
  3823. static int memcg_stat_show(struct seq_file *m, void *v)
  3824. {
  3825. struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
  3826. struct mem_cgroup *mi;
  3827. unsigned int i;
  3828. for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
  3829. if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
  3830. continue;
  3831. seq_printf(m, "%s %ld\n", mem_cgroup_stat_names[i],
  3832. mem_cgroup_read_stat(memcg, i) * PAGE_SIZE);
  3833. }
  3834. for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++)
  3835. seq_printf(m, "%s %lu\n", mem_cgroup_events_names[i],
  3836. mem_cgroup_read_events(memcg, i));
  3837. for (i = 0; i < NR_LRU_LISTS; i++)
  3838. seq_printf(m, "%s %lu\n", mem_cgroup_lru_names[i],
  3839. mem_cgroup_nr_lru_pages(memcg, BIT(i)) * PAGE_SIZE);
  3840. /* Hierarchical information */
  3841. {
  3842. unsigned long long limit, memsw_limit;
  3843. memcg_get_hierarchical_limit(memcg, &limit, &memsw_limit);
  3844. seq_printf(m, "hierarchical_memory_limit %llu\n", limit);
  3845. if (do_swap_account)
  3846. seq_printf(m, "hierarchical_memsw_limit %llu\n",
  3847. memsw_limit);
  3848. }
  3849. for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
  3850. long long val = 0;
  3851. if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
  3852. continue;
  3853. for_each_mem_cgroup_tree(mi, memcg)
  3854. val += mem_cgroup_read_stat(mi, i) * PAGE_SIZE;
  3855. seq_printf(m, "total_%s %lld\n", mem_cgroup_stat_names[i], val);
  3856. }
  3857. for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
  3858. unsigned long long val = 0;
  3859. for_each_mem_cgroup_tree(mi, memcg)
  3860. val += mem_cgroup_read_events(mi, i);
  3861. seq_printf(m, "total_%s %llu\n",
  3862. mem_cgroup_events_names[i], val);
  3863. }
  3864. for (i = 0; i < NR_LRU_LISTS; i++) {
  3865. unsigned long long val = 0;
  3866. for_each_mem_cgroup_tree(mi, memcg)
  3867. val += mem_cgroup_nr_lru_pages(mi, BIT(i)) * PAGE_SIZE;
  3868. seq_printf(m, "total_%s %llu\n", mem_cgroup_lru_names[i], val);
  3869. }
  3870. #ifdef CONFIG_DEBUG_VM
  3871. {
  3872. int nid, zid;
  3873. struct mem_cgroup_per_zone *mz;
  3874. struct zone_reclaim_stat *rstat;
  3875. unsigned long recent_rotated[2] = {0, 0};
  3876. unsigned long recent_scanned[2] = {0, 0};
  3877. for_each_online_node(nid)
  3878. for (zid = 0; zid < MAX_NR_ZONES; zid++) {
  3879. mz = &memcg->nodeinfo[nid]->zoneinfo[zid];
  3880. rstat = &mz->lruvec.reclaim_stat;
  3881. recent_rotated[0] += rstat->recent_rotated[0];
  3882. recent_rotated[1] += rstat->recent_rotated[1];
  3883. recent_scanned[0] += rstat->recent_scanned[0];
  3884. recent_scanned[1] += rstat->recent_scanned[1];
  3885. }
  3886. seq_printf(m, "recent_rotated_anon %lu\n", recent_rotated[0]);
  3887. seq_printf(m, "recent_rotated_file %lu\n", recent_rotated[1]);
  3888. seq_printf(m, "recent_scanned_anon %lu\n", recent_scanned[0]);
  3889. seq_printf(m, "recent_scanned_file %lu\n", recent_scanned[1]);
  3890. }
  3891. #endif
  3892. return 0;
  3893. }
  3894. static u64 mem_cgroup_swappiness_read(struct cgroup_subsys_state *css,
  3895. struct cftype *cft)
  3896. {
  3897. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3898. return mem_cgroup_swappiness(memcg);
  3899. }
  3900. static int mem_cgroup_swappiness_write(struct cgroup_subsys_state *css,
  3901. struct cftype *cft, u64 val)
  3902. {
  3903. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  3904. if (val > 100)
  3905. return -EINVAL;
  3906. if (css->parent)
  3907. memcg->swappiness = val;
  3908. else
  3909. vm_swappiness = val;
  3910. return 0;
  3911. }
  3912. static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
  3913. {
  3914. struct mem_cgroup_threshold_ary *t;
  3915. u64 usage;
  3916. int i;
  3917. rcu_read_lock();
  3918. if (!swap)
  3919. t = rcu_dereference(memcg->thresholds.primary);
  3920. else
  3921. t = rcu_dereference(memcg->memsw_thresholds.primary);
  3922. if (!t)
  3923. goto unlock;
  3924. usage = mem_cgroup_usage(memcg, swap);
  3925. /*
  3926. * current_threshold points to threshold just below or equal to usage.
  3927. * If it's not true, a threshold was crossed after last
  3928. * call of __mem_cgroup_threshold().
  3929. */
  3930. i = t->current_threshold;
  3931. /*
  3932. * Iterate backward over array of thresholds starting from
  3933. * current_threshold and check if a threshold is crossed.
  3934. * If none of thresholds below usage is crossed, we read
  3935. * only one element of the array here.
  3936. */
  3937. for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
  3938. eventfd_signal(t->entries[i].eventfd, 1);
  3939. /* i = current_threshold + 1 */
  3940. i++;
  3941. /*
  3942. * Iterate forward over array of thresholds starting from
  3943. * current_threshold+1 and check if a threshold is crossed.
  3944. * If none of thresholds above usage is crossed, we read
  3945. * only one element of the array here.
  3946. */
  3947. for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
  3948. eventfd_signal(t->entries[i].eventfd, 1);
  3949. /* Update current_threshold */
  3950. t->current_threshold = i - 1;
  3951. unlock:
  3952. rcu_read_unlock();
  3953. }
  3954. static void mem_cgroup_threshold(struct mem_cgroup *memcg)
  3955. {
  3956. while (memcg) {
  3957. __mem_cgroup_threshold(memcg, false);
  3958. if (do_swap_account)
  3959. __mem_cgroup_threshold(memcg, true);
  3960. memcg = parent_mem_cgroup(memcg);
  3961. }
  3962. }
  3963. static int compare_thresholds(const void *a, const void *b)
  3964. {
  3965. const struct mem_cgroup_threshold *_a = a;
  3966. const struct mem_cgroup_threshold *_b = b;
  3967. if (_a->threshold > _b->threshold)
  3968. return 1;
  3969. if (_a->threshold < _b->threshold)
  3970. return -1;
  3971. return 0;
  3972. }
  3973. static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
  3974. {
  3975. struct mem_cgroup_eventfd_list *ev;
  3976. spin_lock(&memcg_oom_lock);
  3977. list_for_each_entry(ev, &memcg->oom_notify, list)
  3978. eventfd_signal(ev->eventfd, 1);
  3979. spin_unlock(&memcg_oom_lock);
  3980. return 0;
  3981. }
  3982. static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
  3983. {
  3984. struct mem_cgroup *iter;
  3985. for_each_mem_cgroup_tree(iter, memcg)
  3986. mem_cgroup_oom_notify_cb(iter);
  3987. }
  3988. static int __mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
  3989. struct eventfd_ctx *eventfd, const char *args, enum res_type type)
  3990. {
  3991. struct mem_cgroup_thresholds *thresholds;
  3992. struct mem_cgroup_threshold_ary *new;
  3993. u64 threshold, usage;
  3994. int i, size, ret;
  3995. ret = res_counter_memparse_write_strategy(args, &threshold);
  3996. if (ret)
  3997. return ret;
  3998. mutex_lock(&memcg->thresholds_lock);
  3999. if (type == _MEM) {
  4000. thresholds = &memcg->thresholds;
  4001. usage = mem_cgroup_usage(memcg, false);
  4002. } else if (type == _MEMSWAP) {
  4003. thresholds = &memcg->memsw_thresholds;
  4004. usage = mem_cgroup_usage(memcg, true);
  4005. } else
  4006. BUG();
  4007. /* Check if a threshold crossed before adding a new one */
  4008. if (thresholds->primary)
  4009. __mem_cgroup_threshold(memcg, type == _MEMSWAP);
  4010. size = thresholds->primary ? thresholds->primary->size + 1 : 1;
  4011. /* Allocate memory for new array of thresholds */
  4012. new = kmalloc(sizeof(*new) + size * sizeof(struct mem_cgroup_threshold),
  4013. GFP_KERNEL);
  4014. if (!new) {
  4015. ret = -ENOMEM;
  4016. goto unlock;
  4017. }
  4018. new->size = size;
  4019. /* Copy thresholds (if any) to new array */
  4020. if (thresholds->primary) {
  4021. memcpy(new->entries, thresholds->primary->entries, (size - 1) *
  4022. sizeof(struct mem_cgroup_threshold));
  4023. }
  4024. /* Add new threshold */
  4025. new->entries[size - 1].eventfd = eventfd;
  4026. new->entries[size - 1].threshold = threshold;
  4027. /* Sort thresholds. Registering of new threshold isn't time-critical */
  4028. sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
  4029. compare_thresholds, NULL);
  4030. /* Find current threshold */
  4031. new->current_threshold = -1;
  4032. for (i = 0; i < size; i++) {
  4033. if (new->entries[i].threshold <= usage) {
  4034. /*
  4035. * new->current_threshold will not be used until
  4036. * rcu_assign_pointer(), so it's safe to increment
  4037. * it here.
  4038. */
  4039. ++new->current_threshold;
  4040. } else
  4041. break;
  4042. }
  4043. /* Free old spare buffer and save old primary buffer as spare */
  4044. kfree(thresholds->spare);
  4045. thresholds->spare = thresholds->primary;
  4046. rcu_assign_pointer(thresholds->primary, new);
  4047. /* To be sure that nobody uses thresholds */
  4048. synchronize_rcu();
  4049. unlock:
  4050. mutex_unlock(&memcg->thresholds_lock);
  4051. return ret;
  4052. }
  4053. static int mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
  4054. struct eventfd_ctx *eventfd, const char *args)
  4055. {
  4056. return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEM);
  4057. }
  4058. static int memsw_cgroup_usage_register_event(struct mem_cgroup *memcg,
  4059. struct eventfd_ctx *eventfd, const char *args)
  4060. {
  4061. return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEMSWAP);
  4062. }
  4063. static void __mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
  4064. struct eventfd_ctx *eventfd, enum res_type type)
  4065. {
  4066. struct mem_cgroup_thresholds *thresholds;
  4067. struct mem_cgroup_threshold_ary *new;
  4068. u64 usage;
  4069. int i, j, size;
  4070. mutex_lock(&memcg->thresholds_lock);
  4071. if (type == _MEM) {
  4072. thresholds = &memcg->thresholds;
  4073. usage = mem_cgroup_usage(memcg, false);
  4074. } else if (type == _MEMSWAP) {
  4075. thresholds = &memcg->memsw_thresholds;
  4076. usage = mem_cgroup_usage(memcg, true);
  4077. } else
  4078. BUG();
  4079. if (!thresholds->primary)
  4080. goto unlock;
  4081. /* Check if a threshold crossed before removing */
  4082. __mem_cgroup_threshold(memcg, type == _MEMSWAP);
  4083. /* Calculate new number of threshold */
  4084. size = 0;
  4085. for (i = 0; i < thresholds->primary->size; i++) {
  4086. if (thresholds->primary->entries[i].eventfd != eventfd)
  4087. size++;
  4088. }
  4089. new = thresholds->spare;
  4090. /* Set thresholds array to NULL if we don't have thresholds */
  4091. if (!size) {
  4092. kfree(new);
  4093. new = NULL;
  4094. goto swap_buffers;
  4095. }
  4096. new->size = size;
  4097. /* Copy thresholds and find current threshold */
  4098. new->current_threshold = -1;
  4099. for (i = 0, j = 0; i < thresholds->primary->size; i++) {
  4100. if (thresholds->primary->entries[i].eventfd == eventfd)
  4101. continue;
  4102. new->entries[j] = thresholds->primary->entries[i];
  4103. if (new->entries[j].threshold <= usage) {
  4104. /*
  4105. * new->current_threshold will not be used
  4106. * until rcu_assign_pointer(), so it's safe to increment
  4107. * it here.
  4108. */
  4109. ++new->current_threshold;
  4110. }
  4111. j++;
  4112. }
  4113. swap_buffers:
  4114. /* Swap primary and spare array */
  4115. thresholds->spare = thresholds->primary;
  4116. /* If all events are unregistered, free the spare array */
  4117. if (!new) {
  4118. kfree(thresholds->spare);
  4119. thresholds->spare = NULL;
  4120. }
  4121. rcu_assign_pointer(thresholds->primary, new);
  4122. /* To be sure that nobody uses thresholds */
  4123. synchronize_rcu();
  4124. unlock:
  4125. mutex_unlock(&memcg->thresholds_lock);
  4126. }
  4127. static void mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
  4128. struct eventfd_ctx *eventfd)
  4129. {
  4130. return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEM);
  4131. }
  4132. static void memsw_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
  4133. struct eventfd_ctx *eventfd)
  4134. {
  4135. return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEMSWAP);
  4136. }
  4137. static int mem_cgroup_oom_register_event(struct mem_cgroup *memcg,
  4138. struct eventfd_ctx *eventfd, const char *args)
  4139. {
  4140. struct mem_cgroup_eventfd_list *event;
  4141. event = kmalloc(sizeof(*event), GFP_KERNEL);
  4142. if (!event)
  4143. return -ENOMEM;
  4144. spin_lock(&memcg_oom_lock);
  4145. event->eventfd = eventfd;
  4146. list_add(&event->list, &memcg->oom_notify);
  4147. /* already in OOM ? */
  4148. if (atomic_read(&memcg->under_oom))
  4149. eventfd_signal(eventfd, 1);
  4150. spin_unlock(&memcg_oom_lock);
  4151. return 0;
  4152. }
  4153. static void mem_cgroup_oom_unregister_event(struct mem_cgroup *memcg,
  4154. struct eventfd_ctx *eventfd)
  4155. {
  4156. struct mem_cgroup_eventfd_list *ev, *tmp;
  4157. spin_lock(&memcg_oom_lock);
  4158. list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
  4159. if (ev->eventfd == eventfd) {
  4160. list_del(&ev->list);
  4161. kfree(ev);
  4162. }
  4163. }
  4164. spin_unlock(&memcg_oom_lock);
  4165. }
  4166. static int mem_cgroup_oom_control_read(struct seq_file *sf, void *v)
  4167. {
  4168. struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(sf));
  4169. seq_printf(sf, "oom_kill_disable %d\n", memcg->oom_kill_disable);
  4170. seq_printf(sf, "under_oom %d\n", (bool)atomic_read(&memcg->under_oom));
  4171. return 0;
  4172. }
  4173. static int mem_cgroup_oom_control_write(struct cgroup_subsys_state *css,
  4174. struct cftype *cft, u64 val)
  4175. {
  4176. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  4177. /* cannot set to root cgroup and only 0 and 1 are allowed */
  4178. if (!css->parent || !((val == 0) || (val == 1)))
  4179. return -EINVAL;
  4180. memcg->oom_kill_disable = val;
  4181. if (!val)
  4182. memcg_oom_recover(memcg);
  4183. return 0;
  4184. }
  4185. #ifdef CONFIG_MEMCG_KMEM
  4186. static int memcg_init_kmem(struct mem_cgroup *memcg, struct cgroup_subsys *ss)
  4187. {
  4188. int ret;
  4189. memcg->kmemcg_id = -1;
  4190. ret = memcg_propagate_kmem(memcg);
  4191. if (ret)
  4192. return ret;
  4193. return mem_cgroup_sockets_init(memcg, ss);
  4194. }
  4195. static void memcg_destroy_kmem(struct mem_cgroup *memcg)
  4196. {
  4197. mem_cgroup_sockets_destroy(memcg);
  4198. }
  4199. static void kmem_cgroup_css_offline(struct mem_cgroup *memcg)
  4200. {
  4201. if (!memcg_kmem_is_active(memcg))
  4202. return;
  4203. /*
  4204. * kmem charges can outlive the cgroup. In the case of slab
  4205. * pages, for instance, a page contain objects from various
  4206. * processes. As we prevent from taking a reference for every
  4207. * such allocation we have to be careful when doing uncharge
  4208. * (see memcg_uncharge_kmem) and here during offlining.
  4209. *
  4210. * The idea is that that only the _last_ uncharge which sees
  4211. * the dead memcg will drop the last reference. An additional
  4212. * reference is taken here before the group is marked dead
  4213. * which is then paired with css_put during uncharge resp. here.
  4214. *
  4215. * Although this might sound strange as this path is called from
  4216. * css_offline() when the referencemight have dropped down to 0 and
  4217. * shouldn't be incremented anymore (css_tryget_online() would
  4218. * fail) we do not have other options because of the kmem
  4219. * allocations lifetime.
  4220. */
  4221. css_get(&memcg->css);
  4222. memcg_kmem_mark_dead(memcg);
  4223. if (res_counter_read_u64(&memcg->kmem, RES_USAGE) != 0)
  4224. return;
  4225. if (memcg_kmem_test_and_clear_dead(memcg))
  4226. css_put(&memcg->css);
  4227. }
  4228. #else
  4229. static int memcg_init_kmem(struct mem_cgroup *memcg, struct cgroup_subsys *ss)
  4230. {
  4231. return 0;
  4232. }
  4233. static void memcg_destroy_kmem(struct mem_cgroup *memcg)
  4234. {
  4235. }
  4236. static void kmem_cgroup_css_offline(struct mem_cgroup *memcg)
  4237. {
  4238. }
  4239. #endif
  4240. /*
  4241. * DO NOT USE IN NEW FILES.
  4242. *
  4243. * "cgroup.event_control" implementation.
  4244. *
  4245. * This is way over-engineered. It tries to support fully configurable
  4246. * events for each user. Such level of flexibility is completely
  4247. * unnecessary especially in the light of the planned unified hierarchy.
  4248. *
  4249. * Please deprecate this and replace with something simpler if at all
  4250. * possible.
  4251. */
  4252. /*
  4253. * Unregister event and free resources.
  4254. *
  4255. * Gets called from workqueue.
  4256. */
  4257. static void memcg_event_remove(struct work_struct *work)
  4258. {
  4259. struct mem_cgroup_event *event =
  4260. container_of(work, struct mem_cgroup_event, remove);
  4261. struct mem_cgroup *memcg = event->memcg;
  4262. remove_wait_queue(event->wqh, &event->wait);
  4263. event->unregister_event(memcg, event->eventfd);
  4264. /* Notify userspace the event is going away. */
  4265. eventfd_signal(event->eventfd, 1);
  4266. eventfd_ctx_put(event->eventfd);
  4267. kfree(event);
  4268. css_put(&memcg->css);
  4269. }
  4270. /*
  4271. * Gets called on POLLHUP on eventfd when user closes it.
  4272. *
  4273. * Called with wqh->lock held and interrupts disabled.
  4274. */
  4275. static int memcg_event_wake(wait_queue_t *wait, unsigned mode,
  4276. int sync, void *key)
  4277. {
  4278. struct mem_cgroup_event *event =
  4279. container_of(wait, struct mem_cgroup_event, wait);
  4280. struct mem_cgroup *memcg = event->memcg;
  4281. unsigned long flags = (unsigned long)key;
  4282. if (flags & POLLHUP) {
  4283. /*
  4284. * If the event has been detached at cgroup removal, we
  4285. * can simply return knowing the other side will cleanup
  4286. * for us.
  4287. *
  4288. * We can't race against event freeing since the other
  4289. * side will require wqh->lock via remove_wait_queue(),
  4290. * which we hold.
  4291. */
  4292. spin_lock(&memcg->event_list_lock);
  4293. if (!list_empty(&event->list)) {
  4294. list_del_init(&event->list);
  4295. /*
  4296. * We are in atomic context, but cgroup_event_remove()
  4297. * may sleep, so we have to call it in workqueue.
  4298. */
  4299. schedule_work(&event->remove);
  4300. }
  4301. spin_unlock(&memcg->event_list_lock);
  4302. }
  4303. return 0;
  4304. }
  4305. static void memcg_event_ptable_queue_proc(struct file *file,
  4306. wait_queue_head_t *wqh, poll_table *pt)
  4307. {
  4308. struct mem_cgroup_event *event =
  4309. container_of(pt, struct mem_cgroup_event, pt);
  4310. event->wqh = wqh;
  4311. add_wait_queue(wqh, &event->wait);
  4312. }
  4313. /*
  4314. * DO NOT USE IN NEW FILES.
  4315. *
  4316. * Parse input and register new cgroup event handler.
  4317. *
  4318. * Input must be in format '<event_fd> <control_fd> <args>'.
  4319. * Interpretation of args is defined by control file implementation.
  4320. */
  4321. static ssize_t memcg_write_event_control(struct kernfs_open_file *of,
  4322. char *buf, size_t nbytes, loff_t off)
  4323. {
  4324. struct cgroup_subsys_state *css = of_css(of);
  4325. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  4326. struct mem_cgroup_event *event;
  4327. struct cgroup_subsys_state *cfile_css;
  4328. unsigned int efd, cfd;
  4329. struct fd efile;
  4330. struct fd cfile;
  4331. const char *name;
  4332. char *endp;
  4333. int ret;
  4334. buf = strstrip(buf);
  4335. efd = simple_strtoul(buf, &endp, 10);
  4336. if (*endp != ' ')
  4337. return -EINVAL;
  4338. buf = endp + 1;
  4339. cfd = simple_strtoul(buf, &endp, 10);
  4340. if ((*endp != ' ') && (*endp != '\0'))
  4341. return -EINVAL;
  4342. buf = endp + 1;
  4343. event = kzalloc(sizeof(*event), GFP_KERNEL);
  4344. if (!event)
  4345. return -ENOMEM;
  4346. event->memcg = memcg;
  4347. INIT_LIST_HEAD(&event->list);
  4348. init_poll_funcptr(&event->pt, memcg_event_ptable_queue_proc);
  4349. init_waitqueue_func_entry(&event->wait, memcg_event_wake);
  4350. INIT_WORK(&event->remove, memcg_event_remove);
  4351. efile = fdget(efd);
  4352. if (!efile.file) {
  4353. ret = -EBADF;
  4354. goto out_kfree;
  4355. }
  4356. event->eventfd = eventfd_ctx_fileget(efile.file);
  4357. if (IS_ERR(event->eventfd)) {
  4358. ret = PTR_ERR(event->eventfd);
  4359. goto out_put_efile;
  4360. }
  4361. cfile = fdget(cfd);
  4362. if (!cfile.file) {
  4363. ret = -EBADF;
  4364. goto out_put_eventfd;
  4365. }
  4366. /* the process need read permission on control file */
  4367. /* AV: shouldn't we check that it's been opened for read instead? */
  4368. ret = inode_permission(file_inode(cfile.file), MAY_READ);
  4369. if (ret < 0)
  4370. goto out_put_cfile;
  4371. /*
  4372. * Determine the event callbacks and set them in @event. This used
  4373. * to be done via struct cftype but cgroup core no longer knows
  4374. * about these events. The following is crude but the whole thing
  4375. * is for compatibility anyway.
  4376. *
  4377. * DO NOT ADD NEW FILES.
  4378. */
  4379. name = cfile.file->f_dentry->d_name.name;
  4380. if (!strcmp(name, "memory.usage_in_bytes")) {
  4381. event->register_event = mem_cgroup_usage_register_event;
  4382. event->unregister_event = mem_cgroup_usage_unregister_event;
  4383. } else if (!strcmp(name, "memory.oom_control")) {
  4384. event->register_event = mem_cgroup_oom_register_event;
  4385. event->unregister_event = mem_cgroup_oom_unregister_event;
  4386. } else if (!strcmp(name, "memory.pressure_level")) {
  4387. event->register_event = vmpressure_register_event;
  4388. event->unregister_event = vmpressure_unregister_event;
  4389. } else if (!strcmp(name, "memory.memsw.usage_in_bytes")) {
  4390. event->register_event = memsw_cgroup_usage_register_event;
  4391. event->unregister_event = memsw_cgroup_usage_unregister_event;
  4392. } else {
  4393. ret = -EINVAL;
  4394. goto out_put_cfile;
  4395. }
  4396. /*
  4397. * Verify @cfile should belong to @css. Also, remaining events are
  4398. * automatically removed on cgroup destruction but the removal is
  4399. * asynchronous, so take an extra ref on @css.
  4400. */
  4401. cfile_css = css_tryget_online_from_dir(cfile.file->f_dentry->d_parent,
  4402. &memory_cgrp_subsys);
  4403. ret = -EINVAL;
  4404. if (IS_ERR(cfile_css))
  4405. goto out_put_cfile;
  4406. if (cfile_css != css) {
  4407. css_put(cfile_css);
  4408. goto out_put_cfile;
  4409. }
  4410. ret = event->register_event(memcg, event->eventfd, buf);
  4411. if (ret)
  4412. goto out_put_css;
  4413. efile.file->f_op->poll(efile.file, &event->pt);
  4414. spin_lock(&memcg->event_list_lock);
  4415. list_add(&event->list, &memcg->event_list);
  4416. spin_unlock(&memcg->event_list_lock);
  4417. fdput(cfile);
  4418. fdput(efile);
  4419. return nbytes;
  4420. out_put_css:
  4421. css_put(css);
  4422. out_put_cfile:
  4423. fdput(cfile);
  4424. out_put_eventfd:
  4425. eventfd_ctx_put(event->eventfd);
  4426. out_put_efile:
  4427. fdput(efile);
  4428. out_kfree:
  4429. kfree(event);
  4430. return ret;
  4431. }
  4432. static struct cftype mem_cgroup_files[] = {
  4433. {
  4434. .name = "usage_in_bytes",
  4435. .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
  4436. .read_u64 = mem_cgroup_read_u64,
  4437. },
  4438. {
  4439. .name = "max_usage_in_bytes",
  4440. .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
  4441. .write = mem_cgroup_reset,
  4442. .read_u64 = mem_cgroup_read_u64,
  4443. },
  4444. {
  4445. .name = "limit_in_bytes",
  4446. .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
  4447. .write = mem_cgroup_write,
  4448. .read_u64 = mem_cgroup_read_u64,
  4449. },
  4450. {
  4451. .name = "soft_limit_in_bytes",
  4452. .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
  4453. .write = mem_cgroup_write,
  4454. .read_u64 = mem_cgroup_read_u64,
  4455. },
  4456. {
  4457. .name = "failcnt",
  4458. .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
  4459. .write = mem_cgroup_reset,
  4460. .read_u64 = mem_cgroup_read_u64,
  4461. },
  4462. {
  4463. .name = "stat",
  4464. .seq_show = memcg_stat_show,
  4465. },
  4466. {
  4467. .name = "force_empty",
  4468. .write = mem_cgroup_force_empty_write,
  4469. },
  4470. {
  4471. .name = "use_hierarchy",
  4472. .write_u64 = mem_cgroup_hierarchy_write,
  4473. .read_u64 = mem_cgroup_hierarchy_read,
  4474. },
  4475. {
  4476. .name = "cgroup.event_control", /* XXX: for compat */
  4477. .write = memcg_write_event_control,
  4478. .flags = CFTYPE_NO_PREFIX,
  4479. .mode = S_IWUGO,
  4480. },
  4481. {
  4482. .name = "swappiness",
  4483. .read_u64 = mem_cgroup_swappiness_read,
  4484. .write_u64 = mem_cgroup_swappiness_write,
  4485. },
  4486. {
  4487. .name = "move_charge_at_immigrate",
  4488. .read_u64 = mem_cgroup_move_charge_read,
  4489. .write_u64 = mem_cgroup_move_charge_write,
  4490. },
  4491. {
  4492. .name = "oom_control",
  4493. .seq_show = mem_cgroup_oom_control_read,
  4494. .write_u64 = mem_cgroup_oom_control_write,
  4495. .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
  4496. },
  4497. {
  4498. .name = "pressure_level",
  4499. },
  4500. #ifdef CONFIG_NUMA
  4501. {
  4502. .name = "numa_stat",
  4503. .seq_show = memcg_numa_stat_show,
  4504. },
  4505. #endif
  4506. #ifdef CONFIG_MEMCG_KMEM
  4507. {
  4508. .name = "kmem.limit_in_bytes",
  4509. .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
  4510. .write = mem_cgroup_write,
  4511. .read_u64 = mem_cgroup_read_u64,
  4512. },
  4513. {
  4514. .name = "kmem.usage_in_bytes",
  4515. .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
  4516. .read_u64 = mem_cgroup_read_u64,
  4517. },
  4518. {
  4519. .name = "kmem.failcnt",
  4520. .private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
  4521. .write = mem_cgroup_reset,
  4522. .read_u64 = mem_cgroup_read_u64,
  4523. },
  4524. {
  4525. .name = "kmem.max_usage_in_bytes",
  4526. .private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
  4527. .write = mem_cgroup_reset,
  4528. .read_u64 = mem_cgroup_read_u64,
  4529. },
  4530. #ifdef CONFIG_SLABINFO
  4531. {
  4532. .name = "kmem.slabinfo",
  4533. .seq_show = mem_cgroup_slabinfo_read,
  4534. },
  4535. #endif
  4536. #endif
  4537. { }, /* terminate */
  4538. };
  4539. #ifdef CONFIG_MEMCG_SWAP
  4540. static struct cftype memsw_cgroup_files[] = {
  4541. {
  4542. .name = "memsw.usage_in_bytes",
  4543. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
  4544. .read_u64 = mem_cgroup_read_u64,
  4545. },
  4546. {
  4547. .name = "memsw.max_usage_in_bytes",
  4548. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
  4549. .write = mem_cgroup_reset,
  4550. .read_u64 = mem_cgroup_read_u64,
  4551. },
  4552. {
  4553. .name = "memsw.limit_in_bytes",
  4554. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
  4555. .write = mem_cgroup_write,
  4556. .read_u64 = mem_cgroup_read_u64,
  4557. },
  4558. {
  4559. .name = "memsw.failcnt",
  4560. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
  4561. .write = mem_cgroup_reset,
  4562. .read_u64 = mem_cgroup_read_u64,
  4563. },
  4564. { }, /* terminate */
  4565. };
  4566. #endif
  4567. static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
  4568. {
  4569. struct mem_cgroup_per_node *pn;
  4570. struct mem_cgroup_per_zone *mz;
  4571. int zone, tmp = node;
  4572. /*
  4573. * This routine is called against possible nodes.
  4574. * But it's BUG to call kmalloc() against offline node.
  4575. *
  4576. * TODO: this routine can waste much memory for nodes which will
  4577. * never be onlined. It's better to use memory hotplug callback
  4578. * function.
  4579. */
  4580. if (!node_state(node, N_NORMAL_MEMORY))
  4581. tmp = -1;
  4582. pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
  4583. if (!pn)
  4584. return 1;
  4585. for (zone = 0; zone < MAX_NR_ZONES; zone++) {
  4586. mz = &pn->zoneinfo[zone];
  4587. lruvec_init(&mz->lruvec);
  4588. mz->usage_in_excess = 0;
  4589. mz->on_tree = false;
  4590. mz->memcg = memcg;
  4591. }
  4592. memcg->nodeinfo[node] = pn;
  4593. return 0;
  4594. }
  4595. static void free_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
  4596. {
  4597. kfree(memcg->nodeinfo[node]);
  4598. }
  4599. static struct mem_cgroup *mem_cgroup_alloc(void)
  4600. {
  4601. struct mem_cgroup *memcg;
  4602. size_t size;
  4603. size = sizeof(struct mem_cgroup);
  4604. size += nr_node_ids * sizeof(struct mem_cgroup_per_node *);
  4605. memcg = kzalloc(size, GFP_KERNEL);
  4606. if (!memcg)
  4607. return NULL;
  4608. memcg->stat = alloc_percpu(struct mem_cgroup_stat_cpu);
  4609. if (!memcg->stat)
  4610. goto out_free;
  4611. spin_lock_init(&memcg->pcp_counter_lock);
  4612. return memcg;
  4613. out_free:
  4614. kfree(memcg);
  4615. return NULL;
  4616. }
  4617. /*
  4618. * At destroying mem_cgroup, references from swap_cgroup can remain.
  4619. * (scanning all at force_empty is too costly...)
  4620. *
  4621. * Instead of clearing all references at force_empty, we remember
  4622. * the number of reference from swap_cgroup and free mem_cgroup when
  4623. * it goes down to 0.
  4624. *
  4625. * Removal of cgroup itself succeeds regardless of refs from swap.
  4626. */
  4627. static void __mem_cgroup_free(struct mem_cgroup *memcg)
  4628. {
  4629. int node;
  4630. mem_cgroup_remove_from_trees(memcg);
  4631. for_each_node(node)
  4632. free_mem_cgroup_per_zone_info(memcg, node);
  4633. free_percpu(memcg->stat);
  4634. /*
  4635. * We need to make sure that (at least for now), the jump label
  4636. * destruction code runs outside of the cgroup lock. This is because
  4637. * get_online_cpus(), which is called from the static_branch update,
  4638. * can't be called inside the cgroup_lock. cpusets are the ones
  4639. * enforcing this dependency, so if they ever change, we might as well.
  4640. *
  4641. * schedule_work() will guarantee this happens. Be careful if you need
  4642. * to move this code around, and make sure it is outside
  4643. * the cgroup_lock.
  4644. */
  4645. disarm_static_keys(memcg);
  4646. kfree(memcg);
  4647. }
  4648. /*
  4649. * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
  4650. */
  4651. struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *memcg)
  4652. {
  4653. if (!memcg->res.parent)
  4654. return NULL;
  4655. return mem_cgroup_from_res_counter(memcg->res.parent, res);
  4656. }
  4657. EXPORT_SYMBOL(parent_mem_cgroup);
  4658. static void __init mem_cgroup_soft_limit_tree_init(void)
  4659. {
  4660. struct mem_cgroup_tree_per_node *rtpn;
  4661. struct mem_cgroup_tree_per_zone *rtpz;
  4662. int tmp, node, zone;
  4663. for_each_node(node) {
  4664. tmp = node;
  4665. if (!node_state(node, N_NORMAL_MEMORY))
  4666. tmp = -1;
  4667. rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, tmp);
  4668. BUG_ON(!rtpn);
  4669. soft_limit_tree.rb_tree_per_node[node] = rtpn;
  4670. for (zone = 0; zone < MAX_NR_ZONES; zone++) {
  4671. rtpz = &rtpn->rb_tree_per_zone[zone];
  4672. rtpz->rb_root = RB_ROOT;
  4673. spin_lock_init(&rtpz->lock);
  4674. }
  4675. }
  4676. }
  4677. static struct cgroup_subsys_state * __ref
  4678. mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
  4679. {
  4680. struct mem_cgroup *memcg;
  4681. long error = -ENOMEM;
  4682. int node;
  4683. memcg = mem_cgroup_alloc();
  4684. if (!memcg)
  4685. return ERR_PTR(error);
  4686. for_each_node(node)
  4687. if (alloc_mem_cgroup_per_zone_info(memcg, node))
  4688. goto free_out;
  4689. /* root ? */
  4690. if (parent_css == NULL) {
  4691. root_mem_cgroup = memcg;
  4692. res_counter_init(&memcg->res, NULL);
  4693. res_counter_init(&memcg->memsw, NULL);
  4694. res_counter_init(&memcg->kmem, NULL);
  4695. }
  4696. memcg->last_scanned_node = MAX_NUMNODES;
  4697. INIT_LIST_HEAD(&memcg->oom_notify);
  4698. memcg->move_charge_at_immigrate = 0;
  4699. mutex_init(&memcg->thresholds_lock);
  4700. spin_lock_init(&memcg->move_lock);
  4701. vmpressure_init(&memcg->vmpressure);
  4702. INIT_LIST_HEAD(&memcg->event_list);
  4703. spin_lock_init(&memcg->event_list_lock);
  4704. return &memcg->css;
  4705. free_out:
  4706. __mem_cgroup_free(memcg);
  4707. return ERR_PTR(error);
  4708. }
  4709. static int
  4710. mem_cgroup_css_online(struct cgroup_subsys_state *css)
  4711. {
  4712. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  4713. struct mem_cgroup *parent = mem_cgroup_from_css(css->parent);
  4714. int ret;
  4715. if (css->id > MEM_CGROUP_ID_MAX)
  4716. return -ENOSPC;
  4717. if (!parent)
  4718. return 0;
  4719. mutex_lock(&memcg_create_mutex);
  4720. memcg->use_hierarchy = parent->use_hierarchy;
  4721. memcg->oom_kill_disable = parent->oom_kill_disable;
  4722. memcg->swappiness = mem_cgroup_swappiness(parent);
  4723. if (parent->use_hierarchy) {
  4724. res_counter_init(&memcg->res, &parent->res);
  4725. res_counter_init(&memcg->memsw, &parent->memsw);
  4726. res_counter_init(&memcg->kmem, &parent->kmem);
  4727. /*
  4728. * No need to take a reference to the parent because cgroup
  4729. * core guarantees its existence.
  4730. */
  4731. } else {
  4732. res_counter_init(&memcg->res, NULL);
  4733. res_counter_init(&memcg->memsw, NULL);
  4734. res_counter_init(&memcg->kmem, NULL);
  4735. /*
  4736. * Deeper hierachy with use_hierarchy == false doesn't make
  4737. * much sense so let cgroup subsystem know about this
  4738. * unfortunate state in our controller.
  4739. */
  4740. if (parent != root_mem_cgroup)
  4741. memory_cgrp_subsys.broken_hierarchy = true;
  4742. }
  4743. mutex_unlock(&memcg_create_mutex);
  4744. ret = memcg_init_kmem(memcg, &memory_cgrp_subsys);
  4745. if (ret)
  4746. return ret;
  4747. /*
  4748. * Make sure the memcg is initialized: mem_cgroup_iter()
  4749. * orders reading memcg->initialized against its callers
  4750. * reading the memcg members.
  4751. */
  4752. smp_store_release(&memcg->initialized, 1);
  4753. return 0;
  4754. }
  4755. /*
  4756. * Announce all parents that a group from their hierarchy is gone.
  4757. */
  4758. static void mem_cgroup_invalidate_reclaim_iterators(struct mem_cgroup *memcg)
  4759. {
  4760. struct mem_cgroup *parent = memcg;
  4761. while ((parent = parent_mem_cgroup(parent)))
  4762. mem_cgroup_iter_invalidate(parent);
  4763. /*
  4764. * if the root memcg is not hierarchical we have to check it
  4765. * explicitely.
  4766. */
  4767. if (!root_mem_cgroup->use_hierarchy)
  4768. mem_cgroup_iter_invalidate(root_mem_cgroup);
  4769. }
  4770. static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
  4771. {
  4772. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  4773. struct mem_cgroup_event *event, *tmp;
  4774. struct cgroup_subsys_state *iter;
  4775. /*
  4776. * Unregister events and notify userspace.
  4777. * Notify userspace about cgroup removing only after rmdir of cgroup
  4778. * directory to avoid race between userspace and kernelspace.
  4779. */
  4780. spin_lock(&memcg->event_list_lock);
  4781. list_for_each_entry_safe(event, tmp, &memcg->event_list, list) {
  4782. list_del_init(&event->list);
  4783. schedule_work(&event->remove);
  4784. }
  4785. spin_unlock(&memcg->event_list_lock);
  4786. kmem_cgroup_css_offline(memcg);
  4787. mem_cgroup_invalidate_reclaim_iterators(memcg);
  4788. /*
  4789. * This requires that offlining is serialized. Right now that is
  4790. * guaranteed because css_killed_work_fn() holds the cgroup_mutex.
  4791. */
  4792. css_for_each_descendant_post(iter, css)
  4793. mem_cgroup_reparent_charges(mem_cgroup_from_css(iter));
  4794. memcg_unregister_all_caches(memcg);
  4795. vmpressure_cleanup(&memcg->vmpressure);
  4796. }
  4797. static void mem_cgroup_css_free(struct cgroup_subsys_state *css)
  4798. {
  4799. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  4800. /*
  4801. * XXX: css_offline() would be where we should reparent all
  4802. * memory to prepare the cgroup for destruction. However,
  4803. * memcg does not do css_tryget_online() and res_counter charging
  4804. * under the same RCU lock region, which means that charging
  4805. * could race with offlining. Offlining only happens to
  4806. * cgroups with no tasks in them but charges can show up
  4807. * without any tasks from the swapin path when the target
  4808. * memcg is looked up from the swapout record and not from the
  4809. * current task as it usually is. A race like this can leak
  4810. * charges and put pages with stale cgroup pointers into
  4811. * circulation:
  4812. *
  4813. * #0 #1
  4814. * lookup_swap_cgroup_id()
  4815. * rcu_read_lock()
  4816. * mem_cgroup_lookup()
  4817. * css_tryget_online()
  4818. * rcu_read_unlock()
  4819. * disable css_tryget_online()
  4820. * call_rcu()
  4821. * offline_css()
  4822. * reparent_charges()
  4823. * res_counter_charge()
  4824. * css_put()
  4825. * css_free()
  4826. * pc->mem_cgroup = dead memcg
  4827. * add page to lru
  4828. *
  4829. * The bulk of the charges are still moved in offline_css() to
  4830. * avoid pinning a lot of pages in case a long-term reference
  4831. * like a swapout record is deferring the css_free() to long
  4832. * after offlining. But this makes sure we catch any charges
  4833. * made after offlining:
  4834. */
  4835. mem_cgroup_reparent_charges(memcg);
  4836. memcg_destroy_kmem(memcg);
  4837. __mem_cgroup_free(memcg);
  4838. }
  4839. /**
  4840. * mem_cgroup_css_reset - reset the states of a mem_cgroup
  4841. * @css: the target css
  4842. *
  4843. * Reset the states of the mem_cgroup associated with @css. This is
  4844. * invoked when the userland requests disabling on the default hierarchy
  4845. * but the memcg is pinned through dependency. The memcg should stop
  4846. * applying policies and should revert to the vanilla state as it may be
  4847. * made visible again.
  4848. *
  4849. * The current implementation only resets the essential configurations.
  4850. * This needs to be expanded to cover all the visible parts.
  4851. */
  4852. static void mem_cgroup_css_reset(struct cgroup_subsys_state *css)
  4853. {
  4854. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  4855. mem_cgroup_resize_limit(memcg, ULLONG_MAX);
  4856. mem_cgroup_resize_memsw_limit(memcg, ULLONG_MAX);
  4857. memcg_update_kmem_limit(memcg, ULLONG_MAX);
  4858. res_counter_set_soft_limit(&memcg->res, ULLONG_MAX);
  4859. }
  4860. #ifdef CONFIG_MMU
  4861. /* Handlers for move charge at task migration. */
  4862. static int mem_cgroup_do_precharge(unsigned long count)
  4863. {
  4864. int ret;
  4865. /* Try a single bulk charge without reclaim first */
  4866. ret = try_charge(mc.to, GFP_KERNEL & ~__GFP_WAIT, count);
  4867. if (!ret) {
  4868. mc.precharge += count;
  4869. return ret;
  4870. }
  4871. if (ret == -EINTR) {
  4872. cancel_charge(root_mem_cgroup, count);
  4873. return ret;
  4874. }
  4875. /* Try charges one by one with reclaim */
  4876. while (count--) {
  4877. ret = try_charge(mc.to, GFP_KERNEL & ~__GFP_NORETRY, 1);
  4878. /*
  4879. * In case of failure, any residual charges against
  4880. * mc.to will be dropped by mem_cgroup_clear_mc()
  4881. * later on. However, cancel any charges that are
  4882. * bypassed to root right away or they'll be lost.
  4883. */
  4884. if (ret == -EINTR)
  4885. cancel_charge(root_mem_cgroup, 1);
  4886. if (ret)
  4887. return ret;
  4888. mc.precharge++;
  4889. cond_resched();
  4890. }
  4891. return 0;
  4892. }
  4893. /**
  4894. * get_mctgt_type - get target type of moving charge
  4895. * @vma: the vma the pte to be checked belongs
  4896. * @addr: the address corresponding to the pte to be checked
  4897. * @ptent: the pte to be checked
  4898. * @target: the pointer the target page or swap ent will be stored(can be NULL)
  4899. *
  4900. * Returns
  4901. * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
  4902. * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
  4903. * move charge. if @target is not NULL, the page is stored in target->page
  4904. * with extra refcnt got(Callers should handle it).
  4905. * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
  4906. * target for charge migration. if @target is not NULL, the entry is stored
  4907. * in target->ent.
  4908. *
  4909. * Called with pte lock held.
  4910. */
  4911. union mc_target {
  4912. struct page *page;
  4913. swp_entry_t ent;
  4914. };
  4915. enum mc_target_type {
  4916. MC_TARGET_NONE = 0,
  4917. MC_TARGET_PAGE,
  4918. MC_TARGET_SWAP,
  4919. };
  4920. static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
  4921. unsigned long addr, pte_t ptent)
  4922. {
  4923. struct page *page = vm_normal_page(vma, addr, ptent);
  4924. if (!page || !page_mapped(page))
  4925. return NULL;
  4926. if (PageAnon(page)) {
  4927. /* we don't move shared anon */
  4928. if (!move_anon())
  4929. return NULL;
  4930. } else if (!move_file())
  4931. /* we ignore mapcount for file pages */
  4932. return NULL;
  4933. if (!get_page_unless_zero(page))
  4934. return NULL;
  4935. return page;
  4936. }
  4937. #ifdef CONFIG_SWAP
  4938. static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
  4939. unsigned long addr, pte_t ptent, swp_entry_t *entry)
  4940. {
  4941. struct page *page = NULL;
  4942. swp_entry_t ent = pte_to_swp_entry(ptent);
  4943. if (!move_anon() || non_swap_entry(ent))
  4944. return NULL;
  4945. /*
  4946. * Because lookup_swap_cache() updates some statistics counter,
  4947. * we call find_get_page() with swapper_space directly.
  4948. */
  4949. page = find_get_page(swap_address_space(ent), ent.val);
  4950. if (do_swap_account)
  4951. entry->val = ent.val;
  4952. return page;
  4953. }
  4954. #else
  4955. static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
  4956. unsigned long addr, pte_t ptent, swp_entry_t *entry)
  4957. {
  4958. return NULL;
  4959. }
  4960. #endif
  4961. static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
  4962. unsigned long addr, pte_t ptent, swp_entry_t *entry)
  4963. {
  4964. struct page *page = NULL;
  4965. struct address_space *mapping;
  4966. pgoff_t pgoff;
  4967. if (!vma->vm_file) /* anonymous vma */
  4968. return NULL;
  4969. if (!move_file())
  4970. return NULL;
  4971. mapping = vma->vm_file->f_mapping;
  4972. if (pte_none(ptent))
  4973. pgoff = linear_page_index(vma, addr);
  4974. else /* pte_file(ptent) is true */
  4975. pgoff = pte_to_pgoff(ptent);
  4976. /* page is moved even if it's not RSS of this task(page-faulted). */
  4977. #ifdef CONFIG_SWAP
  4978. /* shmem/tmpfs may report page out on swap: account for that too. */
  4979. if (shmem_mapping(mapping)) {
  4980. page = find_get_entry(mapping, pgoff);
  4981. if (radix_tree_exceptional_entry(page)) {
  4982. swp_entry_t swp = radix_to_swp_entry(page);
  4983. if (do_swap_account)
  4984. *entry = swp;
  4985. page = find_get_page(swap_address_space(swp), swp.val);
  4986. }
  4987. } else
  4988. page = find_get_page(mapping, pgoff);
  4989. #else
  4990. page = find_get_page(mapping, pgoff);
  4991. #endif
  4992. return page;
  4993. }
  4994. static enum mc_target_type get_mctgt_type(struct vm_area_struct *vma,
  4995. unsigned long addr, pte_t ptent, union mc_target *target)
  4996. {
  4997. struct page *page = NULL;
  4998. struct page_cgroup *pc;
  4999. enum mc_target_type ret = MC_TARGET_NONE;
  5000. swp_entry_t ent = { .val = 0 };
  5001. if (pte_present(ptent))
  5002. page = mc_handle_present_pte(vma, addr, ptent);
  5003. else if (is_swap_pte(ptent))
  5004. page = mc_handle_swap_pte(vma, addr, ptent, &ent);
  5005. else if (pte_none(ptent) || pte_file(ptent))
  5006. page = mc_handle_file_pte(vma, addr, ptent, &ent);
  5007. if (!page && !ent.val)
  5008. return ret;
  5009. if (page) {
  5010. pc = lookup_page_cgroup(page);
  5011. /*
  5012. * Do only loose check w/o serialization.
  5013. * mem_cgroup_move_account() checks the pc is valid or
  5014. * not under LRU exclusion.
  5015. */
  5016. if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
  5017. ret = MC_TARGET_PAGE;
  5018. if (target)
  5019. target->page = page;
  5020. }
  5021. if (!ret || !target)
  5022. put_page(page);
  5023. }
  5024. /* There is a swap entry and a page doesn't exist or isn't charged */
  5025. if (ent.val && !ret &&
  5026. mem_cgroup_id(mc.from) == lookup_swap_cgroup_id(ent)) {
  5027. ret = MC_TARGET_SWAP;
  5028. if (target)
  5029. target->ent = ent;
  5030. }
  5031. return ret;
  5032. }
  5033. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  5034. /*
  5035. * We don't consider swapping or file mapped pages because THP does not
  5036. * support them for now.
  5037. * Caller should make sure that pmd_trans_huge(pmd) is true.
  5038. */
  5039. static enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
  5040. unsigned long addr, pmd_t pmd, union mc_target *target)
  5041. {
  5042. struct page *page = NULL;
  5043. struct page_cgroup *pc;
  5044. enum mc_target_type ret = MC_TARGET_NONE;
  5045. page = pmd_page(pmd);
  5046. VM_BUG_ON_PAGE(!page || !PageHead(page), page);
  5047. if (!move_anon())
  5048. return ret;
  5049. pc = lookup_page_cgroup(page);
  5050. if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
  5051. ret = MC_TARGET_PAGE;
  5052. if (target) {
  5053. get_page(page);
  5054. target->page = page;
  5055. }
  5056. }
  5057. return ret;
  5058. }
  5059. #else
  5060. static inline enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
  5061. unsigned long addr, pmd_t pmd, union mc_target *target)
  5062. {
  5063. return MC_TARGET_NONE;
  5064. }
  5065. #endif
  5066. static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
  5067. unsigned long addr, unsigned long end,
  5068. struct mm_walk *walk)
  5069. {
  5070. struct vm_area_struct *vma = walk->private;
  5071. pte_t *pte;
  5072. spinlock_t *ptl;
  5073. if (pmd_trans_huge_lock(pmd, vma, &ptl) == 1) {
  5074. if (get_mctgt_type_thp(vma, addr, *pmd, NULL) == MC_TARGET_PAGE)
  5075. mc.precharge += HPAGE_PMD_NR;
  5076. spin_unlock(ptl);
  5077. return 0;
  5078. }
  5079. if (pmd_trans_unstable(pmd))
  5080. return 0;
  5081. pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
  5082. for (; addr != end; pte++, addr += PAGE_SIZE)
  5083. if (get_mctgt_type(vma, addr, *pte, NULL))
  5084. mc.precharge++; /* increment precharge temporarily */
  5085. pte_unmap_unlock(pte - 1, ptl);
  5086. cond_resched();
  5087. return 0;
  5088. }
  5089. static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
  5090. {
  5091. unsigned long precharge;
  5092. struct vm_area_struct *vma;
  5093. down_read(&mm->mmap_sem);
  5094. for (vma = mm->mmap; vma; vma = vma->vm_next) {
  5095. struct mm_walk mem_cgroup_count_precharge_walk = {
  5096. .pmd_entry = mem_cgroup_count_precharge_pte_range,
  5097. .mm = mm,
  5098. .private = vma,
  5099. };
  5100. if (is_vm_hugetlb_page(vma))
  5101. continue;
  5102. walk_page_range(vma->vm_start, vma->vm_end,
  5103. &mem_cgroup_count_precharge_walk);
  5104. }
  5105. up_read(&mm->mmap_sem);
  5106. precharge = mc.precharge;
  5107. mc.precharge = 0;
  5108. return precharge;
  5109. }
  5110. static int mem_cgroup_precharge_mc(struct mm_struct *mm)
  5111. {
  5112. unsigned long precharge = mem_cgroup_count_precharge(mm);
  5113. VM_BUG_ON(mc.moving_task);
  5114. mc.moving_task = current;
  5115. return mem_cgroup_do_precharge(precharge);
  5116. }
  5117. /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
  5118. static void __mem_cgroup_clear_mc(void)
  5119. {
  5120. struct mem_cgroup *from = mc.from;
  5121. struct mem_cgroup *to = mc.to;
  5122. int i;
  5123. /* we must uncharge all the leftover precharges from mc.to */
  5124. if (mc.precharge) {
  5125. cancel_charge(mc.to, mc.precharge);
  5126. mc.precharge = 0;
  5127. }
  5128. /*
  5129. * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
  5130. * we must uncharge here.
  5131. */
  5132. if (mc.moved_charge) {
  5133. cancel_charge(mc.from, mc.moved_charge);
  5134. mc.moved_charge = 0;
  5135. }
  5136. /* we must fixup refcnts and charges */
  5137. if (mc.moved_swap) {
  5138. /* uncharge swap account from the old cgroup */
  5139. if (!mem_cgroup_is_root(mc.from))
  5140. res_counter_uncharge(&mc.from->memsw,
  5141. PAGE_SIZE * mc.moved_swap);
  5142. for (i = 0; i < mc.moved_swap; i++)
  5143. css_put(&mc.from->css);
  5144. /*
  5145. * we charged both to->res and to->memsw, so we should
  5146. * uncharge to->res.
  5147. */
  5148. if (!mem_cgroup_is_root(mc.to))
  5149. res_counter_uncharge(&mc.to->res,
  5150. PAGE_SIZE * mc.moved_swap);
  5151. /* we've already done css_get(mc.to) */
  5152. mc.moved_swap = 0;
  5153. }
  5154. memcg_oom_recover(from);
  5155. memcg_oom_recover(to);
  5156. wake_up_all(&mc.waitq);
  5157. }
  5158. static void mem_cgroup_clear_mc(void)
  5159. {
  5160. struct mem_cgroup *from = mc.from;
  5161. /*
  5162. * we must clear moving_task before waking up waiters at the end of
  5163. * task migration.
  5164. */
  5165. mc.moving_task = NULL;
  5166. __mem_cgroup_clear_mc();
  5167. spin_lock(&mc.lock);
  5168. mc.from = NULL;
  5169. mc.to = NULL;
  5170. spin_unlock(&mc.lock);
  5171. mem_cgroup_end_move(from);
  5172. }
  5173. static int mem_cgroup_can_attach(struct cgroup_subsys_state *css,
  5174. struct cgroup_taskset *tset)
  5175. {
  5176. struct task_struct *p = cgroup_taskset_first(tset);
  5177. int ret = 0;
  5178. struct mem_cgroup *memcg = mem_cgroup_from_css(css);
  5179. unsigned long move_charge_at_immigrate;
  5180. /*
  5181. * We are now commited to this value whatever it is. Changes in this
  5182. * tunable will only affect upcoming migrations, not the current one.
  5183. * So we need to save it, and keep it going.
  5184. */
  5185. move_charge_at_immigrate = memcg->move_charge_at_immigrate;
  5186. if (move_charge_at_immigrate) {
  5187. struct mm_struct *mm;
  5188. struct mem_cgroup *from = mem_cgroup_from_task(p);
  5189. VM_BUG_ON(from == memcg);
  5190. mm = get_task_mm(p);
  5191. if (!mm)
  5192. return 0;
  5193. /* We move charges only when we move a owner of the mm */
  5194. if (mm->owner == p) {
  5195. VM_BUG_ON(mc.from);
  5196. VM_BUG_ON(mc.to);
  5197. VM_BUG_ON(mc.precharge);
  5198. VM_BUG_ON(mc.moved_charge);
  5199. VM_BUG_ON(mc.moved_swap);
  5200. mem_cgroup_start_move(from);
  5201. spin_lock(&mc.lock);
  5202. mc.from = from;
  5203. mc.to = memcg;
  5204. mc.immigrate_flags = move_charge_at_immigrate;
  5205. spin_unlock(&mc.lock);
  5206. /* We set mc.moving_task later */
  5207. ret = mem_cgroup_precharge_mc(mm);
  5208. if (ret)
  5209. mem_cgroup_clear_mc();
  5210. }
  5211. mmput(mm);
  5212. }
  5213. return ret;
  5214. }
  5215. static void mem_cgroup_cancel_attach(struct cgroup_subsys_state *css,
  5216. struct cgroup_taskset *tset)
  5217. {
  5218. mem_cgroup_clear_mc();
  5219. }
  5220. static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
  5221. unsigned long addr, unsigned long end,
  5222. struct mm_walk *walk)
  5223. {
  5224. int ret = 0;
  5225. struct vm_area_struct *vma = walk->private;
  5226. pte_t *pte;
  5227. spinlock_t *ptl;
  5228. enum mc_target_type target_type;
  5229. union mc_target target;
  5230. struct page *page;
  5231. struct page_cgroup *pc;
  5232. /*
  5233. * We don't take compound_lock() here but no race with splitting thp
  5234. * happens because:
  5235. * - if pmd_trans_huge_lock() returns 1, the relevant thp is not
  5236. * under splitting, which means there's no concurrent thp split,
  5237. * - if another thread runs into split_huge_page() just after we
  5238. * entered this if-block, the thread must wait for page table lock
  5239. * to be unlocked in __split_huge_page_splitting(), where the main
  5240. * part of thp split is not executed yet.
  5241. */
  5242. if (pmd_trans_huge_lock(pmd, vma, &ptl) == 1) {
  5243. if (mc.precharge < HPAGE_PMD_NR) {
  5244. spin_unlock(ptl);
  5245. return 0;
  5246. }
  5247. target_type = get_mctgt_type_thp(vma, addr, *pmd, &target);
  5248. if (target_type == MC_TARGET_PAGE) {
  5249. page = target.page;
  5250. if (!isolate_lru_page(page)) {
  5251. pc = lookup_page_cgroup(page);
  5252. if (!mem_cgroup_move_account(page, HPAGE_PMD_NR,
  5253. pc, mc.from, mc.to)) {
  5254. mc.precharge -= HPAGE_PMD_NR;
  5255. mc.moved_charge += HPAGE_PMD_NR;
  5256. }
  5257. putback_lru_page(page);
  5258. }
  5259. put_page(page);
  5260. }
  5261. spin_unlock(ptl);
  5262. return 0;
  5263. }
  5264. if (pmd_trans_unstable(pmd))
  5265. return 0;
  5266. retry:
  5267. pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
  5268. for (; addr != end; addr += PAGE_SIZE) {
  5269. pte_t ptent = *(pte++);
  5270. swp_entry_t ent;
  5271. if (!mc.precharge)
  5272. break;
  5273. switch (get_mctgt_type(vma, addr, ptent, &target)) {
  5274. case MC_TARGET_PAGE:
  5275. page = target.page;
  5276. if (isolate_lru_page(page))
  5277. goto put;
  5278. pc = lookup_page_cgroup(page);
  5279. if (!mem_cgroup_move_account(page, 1, pc,
  5280. mc.from, mc.to)) {
  5281. mc.precharge--;
  5282. /* we uncharge from mc.from later. */
  5283. mc.moved_charge++;
  5284. }
  5285. putback_lru_page(page);
  5286. put: /* get_mctgt_type() gets the page */
  5287. put_page(page);
  5288. break;
  5289. case MC_TARGET_SWAP:
  5290. ent = target.ent;
  5291. if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to)) {
  5292. mc.precharge--;
  5293. /* we fixup refcnts and charges later. */
  5294. mc.moved_swap++;
  5295. }
  5296. break;
  5297. default:
  5298. break;
  5299. }
  5300. }
  5301. pte_unmap_unlock(pte - 1, ptl);
  5302. cond_resched();
  5303. if (addr != end) {
  5304. /*
  5305. * We have consumed all precharges we got in can_attach().
  5306. * We try charge one by one, but don't do any additional
  5307. * charges to mc.to if we have failed in charge once in attach()
  5308. * phase.
  5309. */
  5310. ret = mem_cgroup_do_precharge(1);
  5311. if (!ret)
  5312. goto retry;
  5313. }
  5314. return ret;
  5315. }
  5316. static void mem_cgroup_move_charge(struct mm_struct *mm)
  5317. {
  5318. struct vm_area_struct *vma;
  5319. lru_add_drain_all();
  5320. retry:
  5321. if (unlikely(!down_read_trylock(&mm->mmap_sem))) {
  5322. /*
  5323. * Someone who are holding the mmap_sem might be waiting in
  5324. * waitq. So we cancel all extra charges, wake up all waiters,
  5325. * and retry. Because we cancel precharges, we might not be able
  5326. * to move enough charges, but moving charge is a best-effort
  5327. * feature anyway, so it wouldn't be a big problem.
  5328. */
  5329. __mem_cgroup_clear_mc();
  5330. cond_resched();
  5331. goto retry;
  5332. }
  5333. for (vma = mm->mmap; vma; vma = vma->vm_next) {
  5334. int ret;
  5335. struct mm_walk mem_cgroup_move_charge_walk = {
  5336. .pmd_entry = mem_cgroup_move_charge_pte_range,
  5337. .mm = mm,
  5338. .private = vma,
  5339. };
  5340. if (is_vm_hugetlb_page(vma))
  5341. continue;
  5342. ret = walk_page_range(vma->vm_start, vma->vm_end,
  5343. &mem_cgroup_move_charge_walk);
  5344. if (ret)
  5345. /*
  5346. * means we have consumed all precharges and failed in
  5347. * doing additional charge. Just abandon here.
  5348. */
  5349. break;
  5350. }
  5351. up_read(&mm->mmap_sem);
  5352. }
  5353. static void mem_cgroup_move_task(struct cgroup_subsys_state *css,
  5354. struct cgroup_taskset *tset)
  5355. {
  5356. struct task_struct *p = cgroup_taskset_first(tset);
  5357. struct mm_struct *mm = get_task_mm(p);
  5358. if (mm) {
  5359. if (mc.to)
  5360. mem_cgroup_move_charge(mm);
  5361. mmput(mm);
  5362. }
  5363. if (mc.to)
  5364. mem_cgroup_clear_mc();
  5365. }
  5366. #else /* !CONFIG_MMU */
  5367. static int mem_cgroup_can_attach(struct cgroup_subsys_state *css,
  5368. struct cgroup_taskset *tset)
  5369. {
  5370. return 0;
  5371. }
  5372. static void mem_cgroup_cancel_attach(struct cgroup_subsys_state *css,
  5373. struct cgroup_taskset *tset)
  5374. {
  5375. }
  5376. static void mem_cgroup_move_task(struct cgroup_subsys_state *css,
  5377. struct cgroup_taskset *tset)
  5378. {
  5379. }
  5380. #endif
  5381. /*
  5382. * Cgroup retains root cgroups across [un]mount cycles making it necessary
  5383. * to verify whether we're attached to the default hierarchy on each mount
  5384. * attempt.
  5385. */
  5386. static void mem_cgroup_bind(struct cgroup_subsys_state *root_css)
  5387. {
  5388. /*
  5389. * use_hierarchy is forced on the default hierarchy. cgroup core
  5390. * guarantees that @root doesn't have any children, so turning it
  5391. * on for the root memcg is enough.
  5392. */
  5393. if (cgroup_on_dfl(root_css->cgroup))
  5394. mem_cgroup_from_css(root_css)->use_hierarchy = true;
  5395. }
  5396. struct cgroup_subsys memory_cgrp_subsys = {
  5397. .css_alloc = mem_cgroup_css_alloc,
  5398. .css_online = mem_cgroup_css_online,
  5399. .css_offline = mem_cgroup_css_offline,
  5400. .css_free = mem_cgroup_css_free,
  5401. .css_reset = mem_cgroup_css_reset,
  5402. .can_attach = mem_cgroup_can_attach,
  5403. .cancel_attach = mem_cgroup_cancel_attach,
  5404. .attach = mem_cgroup_move_task,
  5405. .bind = mem_cgroup_bind,
  5406. .legacy_cftypes = mem_cgroup_files,
  5407. .early_init = 0,
  5408. };
  5409. #ifdef CONFIG_MEMCG_SWAP
  5410. static int __init enable_swap_account(char *s)
  5411. {
  5412. if (!strcmp(s, "1"))
  5413. really_do_swap_account = 1;
  5414. else if (!strcmp(s, "0"))
  5415. really_do_swap_account = 0;
  5416. return 1;
  5417. }
  5418. __setup("swapaccount=", enable_swap_account);
  5419. static void __init memsw_file_init(void)
  5420. {
  5421. WARN_ON(cgroup_add_legacy_cftypes(&memory_cgrp_subsys,
  5422. memsw_cgroup_files));
  5423. }
  5424. static void __init enable_swap_cgroup(void)
  5425. {
  5426. if (!mem_cgroup_disabled() && really_do_swap_account) {
  5427. do_swap_account = 1;
  5428. memsw_file_init();
  5429. }
  5430. }
  5431. #else
  5432. static void __init enable_swap_cgroup(void)
  5433. {
  5434. }
  5435. #endif
  5436. #ifdef CONFIG_MEMCG_SWAP
  5437. /**
  5438. * mem_cgroup_swapout - transfer a memsw charge to swap
  5439. * @page: page whose memsw charge to transfer
  5440. * @entry: swap entry to move the charge to
  5441. *
  5442. * Transfer the memsw charge of @page to @entry.
  5443. */
  5444. void mem_cgroup_swapout(struct page *page, swp_entry_t entry)
  5445. {
  5446. struct page_cgroup *pc;
  5447. unsigned short oldid;
  5448. VM_BUG_ON_PAGE(PageLRU(page), page);
  5449. VM_BUG_ON_PAGE(page_count(page), page);
  5450. if (!do_swap_account)
  5451. return;
  5452. pc = lookup_page_cgroup(page);
  5453. /* Readahead page, never charged */
  5454. if (!PageCgroupUsed(pc))
  5455. return;
  5456. VM_BUG_ON_PAGE(!(pc->flags & PCG_MEMSW), page);
  5457. oldid = swap_cgroup_record(entry, mem_cgroup_id(pc->mem_cgroup));
  5458. VM_BUG_ON_PAGE(oldid, page);
  5459. pc->flags &= ~PCG_MEMSW;
  5460. css_get(&pc->mem_cgroup->css);
  5461. mem_cgroup_swap_statistics(pc->mem_cgroup, true);
  5462. }
  5463. /**
  5464. * mem_cgroup_uncharge_swap - uncharge a swap entry
  5465. * @entry: swap entry to uncharge
  5466. *
  5467. * Drop the memsw charge associated with @entry.
  5468. */
  5469. void mem_cgroup_uncharge_swap(swp_entry_t entry)
  5470. {
  5471. struct mem_cgroup *memcg;
  5472. unsigned short id;
  5473. if (!do_swap_account)
  5474. return;
  5475. id = swap_cgroup_record(entry, 0);
  5476. rcu_read_lock();
  5477. memcg = mem_cgroup_lookup(id);
  5478. if (memcg) {
  5479. if (!mem_cgroup_is_root(memcg))
  5480. res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
  5481. mem_cgroup_swap_statistics(memcg, false);
  5482. css_put(&memcg->css);
  5483. }
  5484. rcu_read_unlock();
  5485. }
  5486. #endif
  5487. /**
  5488. * mem_cgroup_try_charge - try charging a page
  5489. * @page: page to charge
  5490. * @mm: mm context of the victim
  5491. * @gfp_mask: reclaim mode
  5492. * @memcgp: charged memcg return
  5493. *
  5494. * Try to charge @page to the memcg that @mm belongs to, reclaiming
  5495. * pages according to @gfp_mask if necessary.
  5496. *
  5497. * Returns 0 on success, with *@memcgp pointing to the charged memcg.
  5498. * Otherwise, an error code is returned.
  5499. *
  5500. * After page->mapping has been set up, the caller must finalize the
  5501. * charge with mem_cgroup_commit_charge(). Or abort the transaction
  5502. * with mem_cgroup_cancel_charge() in case page instantiation fails.
  5503. */
  5504. int mem_cgroup_try_charge(struct page *page, struct mm_struct *mm,
  5505. gfp_t gfp_mask, struct mem_cgroup **memcgp)
  5506. {
  5507. struct mem_cgroup *memcg = NULL;
  5508. unsigned int nr_pages = 1;
  5509. int ret = 0;
  5510. if (mem_cgroup_disabled())
  5511. goto out;
  5512. if (PageSwapCache(page)) {
  5513. struct page_cgroup *pc = lookup_page_cgroup(page);
  5514. /*
  5515. * Every swap fault against a single page tries to charge the
  5516. * page, bail as early as possible. shmem_unuse() encounters
  5517. * already charged pages, too. The USED bit is protected by
  5518. * the page lock, which serializes swap cache removal, which
  5519. * in turn serializes uncharging.
  5520. */
  5521. if (PageCgroupUsed(pc))
  5522. goto out;
  5523. }
  5524. if (PageTransHuge(page)) {
  5525. nr_pages <<= compound_order(page);
  5526. VM_BUG_ON_PAGE(!PageTransHuge(page), page);
  5527. }
  5528. if (do_swap_account && PageSwapCache(page))
  5529. memcg = try_get_mem_cgroup_from_page(page);
  5530. if (!memcg)
  5531. memcg = get_mem_cgroup_from_mm(mm);
  5532. ret = try_charge(memcg, gfp_mask, nr_pages);
  5533. css_put(&memcg->css);
  5534. if (ret == -EINTR) {
  5535. memcg = root_mem_cgroup;
  5536. ret = 0;
  5537. }
  5538. out:
  5539. *memcgp = memcg;
  5540. return ret;
  5541. }
  5542. /**
  5543. * mem_cgroup_commit_charge - commit a page charge
  5544. * @page: page to charge
  5545. * @memcg: memcg to charge the page to
  5546. * @lrucare: page might be on LRU already
  5547. *
  5548. * Finalize a charge transaction started by mem_cgroup_try_charge(),
  5549. * after page->mapping has been set up. This must happen atomically
  5550. * as part of the page instantiation, i.e. under the page table lock
  5551. * for anonymous pages, under the page lock for page and swap cache.
  5552. *
  5553. * In addition, the page must not be on the LRU during the commit, to
  5554. * prevent racing with task migration. If it might be, use @lrucare.
  5555. *
  5556. * Use mem_cgroup_cancel_charge() to cancel the transaction instead.
  5557. */
  5558. void mem_cgroup_commit_charge(struct page *page, struct mem_cgroup *memcg,
  5559. bool lrucare)
  5560. {
  5561. unsigned int nr_pages = 1;
  5562. VM_BUG_ON_PAGE(!page->mapping, page);
  5563. VM_BUG_ON_PAGE(PageLRU(page) && !lrucare, page);
  5564. if (mem_cgroup_disabled())
  5565. return;
  5566. /*
  5567. * Swap faults will attempt to charge the same page multiple
  5568. * times. But reuse_swap_page() might have removed the page
  5569. * from swapcache already, so we can't check PageSwapCache().
  5570. */
  5571. if (!memcg)
  5572. return;
  5573. commit_charge(page, memcg, lrucare);
  5574. if (PageTransHuge(page)) {
  5575. nr_pages <<= compound_order(page);
  5576. VM_BUG_ON_PAGE(!PageTransHuge(page), page);
  5577. }
  5578. local_irq_disable();
  5579. mem_cgroup_charge_statistics(memcg, page, nr_pages);
  5580. memcg_check_events(memcg, page);
  5581. local_irq_enable();
  5582. if (do_swap_account && PageSwapCache(page)) {
  5583. swp_entry_t entry = { .val = page_private(page) };
  5584. /*
  5585. * The swap entry might not get freed for a long time,
  5586. * let's not wait for it. The page already received a
  5587. * memory+swap charge, drop the swap entry duplicate.
  5588. */
  5589. mem_cgroup_uncharge_swap(entry);
  5590. }
  5591. }
  5592. /**
  5593. * mem_cgroup_cancel_charge - cancel a page charge
  5594. * @page: page to charge
  5595. * @memcg: memcg to charge the page to
  5596. *
  5597. * Cancel a charge transaction started by mem_cgroup_try_charge().
  5598. */
  5599. void mem_cgroup_cancel_charge(struct page *page, struct mem_cgroup *memcg)
  5600. {
  5601. unsigned int nr_pages = 1;
  5602. if (mem_cgroup_disabled())
  5603. return;
  5604. /*
  5605. * Swap faults will attempt to charge the same page multiple
  5606. * times. But reuse_swap_page() might have removed the page
  5607. * from swapcache already, so we can't check PageSwapCache().
  5608. */
  5609. if (!memcg)
  5610. return;
  5611. if (PageTransHuge(page)) {
  5612. nr_pages <<= compound_order(page);
  5613. VM_BUG_ON_PAGE(!PageTransHuge(page), page);
  5614. }
  5615. cancel_charge(memcg, nr_pages);
  5616. }
  5617. static void uncharge_batch(struct mem_cgroup *memcg, unsigned long pgpgout,
  5618. unsigned long nr_mem, unsigned long nr_memsw,
  5619. unsigned long nr_anon, unsigned long nr_file,
  5620. unsigned long nr_huge, struct page *dummy_page)
  5621. {
  5622. unsigned long flags;
  5623. if (!mem_cgroup_is_root(memcg)) {
  5624. if (nr_mem)
  5625. res_counter_uncharge(&memcg->res,
  5626. nr_mem * PAGE_SIZE);
  5627. if (nr_memsw)
  5628. res_counter_uncharge(&memcg->memsw,
  5629. nr_memsw * PAGE_SIZE);
  5630. memcg_oom_recover(memcg);
  5631. }
  5632. local_irq_save(flags);
  5633. __this_cpu_sub(memcg->stat->count[MEM_CGROUP_STAT_RSS], nr_anon);
  5634. __this_cpu_sub(memcg->stat->count[MEM_CGROUP_STAT_CACHE], nr_file);
  5635. __this_cpu_sub(memcg->stat->count[MEM_CGROUP_STAT_RSS_HUGE], nr_huge);
  5636. __this_cpu_add(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGOUT], pgpgout);
  5637. __this_cpu_add(memcg->stat->nr_page_events, nr_anon + nr_file);
  5638. memcg_check_events(memcg, dummy_page);
  5639. local_irq_restore(flags);
  5640. }
  5641. static void uncharge_list(struct list_head *page_list)
  5642. {
  5643. struct mem_cgroup *memcg = NULL;
  5644. unsigned long nr_memsw = 0;
  5645. unsigned long nr_anon = 0;
  5646. unsigned long nr_file = 0;
  5647. unsigned long nr_huge = 0;
  5648. unsigned long pgpgout = 0;
  5649. unsigned long nr_mem = 0;
  5650. struct list_head *next;
  5651. struct page *page;
  5652. next = page_list->next;
  5653. do {
  5654. unsigned int nr_pages = 1;
  5655. struct page_cgroup *pc;
  5656. page = list_entry(next, struct page, lru);
  5657. next = page->lru.next;
  5658. VM_BUG_ON_PAGE(PageLRU(page), page);
  5659. VM_BUG_ON_PAGE(page_count(page), page);
  5660. pc = lookup_page_cgroup(page);
  5661. if (!PageCgroupUsed(pc))
  5662. continue;
  5663. /*
  5664. * Nobody should be changing or seriously looking at
  5665. * pc->mem_cgroup and pc->flags at this point, we have
  5666. * fully exclusive access to the page.
  5667. */
  5668. if (memcg != pc->mem_cgroup) {
  5669. if (memcg) {
  5670. uncharge_batch(memcg, pgpgout, nr_mem, nr_memsw,
  5671. nr_anon, nr_file, nr_huge, page);
  5672. pgpgout = nr_mem = nr_memsw = 0;
  5673. nr_anon = nr_file = nr_huge = 0;
  5674. }
  5675. memcg = pc->mem_cgroup;
  5676. }
  5677. if (PageTransHuge(page)) {
  5678. nr_pages <<= compound_order(page);
  5679. VM_BUG_ON_PAGE(!PageTransHuge(page), page);
  5680. nr_huge += nr_pages;
  5681. }
  5682. if (PageAnon(page))
  5683. nr_anon += nr_pages;
  5684. else
  5685. nr_file += nr_pages;
  5686. if (pc->flags & PCG_MEM)
  5687. nr_mem += nr_pages;
  5688. if (pc->flags & PCG_MEMSW)
  5689. nr_memsw += nr_pages;
  5690. pc->flags = 0;
  5691. pgpgout++;
  5692. } while (next != page_list);
  5693. if (memcg)
  5694. uncharge_batch(memcg, pgpgout, nr_mem, nr_memsw,
  5695. nr_anon, nr_file, nr_huge, page);
  5696. }
  5697. /**
  5698. * mem_cgroup_uncharge - uncharge a page
  5699. * @page: page to uncharge
  5700. *
  5701. * Uncharge a page previously charged with mem_cgroup_try_charge() and
  5702. * mem_cgroup_commit_charge().
  5703. */
  5704. void mem_cgroup_uncharge(struct page *page)
  5705. {
  5706. struct page_cgroup *pc;
  5707. if (mem_cgroup_disabled())
  5708. return;
  5709. /* Don't touch page->lru of any random page, pre-check: */
  5710. pc = lookup_page_cgroup(page);
  5711. if (!PageCgroupUsed(pc))
  5712. return;
  5713. INIT_LIST_HEAD(&page->lru);
  5714. uncharge_list(&page->lru);
  5715. }
  5716. /**
  5717. * mem_cgroup_uncharge_list - uncharge a list of page
  5718. * @page_list: list of pages to uncharge
  5719. *
  5720. * Uncharge a list of pages previously charged with
  5721. * mem_cgroup_try_charge() and mem_cgroup_commit_charge().
  5722. */
  5723. void mem_cgroup_uncharge_list(struct list_head *page_list)
  5724. {
  5725. if (mem_cgroup_disabled())
  5726. return;
  5727. if (!list_empty(page_list))
  5728. uncharge_list(page_list);
  5729. }
  5730. /**
  5731. * mem_cgroup_migrate - migrate a charge to another page
  5732. * @oldpage: currently charged page
  5733. * @newpage: page to transfer the charge to
  5734. * @lrucare: both pages might be on the LRU already
  5735. *
  5736. * Migrate the charge from @oldpage to @newpage.
  5737. *
  5738. * Both pages must be locked, @newpage->mapping must be set up.
  5739. */
  5740. void mem_cgroup_migrate(struct page *oldpage, struct page *newpage,
  5741. bool lrucare)
  5742. {
  5743. struct page_cgroup *pc;
  5744. int isolated;
  5745. VM_BUG_ON_PAGE(!PageLocked(oldpage), oldpage);
  5746. VM_BUG_ON_PAGE(!PageLocked(newpage), newpage);
  5747. VM_BUG_ON_PAGE(!lrucare && PageLRU(oldpage), oldpage);
  5748. VM_BUG_ON_PAGE(!lrucare && PageLRU(newpage), newpage);
  5749. VM_BUG_ON_PAGE(PageAnon(oldpage) != PageAnon(newpage), newpage);
  5750. VM_BUG_ON_PAGE(PageTransHuge(oldpage) != PageTransHuge(newpage),
  5751. newpage);
  5752. if (mem_cgroup_disabled())
  5753. return;
  5754. /* Page cache replacement: new page already charged? */
  5755. pc = lookup_page_cgroup(newpage);
  5756. if (PageCgroupUsed(pc))
  5757. return;
  5758. /* Re-entrant migration: old page already uncharged? */
  5759. pc = lookup_page_cgroup(oldpage);
  5760. if (!PageCgroupUsed(pc))
  5761. return;
  5762. VM_BUG_ON_PAGE(!(pc->flags & PCG_MEM), oldpage);
  5763. VM_BUG_ON_PAGE(do_swap_account && !(pc->flags & PCG_MEMSW), oldpage);
  5764. if (lrucare)
  5765. lock_page_lru(oldpage, &isolated);
  5766. pc->flags = 0;
  5767. if (lrucare)
  5768. unlock_page_lru(oldpage, isolated);
  5769. commit_charge(newpage, pc->mem_cgroup, lrucare);
  5770. }
  5771. /*
  5772. * subsys_initcall() for memory controller.
  5773. *
  5774. * Some parts like hotcpu_notifier() have to be initialized from this context
  5775. * because of lock dependencies (cgroup_lock -> cpu hotplug) but basically
  5776. * everything that doesn't depend on a specific mem_cgroup structure should
  5777. * be initialized from here.
  5778. */
  5779. static int __init mem_cgroup_init(void)
  5780. {
  5781. hotcpu_notifier(memcg_cpu_hotplug_callback, 0);
  5782. enable_swap_cgroup();
  5783. mem_cgroup_soft_limit_tree_init();
  5784. memcg_stock_init();
  5785. return 0;
  5786. }
  5787. subsys_initcall(mem_cgroup_init);