memcontrol.c 159 KB

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