memcontrol.c 179 KB

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