memcontrol.c 131 KB

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