memcontrol.c 181 KB

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