memcontrol.c 130 KB

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