memcontrol.c 146 KB

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