memcontrol.c 183 KB

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