memcontrol.c 134 KB

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