memcontrol.c 186 KB

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