memcontrol.c 186 KB

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