memcontrol.c 150 KB

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