memcontrol.c 194 KB

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