memcontrol.c 185 KB

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