memcontrol.c 179 KB

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