memcontrol.c 182 KB

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