memcontrol.c 175 KB

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