memcontrol.c 179 KB

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