memcontrol.c 186 KB

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