memcontrol.c 132 KB

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