memcontrol.c 120 KB

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