memcontrol.c 128 KB

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