memcontrol.c 143 KB

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