memcontrol.c 182 KB

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