memcontrol.c 186 KB

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