memcontrol.c 193 KB

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