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. if (unlikely(!PageCgroupUsed(pc)))
  936. continue;
  937. page = pc->page;
  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 *page,
  1850. struct page_cgroup *pc,
  1851. enum charge_type ctype,
  1852. int page_size)
  1853. {
  1854. int nr_pages = page_size >> PAGE_SHIFT;
  1855. lock_page_cgroup(pc);
  1856. if (unlikely(PageCgroupUsed(pc))) {
  1857. unlock_page_cgroup(pc);
  1858. mem_cgroup_cancel_charge(mem, page_size);
  1859. return;
  1860. }
  1861. /*
  1862. * we don't need page_cgroup_lock about tail pages, becase they are not
  1863. * accessed by any other context at this point.
  1864. */
  1865. pc->mem_cgroup = mem;
  1866. /*
  1867. * We access a page_cgroup asynchronously without lock_page_cgroup().
  1868. * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
  1869. * is accessed after testing USED bit. To make pc->mem_cgroup visible
  1870. * before USED bit, we need memory barrier here.
  1871. * See mem_cgroup_add_lru_list(), etc.
  1872. */
  1873. smp_wmb();
  1874. switch (ctype) {
  1875. case MEM_CGROUP_CHARGE_TYPE_CACHE:
  1876. case MEM_CGROUP_CHARGE_TYPE_SHMEM:
  1877. SetPageCgroupCache(pc);
  1878. SetPageCgroupUsed(pc);
  1879. break;
  1880. case MEM_CGROUP_CHARGE_TYPE_MAPPED:
  1881. ClearPageCgroupCache(pc);
  1882. SetPageCgroupUsed(pc);
  1883. break;
  1884. default:
  1885. break;
  1886. }
  1887. mem_cgroup_charge_statistics(mem, PageCgroupCache(pc), nr_pages);
  1888. unlock_page_cgroup(pc);
  1889. /*
  1890. * "charge_statistics" updated event counter. Then, check it.
  1891. * Insert ancestor (and ancestor's ancestors), to softlimit RB-tree.
  1892. * if they exceeds softlimit.
  1893. */
  1894. memcg_check_events(mem, page);
  1895. }
  1896. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  1897. #define PCGF_NOCOPY_AT_SPLIT ((1 << PCG_LOCK) | (1 << PCG_MOVE_LOCK) |\
  1898. (1 << PCG_ACCT_LRU) | (1 << PCG_MIGRATION))
  1899. /*
  1900. * Because tail pages are not marked as "used", set it. We're under
  1901. * zone->lru_lock, 'splitting on pmd' and compund_lock.
  1902. */
  1903. void mem_cgroup_split_huge_fixup(struct page *head, struct page *tail)
  1904. {
  1905. struct page_cgroup *head_pc = lookup_page_cgroup(head);
  1906. struct page_cgroup *tail_pc = lookup_page_cgroup(tail);
  1907. unsigned long flags;
  1908. if (mem_cgroup_disabled())
  1909. return;
  1910. /*
  1911. * We have no races with charge/uncharge but will have races with
  1912. * page state accounting.
  1913. */
  1914. move_lock_page_cgroup(head_pc, &flags);
  1915. tail_pc->mem_cgroup = head_pc->mem_cgroup;
  1916. smp_wmb(); /* see __commit_charge() */
  1917. if (PageCgroupAcctLRU(head_pc)) {
  1918. enum lru_list lru;
  1919. struct mem_cgroup_per_zone *mz;
  1920. /*
  1921. * LRU flags cannot be copied because we need to add tail
  1922. *.page to LRU by generic call and our hook will be called.
  1923. * We hold lru_lock, then, reduce counter directly.
  1924. */
  1925. lru = page_lru(head);
  1926. mz = page_cgroup_zoneinfo(head_pc->mem_cgroup, head);
  1927. MEM_CGROUP_ZSTAT(mz, lru) -= 1;
  1928. }
  1929. tail_pc->flags = head_pc->flags & ~PCGF_NOCOPY_AT_SPLIT;
  1930. move_unlock_page_cgroup(head_pc, &flags);
  1931. }
  1932. #endif
  1933. /**
  1934. * mem_cgroup_move_account - move account of the page
  1935. * @page: the page
  1936. * @pc: page_cgroup of the page.
  1937. * @from: mem_cgroup which the page is moved from.
  1938. * @to: mem_cgroup which the page is moved to. @from != @to.
  1939. * @uncharge: whether we should call uncharge and css_put against @from.
  1940. * @charge_size: number of bytes to charge (regular or huge page)
  1941. *
  1942. * The caller must confirm following.
  1943. * - page is not on LRU (isolate_page() is useful.)
  1944. * - compound_lock is held when charge_size > PAGE_SIZE
  1945. *
  1946. * This function doesn't do "charge" nor css_get to new cgroup. It should be
  1947. * done by a caller(__mem_cgroup_try_charge would be usefull). If @uncharge is
  1948. * true, this function does "uncharge" from old cgroup, but it doesn't if
  1949. * @uncharge is false, so a caller should do "uncharge".
  1950. */
  1951. static int mem_cgroup_move_account(struct page *page, struct page_cgroup *pc,
  1952. struct mem_cgroup *from, struct mem_cgroup *to,
  1953. bool uncharge, int charge_size)
  1954. {
  1955. int nr_pages = charge_size >> PAGE_SHIFT;
  1956. unsigned long flags;
  1957. int ret;
  1958. VM_BUG_ON(from == to);
  1959. VM_BUG_ON(PageLRU(page));
  1960. /*
  1961. * The page is isolated from LRU. So, collapse function
  1962. * will not handle this page. But page splitting can happen.
  1963. * Do this check under compound_page_lock(). The caller should
  1964. * hold it.
  1965. */
  1966. ret = -EBUSY;
  1967. if (charge_size > PAGE_SIZE && !PageTransHuge(page))
  1968. goto out;
  1969. lock_page_cgroup(pc);
  1970. ret = -EINVAL;
  1971. if (!PageCgroupUsed(pc) || pc->mem_cgroup != from)
  1972. goto unlock;
  1973. move_lock_page_cgroup(pc, &flags);
  1974. if (PageCgroupFileMapped(pc)) {
  1975. /* Update mapped_file data for mem_cgroup */
  1976. preempt_disable();
  1977. __this_cpu_dec(from->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
  1978. __this_cpu_inc(to->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
  1979. preempt_enable();
  1980. }
  1981. mem_cgroup_charge_statistics(from, PageCgroupCache(pc), -nr_pages);
  1982. if (uncharge)
  1983. /* This is not "cancel", but cancel_charge does all we need. */
  1984. mem_cgroup_cancel_charge(from, charge_size);
  1985. /* caller should have done css_get */
  1986. pc->mem_cgroup = to;
  1987. mem_cgroup_charge_statistics(to, PageCgroupCache(pc), nr_pages);
  1988. /*
  1989. * We charges against "to" which may not have any tasks. Then, "to"
  1990. * can be under rmdir(). But in current implementation, caller of
  1991. * this function is just force_empty() and move charge, so it's
  1992. * garanteed that "to" is never removed. So, we don't check rmdir
  1993. * status here.
  1994. */
  1995. move_unlock_page_cgroup(pc, &flags);
  1996. ret = 0;
  1997. unlock:
  1998. unlock_page_cgroup(pc);
  1999. /*
  2000. * check events
  2001. */
  2002. memcg_check_events(to, page);
  2003. memcg_check_events(from, page);
  2004. out:
  2005. return ret;
  2006. }
  2007. /*
  2008. * move charges to its parent.
  2009. */
  2010. static int mem_cgroup_move_parent(struct page *page,
  2011. struct page_cgroup *pc,
  2012. struct mem_cgroup *child,
  2013. gfp_t gfp_mask)
  2014. {
  2015. struct cgroup *cg = child->css.cgroup;
  2016. struct cgroup *pcg = cg->parent;
  2017. struct mem_cgroup *parent;
  2018. int page_size = PAGE_SIZE;
  2019. unsigned long flags;
  2020. int ret;
  2021. /* Is ROOT ? */
  2022. if (!pcg)
  2023. return -EINVAL;
  2024. ret = -EBUSY;
  2025. if (!get_page_unless_zero(page))
  2026. goto out;
  2027. if (isolate_lru_page(page))
  2028. goto put;
  2029. if (PageTransHuge(page))
  2030. page_size = HPAGE_SIZE;
  2031. parent = mem_cgroup_from_cont(pcg);
  2032. ret = __mem_cgroup_try_charge(NULL, gfp_mask,
  2033. &parent, false, page_size);
  2034. if (ret || !parent)
  2035. goto put_back;
  2036. if (page_size > PAGE_SIZE)
  2037. flags = compound_lock_irqsave(page);
  2038. ret = mem_cgroup_move_account(page, pc, child, parent, true, page_size);
  2039. if (ret)
  2040. mem_cgroup_cancel_charge(parent, page_size);
  2041. if (page_size > PAGE_SIZE)
  2042. compound_unlock_irqrestore(page, flags);
  2043. put_back:
  2044. putback_lru_page(page);
  2045. put:
  2046. put_page(page);
  2047. out:
  2048. return ret;
  2049. }
  2050. /*
  2051. * Charge the memory controller for page usage.
  2052. * Return
  2053. * 0 if the charge was successful
  2054. * < 0 if the cgroup is over its limit
  2055. */
  2056. static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
  2057. gfp_t gfp_mask, enum charge_type ctype)
  2058. {
  2059. struct mem_cgroup *mem = NULL;
  2060. int page_size = PAGE_SIZE;
  2061. struct page_cgroup *pc;
  2062. bool oom = true;
  2063. int ret;
  2064. if (PageTransHuge(page)) {
  2065. page_size <<= compound_order(page);
  2066. VM_BUG_ON(!PageTransHuge(page));
  2067. /*
  2068. * Never OOM-kill a process for a huge page. The
  2069. * fault handler will fall back to regular pages.
  2070. */
  2071. oom = false;
  2072. }
  2073. pc = lookup_page_cgroup(page);
  2074. BUG_ON(!pc); /* XXX: remove this and move pc lookup into commit */
  2075. ret = __mem_cgroup_try_charge(mm, gfp_mask, &mem, oom, page_size);
  2076. if (ret || !mem)
  2077. return ret;
  2078. __mem_cgroup_commit_charge(mem, page, pc, ctype, page_size);
  2079. return 0;
  2080. }
  2081. int mem_cgroup_newpage_charge(struct page *page,
  2082. struct mm_struct *mm, gfp_t gfp_mask)
  2083. {
  2084. if (mem_cgroup_disabled())
  2085. return 0;
  2086. /*
  2087. * If already mapped, we don't have to account.
  2088. * If page cache, page->mapping has address_space.
  2089. * But page->mapping may have out-of-use anon_vma pointer,
  2090. * detecit it by PageAnon() check. newly-mapped-anon's page->mapping
  2091. * is NULL.
  2092. */
  2093. if (page_mapped(page) || (page->mapping && !PageAnon(page)))
  2094. return 0;
  2095. if (unlikely(!mm))
  2096. mm = &init_mm;
  2097. return mem_cgroup_charge_common(page, mm, gfp_mask,
  2098. MEM_CGROUP_CHARGE_TYPE_MAPPED);
  2099. }
  2100. static void
  2101. __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
  2102. enum charge_type ctype);
  2103. int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
  2104. gfp_t gfp_mask)
  2105. {
  2106. int ret;
  2107. if (mem_cgroup_disabled())
  2108. return 0;
  2109. if (PageCompound(page))
  2110. return 0;
  2111. /*
  2112. * Corner case handling. This is called from add_to_page_cache()
  2113. * in usual. But some FS (shmem) precharges this page before calling it
  2114. * and call add_to_page_cache() with GFP_NOWAIT.
  2115. *
  2116. * For GFP_NOWAIT case, the page may be pre-charged before calling
  2117. * add_to_page_cache(). (See shmem.c) check it here and avoid to call
  2118. * charge twice. (It works but has to pay a bit larger cost.)
  2119. * And when the page is SwapCache, it should take swap information
  2120. * into account. This is under lock_page() now.
  2121. */
  2122. if (!(gfp_mask & __GFP_WAIT)) {
  2123. struct page_cgroup *pc;
  2124. pc = lookup_page_cgroup(page);
  2125. if (!pc)
  2126. return 0;
  2127. lock_page_cgroup(pc);
  2128. if (PageCgroupUsed(pc)) {
  2129. unlock_page_cgroup(pc);
  2130. return 0;
  2131. }
  2132. unlock_page_cgroup(pc);
  2133. }
  2134. if (unlikely(!mm))
  2135. mm = &init_mm;
  2136. if (page_is_file_cache(page))
  2137. return mem_cgroup_charge_common(page, mm, gfp_mask,
  2138. MEM_CGROUP_CHARGE_TYPE_CACHE);
  2139. /* shmem */
  2140. if (PageSwapCache(page)) {
  2141. struct mem_cgroup *mem;
  2142. ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &mem);
  2143. if (!ret)
  2144. __mem_cgroup_commit_charge_swapin(page, mem,
  2145. MEM_CGROUP_CHARGE_TYPE_SHMEM);
  2146. } else
  2147. ret = mem_cgroup_charge_common(page, mm, gfp_mask,
  2148. MEM_CGROUP_CHARGE_TYPE_SHMEM);
  2149. return ret;
  2150. }
  2151. /*
  2152. * While swap-in, try_charge -> commit or cancel, the page is locked.
  2153. * And when try_charge() successfully returns, one refcnt to memcg without
  2154. * struct page_cgroup is acquired. This refcnt will be consumed by
  2155. * "commit()" or removed by "cancel()"
  2156. */
  2157. int mem_cgroup_try_charge_swapin(struct mm_struct *mm,
  2158. struct page *page,
  2159. gfp_t mask, struct mem_cgroup **ptr)
  2160. {
  2161. struct mem_cgroup *mem;
  2162. int ret;
  2163. *ptr = NULL;
  2164. if (mem_cgroup_disabled())
  2165. return 0;
  2166. if (!do_swap_account)
  2167. goto charge_cur_mm;
  2168. /*
  2169. * A racing thread's fault, or swapoff, may have already updated
  2170. * the pte, and even removed page from swap cache: in those cases
  2171. * do_swap_page()'s pte_same() test will fail; but there's also a
  2172. * KSM case which does need to charge the page.
  2173. */
  2174. if (!PageSwapCache(page))
  2175. goto charge_cur_mm;
  2176. mem = try_get_mem_cgroup_from_page(page);
  2177. if (!mem)
  2178. goto charge_cur_mm;
  2179. *ptr = mem;
  2180. ret = __mem_cgroup_try_charge(NULL, mask, ptr, true, PAGE_SIZE);
  2181. css_put(&mem->css);
  2182. return ret;
  2183. charge_cur_mm:
  2184. if (unlikely(!mm))
  2185. mm = &init_mm;
  2186. return __mem_cgroup_try_charge(mm, mask, ptr, true, PAGE_SIZE);
  2187. }
  2188. static void
  2189. __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
  2190. enum charge_type ctype)
  2191. {
  2192. struct page_cgroup *pc;
  2193. if (mem_cgroup_disabled())
  2194. return;
  2195. if (!ptr)
  2196. return;
  2197. cgroup_exclude_rmdir(&ptr->css);
  2198. pc = lookup_page_cgroup(page);
  2199. mem_cgroup_lru_del_before_commit_swapcache(page);
  2200. __mem_cgroup_commit_charge(ptr, page, pc, ctype, PAGE_SIZE);
  2201. mem_cgroup_lru_add_after_commit_swapcache(page);
  2202. /*
  2203. * Now swap is on-memory. This means this page may be
  2204. * counted both as mem and swap....double count.
  2205. * Fix it by uncharging from memsw. Basically, this SwapCache is stable
  2206. * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
  2207. * may call delete_from_swap_cache() before reach here.
  2208. */
  2209. if (do_swap_account && PageSwapCache(page)) {
  2210. swp_entry_t ent = {.val = page_private(page)};
  2211. unsigned short id;
  2212. struct mem_cgroup *memcg;
  2213. id = swap_cgroup_record(ent, 0);
  2214. rcu_read_lock();
  2215. memcg = mem_cgroup_lookup(id);
  2216. if (memcg) {
  2217. /*
  2218. * This recorded memcg can be obsolete one. So, avoid
  2219. * calling css_tryget
  2220. */
  2221. if (!mem_cgroup_is_root(memcg))
  2222. res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
  2223. mem_cgroup_swap_statistics(memcg, false);
  2224. mem_cgroup_put(memcg);
  2225. }
  2226. rcu_read_unlock();
  2227. }
  2228. /*
  2229. * At swapin, we may charge account against cgroup which has no tasks.
  2230. * So, rmdir()->pre_destroy() can be called while we do this charge.
  2231. * In that case, we need to call pre_destroy() again. check it here.
  2232. */
  2233. cgroup_release_and_wakeup_rmdir(&ptr->css);
  2234. }
  2235. void mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr)
  2236. {
  2237. __mem_cgroup_commit_charge_swapin(page, ptr,
  2238. MEM_CGROUP_CHARGE_TYPE_MAPPED);
  2239. }
  2240. void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *mem)
  2241. {
  2242. if (mem_cgroup_disabled())
  2243. return;
  2244. if (!mem)
  2245. return;
  2246. mem_cgroup_cancel_charge(mem, PAGE_SIZE);
  2247. }
  2248. static void
  2249. __do_uncharge(struct mem_cgroup *mem, const enum charge_type ctype,
  2250. int page_size)
  2251. {
  2252. struct memcg_batch_info *batch = NULL;
  2253. bool uncharge_memsw = true;
  2254. /* If swapout, usage of swap doesn't decrease */
  2255. if (!do_swap_account || ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
  2256. uncharge_memsw = false;
  2257. batch = &current->memcg_batch;
  2258. /*
  2259. * In usual, we do css_get() when we remember memcg pointer.
  2260. * But in this case, we keep res->usage until end of a series of
  2261. * uncharges. Then, it's ok to ignore memcg's refcnt.
  2262. */
  2263. if (!batch->memcg)
  2264. batch->memcg = mem;
  2265. /*
  2266. * do_batch > 0 when unmapping pages or inode invalidate/truncate.
  2267. * In those cases, all pages freed continously can be expected to be in
  2268. * the same cgroup and we have chance to coalesce uncharges.
  2269. * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE)
  2270. * because we want to do uncharge as soon as possible.
  2271. */
  2272. if (!batch->do_batch || test_thread_flag(TIF_MEMDIE))
  2273. goto direct_uncharge;
  2274. if (page_size != PAGE_SIZE)
  2275. goto direct_uncharge;
  2276. /*
  2277. * In typical case, batch->memcg == mem. This means we can
  2278. * merge a series of uncharges to an uncharge of res_counter.
  2279. * If not, we uncharge res_counter ony by one.
  2280. */
  2281. if (batch->memcg != mem)
  2282. goto direct_uncharge;
  2283. /* remember freed charge and uncharge it later */
  2284. batch->bytes += PAGE_SIZE;
  2285. if (uncharge_memsw)
  2286. batch->memsw_bytes += PAGE_SIZE;
  2287. return;
  2288. direct_uncharge:
  2289. res_counter_uncharge(&mem->res, page_size);
  2290. if (uncharge_memsw)
  2291. res_counter_uncharge(&mem->memsw, page_size);
  2292. if (unlikely(batch->memcg != mem))
  2293. memcg_oom_recover(mem);
  2294. return;
  2295. }
  2296. /*
  2297. * uncharge if !page_mapped(page)
  2298. */
  2299. static struct mem_cgroup *
  2300. __mem_cgroup_uncharge_common(struct page *page, enum charge_type ctype)
  2301. {
  2302. int count;
  2303. struct page_cgroup *pc;
  2304. struct mem_cgroup *mem = NULL;
  2305. int page_size = PAGE_SIZE;
  2306. if (mem_cgroup_disabled())
  2307. return NULL;
  2308. if (PageSwapCache(page))
  2309. return NULL;
  2310. if (PageTransHuge(page)) {
  2311. page_size <<= compound_order(page);
  2312. VM_BUG_ON(!PageTransHuge(page));
  2313. }
  2314. count = page_size >> PAGE_SHIFT;
  2315. /*
  2316. * Check if our page_cgroup is valid
  2317. */
  2318. pc = lookup_page_cgroup(page);
  2319. if (unlikely(!pc || !PageCgroupUsed(pc)))
  2320. return NULL;
  2321. lock_page_cgroup(pc);
  2322. mem = pc->mem_cgroup;
  2323. if (!PageCgroupUsed(pc))
  2324. goto unlock_out;
  2325. switch (ctype) {
  2326. case MEM_CGROUP_CHARGE_TYPE_MAPPED:
  2327. case MEM_CGROUP_CHARGE_TYPE_DROP:
  2328. /* See mem_cgroup_prepare_migration() */
  2329. if (page_mapped(page) || PageCgroupMigration(pc))
  2330. goto unlock_out;
  2331. break;
  2332. case MEM_CGROUP_CHARGE_TYPE_SWAPOUT:
  2333. if (!PageAnon(page)) { /* Shared memory */
  2334. if (page->mapping && !page_is_file_cache(page))
  2335. goto unlock_out;
  2336. } else if (page_mapped(page)) /* Anon */
  2337. goto unlock_out;
  2338. break;
  2339. default:
  2340. break;
  2341. }
  2342. mem_cgroup_charge_statistics(mem, PageCgroupCache(pc), -count);
  2343. ClearPageCgroupUsed(pc);
  2344. /*
  2345. * pc->mem_cgroup is not cleared here. It will be accessed when it's
  2346. * freed from LRU. This is safe because uncharged page is expected not
  2347. * to be reused (freed soon). Exception is SwapCache, it's handled by
  2348. * special functions.
  2349. */
  2350. unlock_page_cgroup(pc);
  2351. /*
  2352. * even after unlock, we have mem->res.usage here and this memcg
  2353. * will never be freed.
  2354. */
  2355. memcg_check_events(mem, page);
  2356. if (do_swap_account && ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT) {
  2357. mem_cgroup_swap_statistics(mem, true);
  2358. mem_cgroup_get(mem);
  2359. }
  2360. if (!mem_cgroup_is_root(mem))
  2361. __do_uncharge(mem, ctype, page_size);
  2362. return mem;
  2363. unlock_out:
  2364. unlock_page_cgroup(pc);
  2365. return NULL;
  2366. }
  2367. void mem_cgroup_uncharge_page(struct page *page)
  2368. {
  2369. /* early check. */
  2370. if (page_mapped(page))
  2371. return;
  2372. if (page->mapping && !PageAnon(page))
  2373. return;
  2374. __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_MAPPED);
  2375. }
  2376. void mem_cgroup_uncharge_cache_page(struct page *page)
  2377. {
  2378. VM_BUG_ON(page_mapped(page));
  2379. VM_BUG_ON(page->mapping);
  2380. __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_CACHE);
  2381. }
  2382. /*
  2383. * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate.
  2384. * In that cases, pages are freed continuously and we can expect pages
  2385. * are in the same memcg. All these calls itself limits the number of
  2386. * pages freed at once, then uncharge_start/end() is called properly.
  2387. * This may be called prural(2) times in a context,
  2388. */
  2389. void mem_cgroup_uncharge_start(void)
  2390. {
  2391. current->memcg_batch.do_batch++;
  2392. /* We can do nest. */
  2393. if (current->memcg_batch.do_batch == 1) {
  2394. current->memcg_batch.memcg = NULL;
  2395. current->memcg_batch.bytes = 0;
  2396. current->memcg_batch.memsw_bytes = 0;
  2397. }
  2398. }
  2399. void mem_cgroup_uncharge_end(void)
  2400. {
  2401. struct memcg_batch_info *batch = &current->memcg_batch;
  2402. if (!batch->do_batch)
  2403. return;
  2404. batch->do_batch--;
  2405. if (batch->do_batch) /* If stacked, do nothing. */
  2406. return;
  2407. if (!batch->memcg)
  2408. return;
  2409. /*
  2410. * This "batch->memcg" is valid without any css_get/put etc...
  2411. * bacause we hide charges behind us.
  2412. */
  2413. if (batch->bytes)
  2414. res_counter_uncharge(&batch->memcg->res, batch->bytes);
  2415. if (batch->memsw_bytes)
  2416. res_counter_uncharge(&batch->memcg->memsw, batch->memsw_bytes);
  2417. memcg_oom_recover(batch->memcg);
  2418. /* forget this pointer (for sanity check) */
  2419. batch->memcg = NULL;
  2420. }
  2421. #ifdef CONFIG_SWAP
  2422. /*
  2423. * called after __delete_from_swap_cache() and drop "page" account.
  2424. * memcg information is recorded to swap_cgroup of "ent"
  2425. */
  2426. void
  2427. mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout)
  2428. {
  2429. struct mem_cgroup *memcg;
  2430. int ctype = MEM_CGROUP_CHARGE_TYPE_SWAPOUT;
  2431. if (!swapout) /* this was a swap cache but the swap is unused ! */
  2432. ctype = MEM_CGROUP_CHARGE_TYPE_DROP;
  2433. memcg = __mem_cgroup_uncharge_common(page, ctype);
  2434. /*
  2435. * record memcg information, if swapout && memcg != NULL,
  2436. * mem_cgroup_get() was called in uncharge().
  2437. */
  2438. if (do_swap_account && swapout && memcg)
  2439. swap_cgroup_record(ent, css_id(&memcg->css));
  2440. }
  2441. #endif
  2442. #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
  2443. /*
  2444. * called from swap_entry_free(). remove record in swap_cgroup and
  2445. * uncharge "memsw" account.
  2446. */
  2447. void mem_cgroup_uncharge_swap(swp_entry_t ent)
  2448. {
  2449. struct mem_cgroup *memcg;
  2450. unsigned short id;
  2451. if (!do_swap_account)
  2452. return;
  2453. id = swap_cgroup_record(ent, 0);
  2454. rcu_read_lock();
  2455. memcg = mem_cgroup_lookup(id);
  2456. if (memcg) {
  2457. /*
  2458. * We uncharge this because swap is freed.
  2459. * This memcg can be obsolete one. We avoid calling css_tryget
  2460. */
  2461. if (!mem_cgroup_is_root(memcg))
  2462. res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
  2463. mem_cgroup_swap_statistics(memcg, false);
  2464. mem_cgroup_put(memcg);
  2465. }
  2466. rcu_read_unlock();
  2467. }
  2468. /**
  2469. * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
  2470. * @entry: swap entry to be moved
  2471. * @from: mem_cgroup which the entry is moved from
  2472. * @to: mem_cgroup which the entry is moved to
  2473. * @need_fixup: whether we should fixup res_counters and refcounts.
  2474. *
  2475. * It succeeds only when the swap_cgroup's record for this entry is the same
  2476. * as the mem_cgroup's id of @from.
  2477. *
  2478. * Returns 0 on success, -EINVAL on failure.
  2479. *
  2480. * The caller must have charged to @to, IOW, called res_counter_charge() about
  2481. * both res and memsw, and called css_get().
  2482. */
  2483. static int mem_cgroup_move_swap_account(swp_entry_t entry,
  2484. struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
  2485. {
  2486. unsigned short old_id, new_id;
  2487. old_id = css_id(&from->css);
  2488. new_id = css_id(&to->css);
  2489. if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
  2490. mem_cgroup_swap_statistics(from, false);
  2491. mem_cgroup_swap_statistics(to, true);
  2492. /*
  2493. * This function is only called from task migration context now.
  2494. * It postpones res_counter and refcount handling till the end
  2495. * of task migration(mem_cgroup_clear_mc()) for performance
  2496. * improvement. But we cannot postpone mem_cgroup_get(to)
  2497. * because if the process that has been moved to @to does
  2498. * swap-in, the refcount of @to might be decreased to 0.
  2499. */
  2500. mem_cgroup_get(to);
  2501. if (need_fixup) {
  2502. if (!mem_cgroup_is_root(from))
  2503. res_counter_uncharge(&from->memsw, PAGE_SIZE);
  2504. mem_cgroup_put(from);
  2505. /*
  2506. * we charged both to->res and to->memsw, so we should
  2507. * uncharge to->res.
  2508. */
  2509. if (!mem_cgroup_is_root(to))
  2510. res_counter_uncharge(&to->res, PAGE_SIZE);
  2511. }
  2512. return 0;
  2513. }
  2514. return -EINVAL;
  2515. }
  2516. #else
  2517. static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
  2518. struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
  2519. {
  2520. return -EINVAL;
  2521. }
  2522. #endif
  2523. /*
  2524. * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
  2525. * page belongs to.
  2526. */
  2527. int mem_cgroup_prepare_migration(struct page *page,
  2528. struct page *newpage, struct mem_cgroup **ptr, gfp_t gfp_mask)
  2529. {
  2530. struct page_cgroup *pc;
  2531. struct mem_cgroup *mem = NULL;
  2532. enum charge_type ctype;
  2533. int ret = 0;
  2534. *ptr = NULL;
  2535. VM_BUG_ON(PageTransHuge(page));
  2536. if (mem_cgroup_disabled())
  2537. return 0;
  2538. pc = lookup_page_cgroup(page);
  2539. lock_page_cgroup(pc);
  2540. if (PageCgroupUsed(pc)) {
  2541. mem = pc->mem_cgroup;
  2542. css_get(&mem->css);
  2543. /*
  2544. * At migrating an anonymous page, its mapcount goes down
  2545. * to 0 and uncharge() will be called. But, even if it's fully
  2546. * unmapped, migration may fail and this page has to be
  2547. * charged again. We set MIGRATION flag here and delay uncharge
  2548. * until end_migration() is called
  2549. *
  2550. * Corner Case Thinking
  2551. * A)
  2552. * When the old page was mapped as Anon and it's unmap-and-freed
  2553. * while migration was ongoing.
  2554. * If unmap finds the old page, uncharge() of it will be delayed
  2555. * until end_migration(). If unmap finds a new page, it's
  2556. * uncharged when it make mapcount to be 1->0. If unmap code
  2557. * finds swap_migration_entry, the new page will not be mapped
  2558. * and end_migration() will find it(mapcount==0).
  2559. *
  2560. * B)
  2561. * When the old page was mapped but migraion fails, the kernel
  2562. * remaps it. A charge for it is kept by MIGRATION flag even
  2563. * if mapcount goes down to 0. We can do remap successfully
  2564. * without charging it again.
  2565. *
  2566. * C)
  2567. * The "old" page is under lock_page() until the end of
  2568. * migration, so, the old page itself will not be swapped-out.
  2569. * If the new page is swapped out before end_migraton, our
  2570. * hook to usual swap-out path will catch the event.
  2571. */
  2572. if (PageAnon(page))
  2573. SetPageCgroupMigration(pc);
  2574. }
  2575. unlock_page_cgroup(pc);
  2576. /*
  2577. * If the page is not charged at this point,
  2578. * we return here.
  2579. */
  2580. if (!mem)
  2581. return 0;
  2582. *ptr = mem;
  2583. ret = __mem_cgroup_try_charge(NULL, gfp_mask, ptr, false, PAGE_SIZE);
  2584. css_put(&mem->css);/* drop extra refcnt */
  2585. if (ret || *ptr == NULL) {
  2586. if (PageAnon(page)) {
  2587. lock_page_cgroup(pc);
  2588. ClearPageCgroupMigration(pc);
  2589. unlock_page_cgroup(pc);
  2590. /*
  2591. * The old page may be fully unmapped while we kept it.
  2592. */
  2593. mem_cgroup_uncharge_page(page);
  2594. }
  2595. return -ENOMEM;
  2596. }
  2597. /*
  2598. * We charge new page before it's used/mapped. So, even if unlock_page()
  2599. * is called before end_migration, we can catch all events on this new
  2600. * page. In the case new page is migrated but not remapped, new page's
  2601. * mapcount will be finally 0 and we call uncharge in end_migration().
  2602. */
  2603. pc = lookup_page_cgroup(newpage);
  2604. if (PageAnon(page))
  2605. ctype = MEM_CGROUP_CHARGE_TYPE_MAPPED;
  2606. else if (page_is_file_cache(page))
  2607. ctype = MEM_CGROUP_CHARGE_TYPE_CACHE;
  2608. else
  2609. ctype = MEM_CGROUP_CHARGE_TYPE_SHMEM;
  2610. __mem_cgroup_commit_charge(mem, page, pc, ctype, PAGE_SIZE);
  2611. return ret;
  2612. }
  2613. /* remove redundant charge if migration failed*/
  2614. void mem_cgroup_end_migration(struct mem_cgroup *mem,
  2615. struct page *oldpage, struct page *newpage, bool migration_ok)
  2616. {
  2617. struct page *used, *unused;
  2618. struct page_cgroup *pc;
  2619. if (!mem)
  2620. return;
  2621. /* blocks rmdir() */
  2622. cgroup_exclude_rmdir(&mem->css);
  2623. if (!migration_ok) {
  2624. used = oldpage;
  2625. unused = newpage;
  2626. } else {
  2627. used = newpage;
  2628. unused = oldpage;
  2629. }
  2630. /*
  2631. * We disallowed uncharge of pages under migration because mapcount
  2632. * of the page goes down to zero, temporarly.
  2633. * Clear the flag and check the page should be charged.
  2634. */
  2635. pc = lookup_page_cgroup(oldpage);
  2636. lock_page_cgroup(pc);
  2637. ClearPageCgroupMigration(pc);
  2638. unlock_page_cgroup(pc);
  2639. __mem_cgroup_uncharge_common(unused, MEM_CGROUP_CHARGE_TYPE_FORCE);
  2640. /*
  2641. * If a page is a file cache, radix-tree replacement is very atomic
  2642. * and we can skip this check. When it was an Anon page, its mapcount
  2643. * goes down to 0. But because we added MIGRATION flage, it's not
  2644. * uncharged yet. There are several case but page->mapcount check
  2645. * and USED bit check in mem_cgroup_uncharge_page() will do enough
  2646. * check. (see prepare_charge() also)
  2647. */
  2648. if (PageAnon(used))
  2649. mem_cgroup_uncharge_page(used);
  2650. /*
  2651. * At migration, we may charge account against cgroup which has no
  2652. * tasks.
  2653. * So, rmdir()->pre_destroy() can be called while we do this charge.
  2654. * In that case, we need to call pre_destroy() again. check it here.
  2655. */
  2656. cgroup_release_and_wakeup_rmdir(&mem->css);
  2657. }
  2658. /*
  2659. * A call to try to shrink memory usage on charge failure at shmem's swapin.
  2660. * Calling hierarchical_reclaim is not enough because we should update
  2661. * last_oom_jiffies to prevent pagefault_out_of_memory from invoking global OOM.
  2662. * Moreover considering hierarchy, we should reclaim from the mem_over_limit,
  2663. * not from the memcg which this page would be charged to.
  2664. * try_charge_swapin does all of these works properly.
  2665. */
  2666. int mem_cgroup_shmem_charge_fallback(struct page *page,
  2667. struct mm_struct *mm,
  2668. gfp_t gfp_mask)
  2669. {
  2670. struct mem_cgroup *mem;
  2671. int ret;
  2672. if (mem_cgroup_disabled())
  2673. return 0;
  2674. ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &mem);
  2675. if (!ret)
  2676. mem_cgroup_cancel_charge_swapin(mem); /* it does !mem check */
  2677. return ret;
  2678. }
  2679. #ifdef CONFIG_DEBUG_VM
  2680. static struct page_cgroup *lookup_page_cgroup_used(struct page *page)
  2681. {
  2682. struct page_cgroup *pc;
  2683. pc = lookup_page_cgroup(page);
  2684. if (likely(pc) && PageCgroupUsed(pc))
  2685. return pc;
  2686. return NULL;
  2687. }
  2688. bool mem_cgroup_bad_page_check(struct page *page)
  2689. {
  2690. if (mem_cgroup_disabled())
  2691. return false;
  2692. return lookup_page_cgroup_used(page) != NULL;
  2693. }
  2694. void mem_cgroup_print_bad_page(struct page *page)
  2695. {
  2696. struct page_cgroup *pc;
  2697. pc = lookup_page_cgroup_used(page);
  2698. if (pc) {
  2699. int ret = -1;
  2700. char *path;
  2701. printk(KERN_ALERT "pc:%p pc->flags:%lx pc->mem_cgroup:%p",
  2702. pc, pc->flags, pc->mem_cgroup);
  2703. path = kmalloc(PATH_MAX, GFP_KERNEL);
  2704. if (path) {
  2705. rcu_read_lock();
  2706. ret = cgroup_path(pc->mem_cgroup->css.cgroup,
  2707. path, PATH_MAX);
  2708. rcu_read_unlock();
  2709. }
  2710. printk(KERN_CONT "(%s)\n",
  2711. (ret < 0) ? "cannot get the path" : path);
  2712. kfree(path);
  2713. }
  2714. }
  2715. #endif
  2716. static DEFINE_MUTEX(set_limit_mutex);
  2717. static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
  2718. unsigned long long val)
  2719. {
  2720. int retry_count;
  2721. u64 memswlimit, memlimit;
  2722. int ret = 0;
  2723. int children = mem_cgroup_count_children(memcg);
  2724. u64 curusage, oldusage;
  2725. int enlarge;
  2726. /*
  2727. * For keeping hierarchical_reclaim simple, how long we should retry
  2728. * is depends on callers. We set our retry-count to be function
  2729. * of # of children which we should visit in this loop.
  2730. */
  2731. retry_count = MEM_CGROUP_RECLAIM_RETRIES * children;
  2732. oldusage = res_counter_read_u64(&memcg->res, RES_USAGE);
  2733. enlarge = 0;
  2734. while (retry_count) {
  2735. if (signal_pending(current)) {
  2736. ret = -EINTR;
  2737. break;
  2738. }
  2739. /*
  2740. * Rather than hide all in some function, I do this in
  2741. * open coded manner. You see what this really does.
  2742. * We have to guarantee mem->res.limit < mem->memsw.limit.
  2743. */
  2744. mutex_lock(&set_limit_mutex);
  2745. memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
  2746. if (memswlimit < val) {
  2747. ret = -EINVAL;
  2748. mutex_unlock(&set_limit_mutex);
  2749. break;
  2750. }
  2751. memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
  2752. if (memlimit < val)
  2753. enlarge = 1;
  2754. ret = res_counter_set_limit(&memcg->res, val);
  2755. if (!ret) {
  2756. if (memswlimit == val)
  2757. memcg->memsw_is_minimum = true;
  2758. else
  2759. memcg->memsw_is_minimum = false;
  2760. }
  2761. mutex_unlock(&set_limit_mutex);
  2762. if (!ret)
  2763. break;
  2764. mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
  2765. MEM_CGROUP_RECLAIM_SHRINK);
  2766. curusage = res_counter_read_u64(&memcg->res, RES_USAGE);
  2767. /* Usage is reduced ? */
  2768. if (curusage >= oldusage)
  2769. retry_count--;
  2770. else
  2771. oldusage = curusage;
  2772. }
  2773. if (!ret && enlarge)
  2774. memcg_oom_recover(memcg);
  2775. return ret;
  2776. }
  2777. static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
  2778. unsigned long long val)
  2779. {
  2780. int retry_count;
  2781. u64 memlimit, memswlimit, oldusage, curusage;
  2782. int children = mem_cgroup_count_children(memcg);
  2783. int ret = -EBUSY;
  2784. int enlarge = 0;
  2785. /* see mem_cgroup_resize_res_limit */
  2786. retry_count = children * MEM_CGROUP_RECLAIM_RETRIES;
  2787. oldusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
  2788. while (retry_count) {
  2789. if (signal_pending(current)) {
  2790. ret = -EINTR;
  2791. break;
  2792. }
  2793. /*
  2794. * Rather than hide all in some function, I do this in
  2795. * open coded manner. You see what this really does.
  2796. * We have to guarantee mem->res.limit < mem->memsw.limit.
  2797. */
  2798. mutex_lock(&set_limit_mutex);
  2799. memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
  2800. if (memlimit > val) {
  2801. ret = -EINVAL;
  2802. mutex_unlock(&set_limit_mutex);
  2803. break;
  2804. }
  2805. memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
  2806. if (memswlimit < val)
  2807. enlarge = 1;
  2808. ret = res_counter_set_limit(&memcg->memsw, val);
  2809. if (!ret) {
  2810. if (memlimit == val)
  2811. memcg->memsw_is_minimum = true;
  2812. else
  2813. memcg->memsw_is_minimum = false;
  2814. }
  2815. mutex_unlock(&set_limit_mutex);
  2816. if (!ret)
  2817. break;
  2818. mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
  2819. MEM_CGROUP_RECLAIM_NOSWAP |
  2820. MEM_CGROUP_RECLAIM_SHRINK);
  2821. curusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
  2822. /* Usage is reduced ? */
  2823. if (curusage >= oldusage)
  2824. retry_count--;
  2825. else
  2826. oldusage = curusage;
  2827. }
  2828. if (!ret && enlarge)
  2829. memcg_oom_recover(memcg);
  2830. return ret;
  2831. }
  2832. unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
  2833. gfp_t gfp_mask)
  2834. {
  2835. unsigned long nr_reclaimed = 0;
  2836. struct mem_cgroup_per_zone *mz, *next_mz = NULL;
  2837. unsigned long reclaimed;
  2838. int loop = 0;
  2839. struct mem_cgroup_tree_per_zone *mctz;
  2840. unsigned long long excess;
  2841. if (order > 0)
  2842. return 0;
  2843. mctz = soft_limit_tree_node_zone(zone_to_nid(zone), zone_idx(zone));
  2844. /*
  2845. * This loop can run a while, specially if mem_cgroup's continuously
  2846. * keep exceeding their soft limit and putting the system under
  2847. * pressure
  2848. */
  2849. do {
  2850. if (next_mz)
  2851. mz = next_mz;
  2852. else
  2853. mz = mem_cgroup_largest_soft_limit_node(mctz);
  2854. if (!mz)
  2855. break;
  2856. reclaimed = mem_cgroup_hierarchical_reclaim(mz->mem, zone,
  2857. gfp_mask,
  2858. MEM_CGROUP_RECLAIM_SOFT);
  2859. nr_reclaimed += reclaimed;
  2860. spin_lock(&mctz->lock);
  2861. /*
  2862. * If we failed to reclaim anything from this memory cgroup
  2863. * it is time to move on to the next cgroup
  2864. */
  2865. next_mz = NULL;
  2866. if (!reclaimed) {
  2867. do {
  2868. /*
  2869. * Loop until we find yet another one.
  2870. *
  2871. * By the time we get the soft_limit lock
  2872. * again, someone might have aded the
  2873. * group back on the RB tree. Iterate to
  2874. * make sure we get a different mem.
  2875. * mem_cgroup_largest_soft_limit_node returns
  2876. * NULL if no other cgroup is present on
  2877. * the tree
  2878. */
  2879. next_mz =
  2880. __mem_cgroup_largest_soft_limit_node(mctz);
  2881. if (next_mz == mz) {
  2882. css_put(&next_mz->mem->css);
  2883. next_mz = NULL;
  2884. } else /* next_mz == NULL or other memcg */
  2885. break;
  2886. } while (1);
  2887. }
  2888. __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
  2889. excess = res_counter_soft_limit_excess(&mz->mem->res);
  2890. /*
  2891. * One school of thought says that we should not add
  2892. * back the node to the tree if reclaim returns 0.
  2893. * But our reclaim could return 0, simply because due
  2894. * to priority we are exposing a smaller subset of
  2895. * memory to reclaim from. Consider this as a longer
  2896. * term TODO.
  2897. */
  2898. /* If excess == 0, no tree ops */
  2899. __mem_cgroup_insert_exceeded(mz->mem, mz, mctz, excess);
  2900. spin_unlock(&mctz->lock);
  2901. css_put(&mz->mem->css);
  2902. loop++;
  2903. /*
  2904. * Could not reclaim anything and there are no more
  2905. * mem cgroups to try or we seem to be looping without
  2906. * reclaiming anything.
  2907. */
  2908. if (!nr_reclaimed &&
  2909. (next_mz == NULL ||
  2910. loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
  2911. break;
  2912. } while (!nr_reclaimed);
  2913. if (next_mz)
  2914. css_put(&next_mz->mem->css);
  2915. return nr_reclaimed;
  2916. }
  2917. /*
  2918. * This routine traverse page_cgroup in given list and drop them all.
  2919. * *And* this routine doesn't reclaim page itself, just removes page_cgroup.
  2920. */
  2921. static int mem_cgroup_force_empty_list(struct mem_cgroup *mem,
  2922. int node, int zid, enum lru_list lru)
  2923. {
  2924. struct zone *zone;
  2925. struct mem_cgroup_per_zone *mz;
  2926. struct page_cgroup *pc, *busy;
  2927. unsigned long flags, loop;
  2928. struct list_head *list;
  2929. int ret = 0;
  2930. zone = &NODE_DATA(node)->node_zones[zid];
  2931. mz = mem_cgroup_zoneinfo(mem, node, zid);
  2932. list = &mz->lists[lru];
  2933. loop = MEM_CGROUP_ZSTAT(mz, lru);
  2934. /* give some margin against EBUSY etc...*/
  2935. loop += 256;
  2936. busy = NULL;
  2937. while (loop--) {
  2938. struct page *page;
  2939. ret = 0;
  2940. spin_lock_irqsave(&zone->lru_lock, flags);
  2941. if (list_empty(list)) {
  2942. spin_unlock_irqrestore(&zone->lru_lock, flags);
  2943. break;
  2944. }
  2945. pc = list_entry(list->prev, struct page_cgroup, lru);
  2946. if (busy == pc) {
  2947. list_move(&pc->lru, list);
  2948. busy = NULL;
  2949. spin_unlock_irqrestore(&zone->lru_lock, flags);
  2950. continue;
  2951. }
  2952. spin_unlock_irqrestore(&zone->lru_lock, flags);
  2953. page = pc->page;
  2954. ret = mem_cgroup_move_parent(page, pc, mem, GFP_KERNEL);
  2955. if (ret == -ENOMEM)
  2956. break;
  2957. if (ret == -EBUSY || ret == -EINVAL) {
  2958. /* found lock contention or "pc" is obsolete. */
  2959. busy = pc;
  2960. cond_resched();
  2961. } else
  2962. busy = NULL;
  2963. }
  2964. if (!ret && !list_empty(list))
  2965. return -EBUSY;
  2966. return ret;
  2967. }
  2968. /*
  2969. * make mem_cgroup's charge to be 0 if there is no task.
  2970. * This enables deleting this mem_cgroup.
  2971. */
  2972. static int mem_cgroup_force_empty(struct mem_cgroup *mem, bool free_all)
  2973. {
  2974. int ret;
  2975. int node, zid, shrink;
  2976. int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
  2977. struct cgroup *cgrp = mem->css.cgroup;
  2978. css_get(&mem->css);
  2979. shrink = 0;
  2980. /* should free all ? */
  2981. if (free_all)
  2982. goto try_to_free;
  2983. move_account:
  2984. do {
  2985. ret = -EBUSY;
  2986. if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children))
  2987. goto out;
  2988. ret = -EINTR;
  2989. if (signal_pending(current))
  2990. goto out;
  2991. /* This is for making all *used* pages to be on LRU. */
  2992. lru_add_drain_all();
  2993. drain_all_stock_sync();
  2994. ret = 0;
  2995. mem_cgroup_start_move(mem);
  2996. for_each_node_state(node, N_HIGH_MEMORY) {
  2997. for (zid = 0; !ret && zid < MAX_NR_ZONES; zid++) {
  2998. enum lru_list l;
  2999. for_each_lru(l) {
  3000. ret = mem_cgroup_force_empty_list(mem,
  3001. node, zid, l);
  3002. if (ret)
  3003. break;
  3004. }
  3005. }
  3006. if (ret)
  3007. break;
  3008. }
  3009. mem_cgroup_end_move(mem);
  3010. memcg_oom_recover(mem);
  3011. /* it seems parent cgroup doesn't have enough mem */
  3012. if (ret == -ENOMEM)
  3013. goto try_to_free;
  3014. cond_resched();
  3015. /* "ret" should also be checked to ensure all lists are empty. */
  3016. } while (mem->res.usage > 0 || ret);
  3017. out:
  3018. css_put(&mem->css);
  3019. return ret;
  3020. try_to_free:
  3021. /* returns EBUSY if there is a task or if we come here twice. */
  3022. if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children) || shrink) {
  3023. ret = -EBUSY;
  3024. goto out;
  3025. }
  3026. /* we call try-to-free pages for make this cgroup empty */
  3027. lru_add_drain_all();
  3028. /* try to free all pages in this cgroup */
  3029. shrink = 1;
  3030. while (nr_retries && mem->res.usage > 0) {
  3031. int progress;
  3032. if (signal_pending(current)) {
  3033. ret = -EINTR;
  3034. goto out;
  3035. }
  3036. progress = try_to_free_mem_cgroup_pages(mem, GFP_KERNEL,
  3037. false, get_swappiness(mem));
  3038. if (!progress) {
  3039. nr_retries--;
  3040. /* maybe some writeback is necessary */
  3041. congestion_wait(BLK_RW_ASYNC, HZ/10);
  3042. }
  3043. }
  3044. lru_add_drain();
  3045. /* try move_account...there may be some *locked* pages. */
  3046. goto move_account;
  3047. }
  3048. int mem_cgroup_force_empty_write(struct cgroup *cont, unsigned int event)
  3049. {
  3050. return mem_cgroup_force_empty(mem_cgroup_from_cont(cont), true);
  3051. }
  3052. static u64 mem_cgroup_hierarchy_read(struct cgroup *cont, struct cftype *cft)
  3053. {
  3054. return mem_cgroup_from_cont(cont)->use_hierarchy;
  3055. }
  3056. static int mem_cgroup_hierarchy_write(struct cgroup *cont, struct cftype *cft,
  3057. u64 val)
  3058. {
  3059. int retval = 0;
  3060. struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
  3061. struct cgroup *parent = cont->parent;
  3062. struct mem_cgroup *parent_mem = NULL;
  3063. if (parent)
  3064. parent_mem = mem_cgroup_from_cont(parent);
  3065. cgroup_lock();
  3066. /*
  3067. * If parent's use_hierarchy is set, we can't make any modifications
  3068. * in the child subtrees. If it is unset, then the change can
  3069. * occur, provided the current cgroup has no children.
  3070. *
  3071. * For the root cgroup, parent_mem is NULL, we allow value to be
  3072. * set if there are no children.
  3073. */
  3074. if ((!parent_mem || !parent_mem->use_hierarchy) &&
  3075. (val == 1 || val == 0)) {
  3076. if (list_empty(&cont->children))
  3077. mem->use_hierarchy = val;
  3078. else
  3079. retval = -EBUSY;
  3080. } else
  3081. retval = -EINVAL;
  3082. cgroup_unlock();
  3083. return retval;
  3084. }
  3085. static u64 mem_cgroup_get_recursive_idx_stat(struct mem_cgroup *mem,
  3086. enum mem_cgroup_stat_index idx)
  3087. {
  3088. struct mem_cgroup *iter;
  3089. s64 val = 0;
  3090. /* each per cpu's value can be minus.Then, use s64 */
  3091. for_each_mem_cgroup_tree(iter, mem)
  3092. val += mem_cgroup_read_stat(iter, idx);
  3093. if (val < 0) /* race ? */
  3094. val = 0;
  3095. return val;
  3096. }
  3097. static inline u64 mem_cgroup_usage(struct mem_cgroup *mem, bool swap)
  3098. {
  3099. u64 val;
  3100. if (!mem_cgroup_is_root(mem)) {
  3101. if (!swap)
  3102. return res_counter_read_u64(&mem->res, RES_USAGE);
  3103. else
  3104. return res_counter_read_u64(&mem->memsw, RES_USAGE);
  3105. }
  3106. val = mem_cgroup_get_recursive_idx_stat(mem, MEM_CGROUP_STAT_CACHE);
  3107. val += mem_cgroup_get_recursive_idx_stat(mem, MEM_CGROUP_STAT_RSS);
  3108. if (swap)
  3109. val += mem_cgroup_get_recursive_idx_stat(mem,
  3110. MEM_CGROUP_STAT_SWAPOUT);
  3111. return val << PAGE_SHIFT;
  3112. }
  3113. static u64 mem_cgroup_read(struct cgroup *cont, struct cftype *cft)
  3114. {
  3115. struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
  3116. u64 val;
  3117. int type, name;
  3118. type = MEMFILE_TYPE(cft->private);
  3119. name = MEMFILE_ATTR(cft->private);
  3120. switch (type) {
  3121. case _MEM:
  3122. if (name == RES_USAGE)
  3123. val = mem_cgroup_usage(mem, false);
  3124. else
  3125. val = res_counter_read_u64(&mem->res, name);
  3126. break;
  3127. case _MEMSWAP:
  3128. if (name == RES_USAGE)
  3129. val = mem_cgroup_usage(mem, true);
  3130. else
  3131. val = res_counter_read_u64(&mem->memsw, name);
  3132. break;
  3133. default:
  3134. BUG();
  3135. break;
  3136. }
  3137. return val;
  3138. }
  3139. /*
  3140. * The user of this function is...
  3141. * RES_LIMIT.
  3142. */
  3143. static int mem_cgroup_write(struct cgroup *cont, struct cftype *cft,
  3144. const char *buffer)
  3145. {
  3146. struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
  3147. int type, name;
  3148. unsigned long long val;
  3149. int ret;
  3150. type = MEMFILE_TYPE(cft->private);
  3151. name = MEMFILE_ATTR(cft->private);
  3152. switch (name) {
  3153. case RES_LIMIT:
  3154. if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
  3155. ret = -EINVAL;
  3156. break;
  3157. }
  3158. /* This function does all necessary parse...reuse it */
  3159. ret = res_counter_memparse_write_strategy(buffer, &val);
  3160. if (ret)
  3161. break;
  3162. if (type == _MEM)
  3163. ret = mem_cgroup_resize_limit(memcg, val);
  3164. else
  3165. ret = mem_cgroup_resize_memsw_limit(memcg, val);
  3166. break;
  3167. case RES_SOFT_LIMIT:
  3168. ret = res_counter_memparse_write_strategy(buffer, &val);
  3169. if (ret)
  3170. break;
  3171. /*
  3172. * For memsw, soft limits are hard to implement in terms
  3173. * of semantics, for now, we support soft limits for
  3174. * control without swap
  3175. */
  3176. if (type == _MEM)
  3177. ret = res_counter_set_soft_limit(&memcg->res, val);
  3178. else
  3179. ret = -EINVAL;
  3180. break;
  3181. default:
  3182. ret = -EINVAL; /* should be BUG() ? */
  3183. break;
  3184. }
  3185. return ret;
  3186. }
  3187. static void memcg_get_hierarchical_limit(struct mem_cgroup *memcg,
  3188. unsigned long long *mem_limit, unsigned long long *memsw_limit)
  3189. {
  3190. struct cgroup *cgroup;
  3191. unsigned long long min_limit, min_memsw_limit, tmp;
  3192. min_limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
  3193. min_memsw_limit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
  3194. cgroup = memcg->css.cgroup;
  3195. if (!memcg->use_hierarchy)
  3196. goto out;
  3197. while (cgroup->parent) {
  3198. cgroup = cgroup->parent;
  3199. memcg = mem_cgroup_from_cont(cgroup);
  3200. if (!memcg->use_hierarchy)
  3201. break;
  3202. tmp = res_counter_read_u64(&memcg->res, RES_LIMIT);
  3203. min_limit = min(min_limit, tmp);
  3204. tmp = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
  3205. min_memsw_limit = min(min_memsw_limit, tmp);
  3206. }
  3207. out:
  3208. *mem_limit = min_limit;
  3209. *memsw_limit = min_memsw_limit;
  3210. return;
  3211. }
  3212. static int mem_cgroup_reset(struct cgroup *cont, unsigned int event)
  3213. {
  3214. struct mem_cgroup *mem;
  3215. int type, name;
  3216. mem = mem_cgroup_from_cont(cont);
  3217. type = MEMFILE_TYPE(event);
  3218. name = MEMFILE_ATTR(event);
  3219. switch (name) {
  3220. case RES_MAX_USAGE:
  3221. if (type == _MEM)
  3222. res_counter_reset_max(&mem->res);
  3223. else
  3224. res_counter_reset_max(&mem->memsw);
  3225. break;
  3226. case RES_FAILCNT:
  3227. if (type == _MEM)
  3228. res_counter_reset_failcnt(&mem->res);
  3229. else
  3230. res_counter_reset_failcnt(&mem->memsw);
  3231. break;
  3232. }
  3233. return 0;
  3234. }
  3235. static u64 mem_cgroup_move_charge_read(struct cgroup *cgrp,
  3236. struct cftype *cft)
  3237. {
  3238. return mem_cgroup_from_cont(cgrp)->move_charge_at_immigrate;
  3239. }
  3240. #ifdef CONFIG_MMU
  3241. static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
  3242. struct cftype *cft, u64 val)
  3243. {
  3244. struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
  3245. if (val >= (1 << NR_MOVE_TYPE))
  3246. return -EINVAL;
  3247. /*
  3248. * We check this value several times in both in can_attach() and
  3249. * attach(), so we need cgroup lock to prevent this value from being
  3250. * inconsistent.
  3251. */
  3252. cgroup_lock();
  3253. mem->move_charge_at_immigrate = val;
  3254. cgroup_unlock();
  3255. return 0;
  3256. }
  3257. #else
  3258. static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
  3259. struct cftype *cft, u64 val)
  3260. {
  3261. return -ENOSYS;
  3262. }
  3263. #endif
  3264. /* For read statistics */
  3265. enum {
  3266. MCS_CACHE,
  3267. MCS_RSS,
  3268. MCS_FILE_MAPPED,
  3269. MCS_PGPGIN,
  3270. MCS_PGPGOUT,
  3271. MCS_SWAP,
  3272. MCS_INACTIVE_ANON,
  3273. MCS_ACTIVE_ANON,
  3274. MCS_INACTIVE_FILE,
  3275. MCS_ACTIVE_FILE,
  3276. MCS_UNEVICTABLE,
  3277. NR_MCS_STAT,
  3278. };
  3279. struct mcs_total_stat {
  3280. s64 stat[NR_MCS_STAT];
  3281. };
  3282. struct {
  3283. char *local_name;
  3284. char *total_name;
  3285. } memcg_stat_strings[NR_MCS_STAT] = {
  3286. {"cache", "total_cache"},
  3287. {"rss", "total_rss"},
  3288. {"mapped_file", "total_mapped_file"},
  3289. {"pgpgin", "total_pgpgin"},
  3290. {"pgpgout", "total_pgpgout"},
  3291. {"swap", "total_swap"},
  3292. {"inactive_anon", "total_inactive_anon"},
  3293. {"active_anon", "total_active_anon"},
  3294. {"inactive_file", "total_inactive_file"},
  3295. {"active_file", "total_active_file"},
  3296. {"unevictable", "total_unevictable"}
  3297. };
  3298. static void
  3299. mem_cgroup_get_local_stat(struct mem_cgroup *mem, struct mcs_total_stat *s)
  3300. {
  3301. s64 val;
  3302. /* per cpu stat */
  3303. val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_CACHE);
  3304. s->stat[MCS_CACHE] += val * PAGE_SIZE;
  3305. val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_RSS);
  3306. s->stat[MCS_RSS] += val * PAGE_SIZE;
  3307. val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_FILE_MAPPED);
  3308. s->stat[MCS_FILE_MAPPED] += val * PAGE_SIZE;
  3309. val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_PGPGIN_COUNT);
  3310. s->stat[MCS_PGPGIN] += val;
  3311. val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_PGPGOUT_COUNT);
  3312. s->stat[MCS_PGPGOUT] += val;
  3313. if (do_swap_account) {
  3314. val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_SWAPOUT);
  3315. s->stat[MCS_SWAP] += val * PAGE_SIZE;
  3316. }
  3317. /* per zone stat */
  3318. val = mem_cgroup_get_local_zonestat(mem, LRU_INACTIVE_ANON);
  3319. s->stat[MCS_INACTIVE_ANON] += val * PAGE_SIZE;
  3320. val = mem_cgroup_get_local_zonestat(mem, LRU_ACTIVE_ANON);
  3321. s->stat[MCS_ACTIVE_ANON] += val * PAGE_SIZE;
  3322. val = mem_cgroup_get_local_zonestat(mem, LRU_INACTIVE_FILE);
  3323. s->stat[MCS_INACTIVE_FILE] += val * PAGE_SIZE;
  3324. val = mem_cgroup_get_local_zonestat(mem, LRU_ACTIVE_FILE);
  3325. s->stat[MCS_ACTIVE_FILE] += val * PAGE_SIZE;
  3326. val = mem_cgroup_get_local_zonestat(mem, LRU_UNEVICTABLE);
  3327. s->stat[MCS_UNEVICTABLE] += val * PAGE_SIZE;
  3328. }
  3329. static void
  3330. mem_cgroup_get_total_stat(struct mem_cgroup *mem, struct mcs_total_stat *s)
  3331. {
  3332. struct mem_cgroup *iter;
  3333. for_each_mem_cgroup_tree(iter, mem)
  3334. mem_cgroup_get_local_stat(iter, s);
  3335. }
  3336. static int mem_control_stat_show(struct cgroup *cont, struct cftype *cft,
  3337. struct cgroup_map_cb *cb)
  3338. {
  3339. struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
  3340. struct mcs_total_stat mystat;
  3341. int i;
  3342. memset(&mystat, 0, sizeof(mystat));
  3343. mem_cgroup_get_local_stat(mem_cont, &mystat);
  3344. for (i = 0; i < NR_MCS_STAT; i++) {
  3345. if (i == MCS_SWAP && !do_swap_account)
  3346. continue;
  3347. cb->fill(cb, memcg_stat_strings[i].local_name, mystat.stat[i]);
  3348. }
  3349. /* Hierarchical information */
  3350. {
  3351. unsigned long long limit, memsw_limit;
  3352. memcg_get_hierarchical_limit(mem_cont, &limit, &memsw_limit);
  3353. cb->fill(cb, "hierarchical_memory_limit", limit);
  3354. if (do_swap_account)
  3355. cb->fill(cb, "hierarchical_memsw_limit", memsw_limit);
  3356. }
  3357. memset(&mystat, 0, sizeof(mystat));
  3358. mem_cgroup_get_total_stat(mem_cont, &mystat);
  3359. for (i = 0; i < NR_MCS_STAT; i++) {
  3360. if (i == MCS_SWAP && !do_swap_account)
  3361. continue;
  3362. cb->fill(cb, memcg_stat_strings[i].total_name, mystat.stat[i]);
  3363. }
  3364. #ifdef CONFIG_DEBUG_VM
  3365. cb->fill(cb, "inactive_ratio", calc_inactive_ratio(mem_cont, NULL));
  3366. {
  3367. int nid, zid;
  3368. struct mem_cgroup_per_zone *mz;
  3369. unsigned long recent_rotated[2] = {0, 0};
  3370. unsigned long recent_scanned[2] = {0, 0};
  3371. for_each_online_node(nid)
  3372. for (zid = 0; zid < MAX_NR_ZONES; zid++) {
  3373. mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
  3374. recent_rotated[0] +=
  3375. mz->reclaim_stat.recent_rotated[0];
  3376. recent_rotated[1] +=
  3377. mz->reclaim_stat.recent_rotated[1];
  3378. recent_scanned[0] +=
  3379. mz->reclaim_stat.recent_scanned[0];
  3380. recent_scanned[1] +=
  3381. mz->reclaim_stat.recent_scanned[1];
  3382. }
  3383. cb->fill(cb, "recent_rotated_anon", recent_rotated[0]);
  3384. cb->fill(cb, "recent_rotated_file", recent_rotated[1]);
  3385. cb->fill(cb, "recent_scanned_anon", recent_scanned[0]);
  3386. cb->fill(cb, "recent_scanned_file", recent_scanned[1]);
  3387. }
  3388. #endif
  3389. return 0;
  3390. }
  3391. static u64 mem_cgroup_swappiness_read(struct cgroup *cgrp, struct cftype *cft)
  3392. {
  3393. struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
  3394. return get_swappiness(memcg);
  3395. }
  3396. static int mem_cgroup_swappiness_write(struct cgroup *cgrp, struct cftype *cft,
  3397. u64 val)
  3398. {
  3399. struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
  3400. struct mem_cgroup *parent;
  3401. if (val > 100)
  3402. return -EINVAL;
  3403. if (cgrp->parent == NULL)
  3404. return -EINVAL;
  3405. parent = mem_cgroup_from_cont(cgrp->parent);
  3406. cgroup_lock();
  3407. /* If under hierarchy, only empty-root can set this value */
  3408. if ((parent->use_hierarchy) ||
  3409. (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
  3410. cgroup_unlock();
  3411. return -EINVAL;
  3412. }
  3413. spin_lock(&memcg->reclaim_param_lock);
  3414. memcg->swappiness = val;
  3415. spin_unlock(&memcg->reclaim_param_lock);
  3416. cgroup_unlock();
  3417. return 0;
  3418. }
  3419. static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
  3420. {
  3421. struct mem_cgroup_threshold_ary *t;
  3422. u64 usage;
  3423. int i;
  3424. rcu_read_lock();
  3425. if (!swap)
  3426. t = rcu_dereference(memcg->thresholds.primary);
  3427. else
  3428. t = rcu_dereference(memcg->memsw_thresholds.primary);
  3429. if (!t)
  3430. goto unlock;
  3431. usage = mem_cgroup_usage(memcg, swap);
  3432. /*
  3433. * current_threshold points to threshold just below usage.
  3434. * If it's not true, a threshold was crossed after last
  3435. * call of __mem_cgroup_threshold().
  3436. */
  3437. i = t->current_threshold;
  3438. /*
  3439. * Iterate backward over array of thresholds starting from
  3440. * current_threshold and check if a threshold is crossed.
  3441. * If none of thresholds below usage is crossed, we read
  3442. * only one element of the array here.
  3443. */
  3444. for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
  3445. eventfd_signal(t->entries[i].eventfd, 1);
  3446. /* i = current_threshold + 1 */
  3447. i++;
  3448. /*
  3449. * Iterate forward over array of thresholds starting from
  3450. * current_threshold+1 and check if a threshold is crossed.
  3451. * If none of thresholds above usage is crossed, we read
  3452. * only one element of the array here.
  3453. */
  3454. for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
  3455. eventfd_signal(t->entries[i].eventfd, 1);
  3456. /* Update current_threshold */
  3457. t->current_threshold = i - 1;
  3458. unlock:
  3459. rcu_read_unlock();
  3460. }
  3461. static void mem_cgroup_threshold(struct mem_cgroup *memcg)
  3462. {
  3463. while (memcg) {
  3464. __mem_cgroup_threshold(memcg, false);
  3465. if (do_swap_account)
  3466. __mem_cgroup_threshold(memcg, true);
  3467. memcg = parent_mem_cgroup(memcg);
  3468. }
  3469. }
  3470. static int compare_thresholds(const void *a, const void *b)
  3471. {
  3472. const struct mem_cgroup_threshold *_a = a;
  3473. const struct mem_cgroup_threshold *_b = b;
  3474. return _a->threshold - _b->threshold;
  3475. }
  3476. static int mem_cgroup_oom_notify_cb(struct mem_cgroup *mem)
  3477. {
  3478. struct mem_cgroup_eventfd_list *ev;
  3479. list_for_each_entry(ev, &mem->oom_notify, list)
  3480. eventfd_signal(ev->eventfd, 1);
  3481. return 0;
  3482. }
  3483. static void mem_cgroup_oom_notify(struct mem_cgroup *mem)
  3484. {
  3485. struct mem_cgroup *iter;
  3486. for_each_mem_cgroup_tree(iter, mem)
  3487. mem_cgroup_oom_notify_cb(iter);
  3488. }
  3489. static int mem_cgroup_usage_register_event(struct cgroup *cgrp,
  3490. struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
  3491. {
  3492. struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
  3493. struct mem_cgroup_thresholds *thresholds;
  3494. struct mem_cgroup_threshold_ary *new;
  3495. int type = MEMFILE_TYPE(cft->private);
  3496. u64 threshold, usage;
  3497. int i, size, ret;
  3498. ret = res_counter_memparse_write_strategy(args, &threshold);
  3499. if (ret)
  3500. return ret;
  3501. mutex_lock(&memcg->thresholds_lock);
  3502. if (type == _MEM)
  3503. thresholds = &memcg->thresholds;
  3504. else if (type == _MEMSWAP)
  3505. thresholds = &memcg->memsw_thresholds;
  3506. else
  3507. BUG();
  3508. usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
  3509. /* Check if a threshold crossed before adding a new one */
  3510. if (thresholds->primary)
  3511. __mem_cgroup_threshold(memcg, type == _MEMSWAP);
  3512. size = thresholds->primary ? thresholds->primary->size + 1 : 1;
  3513. /* Allocate memory for new array of thresholds */
  3514. new = kmalloc(sizeof(*new) + size * sizeof(struct mem_cgroup_threshold),
  3515. GFP_KERNEL);
  3516. if (!new) {
  3517. ret = -ENOMEM;
  3518. goto unlock;
  3519. }
  3520. new->size = size;
  3521. /* Copy thresholds (if any) to new array */
  3522. if (thresholds->primary) {
  3523. memcpy(new->entries, thresholds->primary->entries, (size - 1) *
  3524. sizeof(struct mem_cgroup_threshold));
  3525. }
  3526. /* Add new threshold */
  3527. new->entries[size - 1].eventfd = eventfd;
  3528. new->entries[size - 1].threshold = threshold;
  3529. /* Sort thresholds. Registering of new threshold isn't time-critical */
  3530. sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
  3531. compare_thresholds, NULL);
  3532. /* Find current threshold */
  3533. new->current_threshold = -1;
  3534. for (i = 0; i < size; i++) {
  3535. if (new->entries[i].threshold < usage) {
  3536. /*
  3537. * new->current_threshold will not be used until
  3538. * rcu_assign_pointer(), so it's safe to increment
  3539. * it here.
  3540. */
  3541. ++new->current_threshold;
  3542. }
  3543. }
  3544. /* Free old spare buffer and save old primary buffer as spare */
  3545. kfree(thresholds->spare);
  3546. thresholds->spare = thresholds->primary;
  3547. rcu_assign_pointer(thresholds->primary, new);
  3548. /* To be sure that nobody uses thresholds */
  3549. synchronize_rcu();
  3550. unlock:
  3551. mutex_unlock(&memcg->thresholds_lock);
  3552. return ret;
  3553. }
  3554. static void mem_cgroup_usage_unregister_event(struct cgroup *cgrp,
  3555. struct cftype *cft, struct eventfd_ctx *eventfd)
  3556. {
  3557. struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
  3558. struct mem_cgroup_thresholds *thresholds;
  3559. struct mem_cgroup_threshold_ary *new;
  3560. int type = MEMFILE_TYPE(cft->private);
  3561. u64 usage;
  3562. int i, j, size;
  3563. mutex_lock(&memcg->thresholds_lock);
  3564. if (type == _MEM)
  3565. thresholds = &memcg->thresholds;
  3566. else if (type == _MEMSWAP)
  3567. thresholds = &memcg->memsw_thresholds;
  3568. else
  3569. BUG();
  3570. /*
  3571. * Something went wrong if we trying to unregister a threshold
  3572. * if we don't have thresholds
  3573. */
  3574. BUG_ON(!thresholds);
  3575. usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
  3576. /* Check if a threshold crossed before removing */
  3577. __mem_cgroup_threshold(memcg, type == _MEMSWAP);
  3578. /* Calculate new number of threshold */
  3579. size = 0;
  3580. for (i = 0; i < thresholds->primary->size; i++) {
  3581. if (thresholds->primary->entries[i].eventfd != eventfd)
  3582. size++;
  3583. }
  3584. new = thresholds->spare;
  3585. /* Set thresholds array to NULL if we don't have thresholds */
  3586. if (!size) {
  3587. kfree(new);
  3588. new = NULL;
  3589. goto swap_buffers;
  3590. }
  3591. new->size = size;
  3592. /* Copy thresholds and find current threshold */
  3593. new->current_threshold = -1;
  3594. for (i = 0, j = 0; i < thresholds->primary->size; i++) {
  3595. if (thresholds->primary->entries[i].eventfd == eventfd)
  3596. continue;
  3597. new->entries[j] = thresholds->primary->entries[i];
  3598. if (new->entries[j].threshold < usage) {
  3599. /*
  3600. * new->current_threshold will not be used
  3601. * until rcu_assign_pointer(), so it's safe to increment
  3602. * it here.
  3603. */
  3604. ++new->current_threshold;
  3605. }
  3606. j++;
  3607. }
  3608. swap_buffers:
  3609. /* Swap primary and spare array */
  3610. thresholds->spare = thresholds->primary;
  3611. rcu_assign_pointer(thresholds->primary, new);
  3612. /* To be sure that nobody uses thresholds */
  3613. synchronize_rcu();
  3614. mutex_unlock(&memcg->thresholds_lock);
  3615. }
  3616. static int mem_cgroup_oom_register_event(struct cgroup *cgrp,
  3617. struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
  3618. {
  3619. struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
  3620. struct mem_cgroup_eventfd_list *event;
  3621. int type = MEMFILE_TYPE(cft->private);
  3622. BUG_ON(type != _OOM_TYPE);
  3623. event = kmalloc(sizeof(*event), GFP_KERNEL);
  3624. if (!event)
  3625. return -ENOMEM;
  3626. mutex_lock(&memcg_oom_mutex);
  3627. event->eventfd = eventfd;
  3628. list_add(&event->list, &memcg->oom_notify);
  3629. /* already in OOM ? */
  3630. if (atomic_read(&memcg->oom_lock))
  3631. eventfd_signal(eventfd, 1);
  3632. mutex_unlock(&memcg_oom_mutex);
  3633. return 0;
  3634. }
  3635. static void mem_cgroup_oom_unregister_event(struct cgroup *cgrp,
  3636. struct cftype *cft, struct eventfd_ctx *eventfd)
  3637. {
  3638. struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
  3639. struct mem_cgroup_eventfd_list *ev, *tmp;
  3640. int type = MEMFILE_TYPE(cft->private);
  3641. BUG_ON(type != _OOM_TYPE);
  3642. mutex_lock(&memcg_oom_mutex);
  3643. list_for_each_entry_safe(ev, tmp, &mem->oom_notify, list) {
  3644. if (ev->eventfd == eventfd) {
  3645. list_del(&ev->list);
  3646. kfree(ev);
  3647. }
  3648. }
  3649. mutex_unlock(&memcg_oom_mutex);
  3650. }
  3651. static int mem_cgroup_oom_control_read(struct cgroup *cgrp,
  3652. struct cftype *cft, struct cgroup_map_cb *cb)
  3653. {
  3654. struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
  3655. cb->fill(cb, "oom_kill_disable", mem->oom_kill_disable);
  3656. if (atomic_read(&mem->oom_lock))
  3657. cb->fill(cb, "under_oom", 1);
  3658. else
  3659. cb->fill(cb, "under_oom", 0);
  3660. return 0;
  3661. }
  3662. static int mem_cgroup_oom_control_write(struct cgroup *cgrp,
  3663. struct cftype *cft, u64 val)
  3664. {
  3665. struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
  3666. struct mem_cgroup *parent;
  3667. /* cannot set to root cgroup and only 0 and 1 are allowed */
  3668. if (!cgrp->parent || !((val == 0) || (val == 1)))
  3669. return -EINVAL;
  3670. parent = mem_cgroup_from_cont(cgrp->parent);
  3671. cgroup_lock();
  3672. /* oom-kill-disable is a flag for subhierarchy. */
  3673. if ((parent->use_hierarchy) ||
  3674. (mem->use_hierarchy && !list_empty(&cgrp->children))) {
  3675. cgroup_unlock();
  3676. return -EINVAL;
  3677. }
  3678. mem->oom_kill_disable = val;
  3679. if (!val)
  3680. memcg_oom_recover(mem);
  3681. cgroup_unlock();
  3682. return 0;
  3683. }
  3684. static struct cftype mem_cgroup_files[] = {
  3685. {
  3686. .name = "usage_in_bytes",
  3687. .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
  3688. .read_u64 = mem_cgroup_read,
  3689. .register_event = mem_cgroup_usage_register_event,
  3690. .unregister_event = mem_cgroup_usage_unregister_event,
  3691. },
  3692. {
  3693. .name = "max_usage_in_bytes",
  3694. .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
  3695. .trigger = mem_cgroup_reset,
  3696. .read_u64 = mem_cgroup_read,
  3697. },
  3698. {
  3699. .name = "limit_in_bytes",
  3700. .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
  3701. .write_string = mem_cgroup_write,
  3702. .read_u64 = mem_cgroup_read,
  3703. },
  3704. {
  3705. .name = "soft_limit_in_bytes",
  3706. .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
  3707. .write_string = mem_cgroup_write,
  3708. .read_u64 = mem_cgroup_read,
  3709. },
  3710. {
  3711. .name = "failcnt",
  3712. .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
  3713. .trigger = mem_cgroup_reset,
  3714. .read_u64 = mem_cgroup_read,
  3715. },
  3716. {
  3717. .name = "stat",
  3718. .read_map = mem_control_stat_show,
  3719. },
  3720. {
  3721. .name = "force_empty",
  3722. .trigger = mem_cgroup_force_empty_write,
  3723. },
  3724. {
  3725. .name = "use_hierarchy",
  3726. .write_u64 = mem_cgroup_hierarchy_write,
  3727. .read_u64 = mem_cgroup_hierarchy_read,
  3728. },
  3729. {
  3730. .name = "swappiness",
  3731. .read_u64 = mem_cgroup_swappiness_read,
  3732. .write_u64 = mem_cgroup_swappiness_write,
  3733. },
  3734. {
  3735. .name = "move_charge_at_immigrate",
  3736. .read_u64 = mem_cgroup_move_charge_read,
  3737. .write_u64 = mem_cgroup_move_charge_write,
  3738. },
  3739. {
  3740. .name = "oom_control",
  3741. .read_map = mem_cgroup_oom_control_read,
  3742. .write_u64 = mem_cgroup_oom_control_write,
  3743. .register_event = mem_cgroup_oom_register_event,
  3744. .unregister_event = mem_cgroup_oom_unregister_event,
  3745. .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
  3746. },
  3747. };
  3748. #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
  3749. static struct cftype memsw_cgroup_files[] = {
  3750. {
  3751. .name = "memsw.usage_in_bytes",
  3752. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
  3753. .read_u64 = mem_cgroup_read,
  3754. .register_event = mem_cgroup_usage_register_event,
  3755. .unregister_event = mem_cgroup_usage_unregister_event,
  3756. },
  3757. {
  3758. .name = "memsw.max_usage_in_bytes",
  3759. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
  3760. .trigger = mem_cgroup_reset,
  3761. .read_u64 = mem_cgroup_read,
  3762. },
  3763. {
  3764. .name = "memsw.limit_in_bytes",
  3765. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
  3766. .write_string = mem_cgroup_write,
  3767. .read_u64 = mem_cgroup_read,
  3768. },
  3769. {
  3770. .name = "memsw.failcnt",
  3771. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
  3772. .trigger = mem_cgroup_reset,
  3773. .read_u64 = mem_cgroup_read,
  3774. },
  3775. };
  3776. static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
  3777. {
  3778. if (!do_swap_account)
  3779. return 0;
  3780. return cgroup_add_files(cont, ss, memsw_cgroup_files,
  3781. ARRAY_SIZE(memsw_cgroup_files));
  3782. };
  3783. #else
  3784. static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
  3785. {
  3786. return 0;
  3787. }
  3788. #endif
  3789. static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
  3790. {
  3791. struct mem_cgroup_per_node *pn;
  3792. struct mem_cgroup_per_zone *mz;
  3793. enum lru_list l;
  3794. int zone, tmp = node;
  3795. /*
  3796. * This routine is called against possible nodes.
  3797. * But it's BUG to call kmalloc() against offline node.
  3798. *
  3799. * TODO: this routine can waste much memory for nodes which will
  3800. * never be onlined. It's better to use memory hotplug callback
  3801. * function.
  3802. */
  3803. if (!node_state(node, N_NORMAL_MEMORY))
  3804. tmp = -1;
  3805. pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
  3806. if (!pn)
  3807. return 1;
  3808. mem->info.nodeinfo[node] = pn;
  3809. for (zone = 0; zone < MAX_NR_ZONES; zone++) {
  3810. mz = &pn->zoneinfo[zone];
  3811. for_each_lru(l)
  3812. INIT_LIST_HEAD(&mz->lists[l]);
  3813. mz->usage_in_excess = 0;
  3814. mz->on_tree = false;
  3815. mz->mem = mem;
  3816. }
  3817. return 0;
  3818. }
  3819. static void free_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
  3820. {
  3821. kfree(mem->info.nodeinfo[node]);
  3822. }
  3823. static struct mem_cgroup *mem_cgroup_alloc(void)
  3824. {
  3825. struct mem_cgroup *mem;
  3826. int size = sizeof(struct mem_cgroup);
  3827. /* Can be very big if MAX_NUMNODES is very big */
  3828. if (size < PAGE_SIZE)
  3829. mem = kzalloc(size, GFP_KERNEL);
  3830. else
  3831. mem = vzalloc(size);
  3832. if (!mem)
  3833. return NULL;
  3834. mem->stat = alloc_percpu(struct mem_cgroup_stat_cpu);
  3835. if (!mem->stat)
  3836. goto out_free;
  3837. spin_lock_init(&mem->pcp_counter_lock);
  3838. return mem;
  3839. out_free:
  3840. if (size < PAGE_SIZE)
  3841. kfree(mem);
  3842. else
  3843. vfree(mem);
  3844. return NULL;
  3845. }
  3846. /*
  3847. * At destroying mem_cgroup, references from swap_cgroup can remain.
  3848. * (scanning all at force_empty is too costly...)
  3849. *
  3850. * Instead of clearing all references at force_empty, we remember
  3851. * the number of reference from swap_cgroup and free mem_cgroup when
  3852. * it goes down to 0.
  3853. *
  3854. * Removal of cgroup itself succeeds regardless of refs from swap.
  3855. */
  3856. static void __mem_cgroup_free(struct mem_cgroup *mem)
  3857. {
  3858. int node;
  3859. mem_cgroup_remove_from_trees(mem);
  3860. free_css_id(&mem_cgroup_subsys, &mem->css);
  3861. for_each_node_state(node, N_POSSIBLE)
  3862. free_mem_cgroup_per_zone_info(mem, node);
  3863. free_percpu(mem->stat);
  3864. if (sizeof(struct mem_cgroup) < PAGE_SIZE)
  3865. kfree(mem);
  3866. else
  3867. vfree(mem);
  3868. }
  3869. static void mem_cgroup_get(struct mem_cgroup *mem)
  3870. {
  3871. atomic_inc(&mem->refcnt);
  3872. }
  3873. static void __mem_cgroup_put(struct mem_cgroup *mem, int count)
  3874. {
  3875. if (atomic_sub_and_test(count, &mem->refcnt)) {
  3876. struct mem_cgroup *parent = parent_mem_cgroup(mem);
  3877. __mem_cgroup_free(mem);
  3878. if (parent)
  3879. mem_cgroup_put(parent);
  3880. }
  3881. }
  3882. static void mem_cgroup_put(struct mem_cgroup *mem)
  3883. {
  3884. __mem_cgroup_put(mem, 1);
  3885. }
  3886. /*
  3887. * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
  3888. */
  3889. static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *mem)
  3890. {
  3891. if (!mem->res.parent)
  3892. return NULL;
  3893. return mem_cgroup_from_res_counter(mem->res.parent, res);
  3894. }
  3895. #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
  3896. static void __init enable_swap_cgroup(void)
  3897. {
  3898. if (!mem_cgroup_disabled() && really_do_swap_account)
  3899. do_swap_account = 1;
  3900. }
  3901. #else
  3902. static void __init enable_swap_cgroup(void)
  3903. {
  3904. }
  3905. #endif
  3906. static int mem_cgroup_soft_limit_tree_init(void)
  3907. {
  3908. struct mem_cgroup_tree_per_node *rtpn;
  3909. struct mem_cgroup_tree_per_zone *rtpz;
  3910. int tmp, node, zone;
  3911. for_each_node_state(node, N_POSSIBLE) {
  3912. tmp = node;
  3913. if (!node_state(node, N_NORMAL_MEMORY))
  3914. tmp = -1;
  3915. rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, tmp);
  3916. if (!rtpn)
  3917. return 1;
  3918. soft_limit_tree.rb_tree_per_node[node] = rtpn;
  3919. for (zone = 0; zone < MAX_NR_ZONES; zone++) {
  3920. rtpz = &rtpn->rb_tree_per_zone[zone];
  3921. rtpz->rb_root = RB_ROOT;
  3922. spin_lock_init(&rtpz->lock);
  3923. }
  3924. }
  3925. return 0;
  3926. }
  3927. static struct cgroup_subsys_state * __ref
  3928. mem_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cont)
  3929. {
  3930. struct mem_cgroup *mem, *parent;
  3931. long error = -ENOMEM;
  3932. int node;
  3933. mem = mem_cgroup_alloc();
  3934. if (!mem)
  3935. return ERR_PTR(error);
  3936. for_each_node_state(node, N_POSSIBLE)
  3937. if (alloc_mem_cgroup_per_zone_info(mem, node))
  3938. goto free_out;
  3939. /* root ? */
  3940. if (cont->parent == NULL) {
  3941. int cpu;
  3942. enable_swap_cgroup();
  3943. parent = NULL;
  3944. root_mem_cgroup = mem;
  3945. if (mem_cgroup_soft_limit_tree_init())
  3946. goto free_out;
  3947. for_each_possible_cpu(cpu) {
  3948. struct memcg_stock_pcp *stock =
  3949. &per_cpu(memcg_stock, cpu);
  3950. INIT_WORK(&stock->work, drain_local_stock);
  3951. }
  3952. hotcpu_notifier(memcg_cpu_hotplug_callback, 0);
  3953. } else {
  3954. parent = mem_cgroup_from_cont(cont->parent);
  3955. mem->use_hierarchy = parent->use_hierarchy;
  3956. mem->oom_kill_disable = parent->oom_kill_disable;
  3957. }
  3958. if (parent && parent->use_hierarchy) {
  3959. res_counter_init(&mem->res, &parent->res);
  3960. res_counter_init(&mem->memsw, &parent->memsw);
  3961. /*
  3962. * We increment refcnt of the parent to ensure that we can
  3963. * safely access it on res_counter_charge/uncharge.
  3964. * This refcnt will be decremented when freeing this
  3965. * mem_cgroup(see mem_cgroup_put).
  3966. */
  3967. mem_cgroup_get(parent);
  3968. } else {
  3969. res_counter_init(&mem->res, NULL);
  3970. res_counter_init(&mem->memsw, NULL);
  3971. }
  3972. mem->last_scanned_child = 0;
  3973. spin_lock_init(&mem->reclaim_param_lock);
  3974. INIT_LIST_HEAD(&mem->oom_notify);
  3975. if (parent)
  3976. mem->swappiness = get_swappiness(parent);
  3977. atomic_set(&mem->refcnt, 1);
  3978. mem->move_charge_at_immigrate = 0;
  3979. mutex_init(&mem->thresholds_lock);
  3980. return &mem->css;
  3981. free_out:
  3982. __mem_cgroup_free(mem);
  3983. root_mem_cgroup = NULL;
  3984. return ERR_PTR(error);
  3985. }
  3986. static int mem_cgroup_pre_destroy(struct cgroup_subsys *ss,
  3987. struct cgroup *cont)
  3988. {
  3989. struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
  3990. return mem_cgroup_force_empty(mem, false);
  3991. }
  3992. static void mem_cgroup_destroy(struct cgroup_subsys *ss,
  3993. struct cgroup *cont)
  3994. {
  3995. struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
  3996. mem_cgroup_put(mem);
  3997. }
  3998. static int mem_cgroup_populate(struct cgroup_subsys *ss,
  3999. struct cgroup *cont)
  4000. {
  4001. int ret;
  4002. ret = cgroup_add_files(cont, ss, mem_cgroup_files,
  4003. ARRAY_SIZE(mem_cgroup_files));
  4004. if (!ret)
  4005. ret = register_memsw_files(cont, ss);
  4006. return ret;
  4007. }
  4008. #ifdef CONFIG_MMU
  4009. /* Handlers for move charge at task migration. */
  4010. #define PRECHARGE_COUNT_AT_ONCE 256
  4011. static int mem_cgroup_do_precharge(unsigned long count)
  4012. {
  4013. int ret = 0;
  4014. int batch_count = PRECHARGE_COUNT_AT_ONCE;
  4015. struct mem_cgroup *mem = mc.to;
  4016. if (mem_cgroup_is_root(mem)) {
  4017. mc.precharge += count;
  4018. /* we don't need css_get for root */
  4019. return ret;
  4020. }
  4021. /* try to charge at once */
  4022. if (count > 1) {
  4023. struct res_counter *dummy;
  4024. /*
  4025. * "mem" cannot be under rmdir() because we've already checked
  4026. * by cgroup_lock_live_cgroup() that it is not removed and we
  4027. * are still under the same cgroup_mutex. So we can postpone
  4028. * css_get().
  4029. */
  4030. if (res_counter_charge(&mem->res, PAGE_SIZE * count, &dummy))
  4031. goto one_by_one;
  4032. if (do_swap_account && res_counter_charge(&mem->memsw,
  4033. PAGE_SIZE * count, &dummy)) {
  4034. res_counter_uncharge(&mem->res, PAGE_SIZE * count);
  4035. goto one_by_one;
  4036. }
  4037. mc.precharge += count;
  4038. return ret;
  4039. }
  4040. one_by_one:
  4041. /* fall back to one by one charge */
  4042. while (count--) {
  4043. if (signal_pending(current)) {
  4044. ret = -EINTR;
  4045. break;
  4046. }
  4047. if (!batch_count--) {
  4048. batch_count = PRECHARGE_COUNT_AT_ONCE;
  4049. cond_resched();
  4050. }
  4051. ret = __mem_cgroup_try_charge(NULL, GFP_KERNEL, &mem, false,
  4052. PAGE_SIZE);
  4053. if (ret || !mem)
  4054. /* mem_cgroup_clear_mc() will do uncharge later */
  4055. return -ENOMEM;
  4056. mc.precharge++;
  4057. }
  4058. return ret;
  4059. }
  4060. /**
  4061. * is_target_pte_for_mc - check a pte whether it is valid for move charge
  4062. * @vma: the vma the pte to be checked belongs
  4063. * @addr: the address corresponding to the pte to be checked
  4064. * @ptent: the pte to be checked
  4065. * @target: the pointer the target page or swap ent will be stored(can be NULL)
  4066. *
  4067. * Returns
  4068. * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
  4069. * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
  4070. * move charge. if @target is not NULL, the page is stored in target->page
  4071. * with extra refcnt got(Callers should handle it).
  4072. * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
  4073. * target for charge migration. if @target is not NULL, the entry is stored
  4074. * in target->ent.
  4075. *
  4076. * Called with pte lock held.
  4077. */
  4078. union mc_target {
  4079. struct page *page;
  4080. swp_entry_t ent;
  4081. };
  4082. enum mc_target_type {
  4083. MC_TARGET_NONE, /* not used */
  4084. MC_TARGET_PAGE,
  4085. MC_TARGET_SWAP,
  4086. };
  4087. static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
  4088. unsigned long addr, pte_t ptent)
  4089. {
  4090. struct page *page = vm_normal_page(vma, addr, ptent);
  4091. if (!page || !page_mapped(page))
  4092. return NULL;
  4093. if (PageAnon(page)) {
  4094. /* we don't move shared anon */
  4095. if (!move_anon() || page_mapcount(page) > 2)
  4096. return NULL;
  4097. } else if (!move_file())
  4098. /* we ignore mapcount for file pages */
  4099. return NULL;
  4100. if (!get_page_unless_zero(page))
  4101. return NULL;
  4102. return page;
  4103. }
  4104. static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
  4105. unsigned long addr, pte_t ptent, swp_entry_t *entry)
  4106. {
  4107. int usage_count;
  4108. struct page *page = NULL;
  4109. swp_entry_t ent = pte_to_swp_entry(ptent);
  4110. if (!move_anon() || non_swap_entry(ent))
  4111. return NULL;
  4112. usage_count = mem_cgroup_count_swap_user(ent, &page);
  4113. if (usage_count > 1) { /* we don't move shared anon */
  4114. if (page)
  4115. put_page(page);
  4116. return NULL;
  4117. }
  4118. if (do_swap_account)
  4119. entry->val = ent.val;
  4120. return page;
  4121. }
  4122. static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
  4123. unsigned long addr, pte_t ptent, swp_entry_t *entry)
  4124. {
  4125. struct page *page = NULL;
  4126. struct inode *inode;
  4127. struct address_space *mapping;
  4128. pgoff_t pgoff;
  4129. if (!vma->vm_file) /* anonymous vma */
  4130. return NULL;
  4131. if (!move_file())
  4132. return NULL;
  4133. inode = vma->vm_file->f_path.dentry->d_inode;
  4134. mapping = vma->vm_file->f_mapping;
  4135. if (pte_none(ptent))
  4136. pgoff = linear_page_index(vma, addr);
  4137. else /* pte_file(ptent) is true */
  4138. pgoff = pte_to_pgoff(ptent);
  4139. /* page is moved even if it's not RSS of this task(page-faulted). */
  4140. if (!mapping_cap_swap_backed(mapping)) { /* normal file */
  4141. page = find_get_page(mapping, pgoff);
  4142. } else { /* shmem/tmpfs file. we should take account of swap too. */
  4143. swp_entry_t ent;
  4144. mem_cgroup_get_shmem_target(inode, pgoff, &page, &ent);
  4145. if (do_swap_account)
  4146. entry->val = ent.val;
  4147. }
  4148. return page;
  4149. }
  4150. static int is_target_pte_for_mc(struct vm_area_struct *vma,
  4151. unsigned long addr, pte_t ptent, union mc_target *target)
  4152. {
  4153. struct page *page = NULL;
  4154. struct page_cgroup *pc;
  4155. int ret = 0;
  4156. swp_entry_t ent = { .val = 0 };
  4157. if (pte_present(ptent))
  4158. page = mc_handle_present_pte(vma, addr, ptent);
  4159. else if (is_swap_pte(ptent))
  4160. page = mc_handle_swap_pte(vma, addr, ptent, &ent);
  4161. else if (pte_none(ptent) || pte_file(ptent))
  4162. page = mc_handle_file_pte(vma, addr, ptent, &ent);
  4163. if (!page && !ent.val)
  4164. return 0;
  4165. if (page) {
  4166. pc = lookup_page_cgroup(page);
  4167. /*
  4168. * Do only loose check w/o page_cgroup lock.
  4169. * mem_cgroup_move_account() checks the pc is valid or not under
  4170. * the lock.
  4171. */
  4172. if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
  4173. ret = MC_TARGET_PAGE;
  4174. if (target)
  4175. target->page = page;
  4176. }
  4177. if (!ret || !target)
  4178. put_page(page);
  4179. }
  4180. /* There is a swap entry and a page doesn't exist or isn't charged */
  4181. if (ent.val && !ret &&
  4182. css_id(&mc.from->css) == lookup_swap_cgroup(ent)) {
  4183. ret = MC_TARGET_SWAP;
  4184. if (target)
  4185. target->ent = ent;
  4186. }
  4187. return ret;
  4188. }
  4189. static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
  4190. unsigned long addr, unsigned long end,
  4191. struct mm_walk *walk)
  4192. {
  4193. struct vm_area_struct *vma = walk->private;
  4194. pte_t *pte;
  4195. spinlock_t *ptl;
  4196. split_huge_page_pmd(walk->mm, pmd);
  4197. pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
  4198. for (; addr != end; pte++, addr += PAGE_SIZE)
  4199. if (is_target_pte_for_mc(vma, addr, *pte, NULL))
  4200. mc.precharge++; /* increment precharge temporarily */
  4201. pte_unmap_unlock(pte - 1, ptl);
  4202. cond_resched();
  4203. return 0;
  4204. }
  4205. static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
  4206. {
  4207. unsigned long precharge;
  4208. struct vm_area_struct *vma;
  4209. down_read(&mm->mmap_sem);
  4210. for (vma = mm->mmap; vma; vma = vma->vm_next) {
  4211. struct mm_walk mem_cgroup_count_precharge_walk = {
  4212. .pmd_entry = mem_cgroup_count_precharge_pte_range,
  4213. .mm = mm,
  4214. .private = vma,
  4215. };
  4216. if (is_vm_hugetlb_page(vma))
  4217. continue;
  4218. walk_page_range(vma->vm_start, vma->vm_end,
  4219. &mem_cgroup_count_precharge_walk);
  4220. }
  4221. up_read(&mm->mmap_sem);
  4222. precharge = mc.precharge;
  4223. mc.precharge = 0;
  4224. return precharge;
  4225. }
  4226. static int mem_cgroup_precharge_mc(struct mm_struct *mm)
  4227. {
  4228. unsigned long precharge = mem_cgroup_count_precharge(mm);
  4229. VM_BUG_ON(mc.moving_task);
  4230. mc.moving_task = current;
  4231. return mem_cgroup_do_precharge(precharge);
  4232. }
  4233. /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
  4234. static void __mem_cgroup_clear_mc(void)
  4235. {
  4236. struct mem_cgroup *from = mc.from;
  4237. struct mem_cgroup *to = mc.to;
  4238. /* we must uncharge all the leftover precharges from mc.to */
  4239. if (mc.precharge) {
  4240. __mem_cgroup_cancel_charge(mc.to, mc.precharge);
  4241. mc.precharge = 0;
  4242. }
  4243. /*
  4244. * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
  4245. * we must uncharge here.
  4246. */
  4247. if (mc.moved_charge) {
  4248. __mem_cgroup_cancel_charge(mc.from, mc.moved_charge);
  4249. mc.moved_charge = 0;
  4250. }
  4251. /* we must fixup refcnts and charges */
  4252. if (mc.moved_swap) {
  4253. /* uncharge swap account from the old cgroup */
  4254. if (!mem_cgroup_is_root(mc.from))
  4255. res_counter_uncharge(&mc.from->memsw,
  4256. PAGE_SIZE * mc.moved_swap);
  4257. __mem_cgroup_put(mc.from, mc.moved_swap);
  4258. if (!mem_cgroup_is_root(mc.to)) {
  4259. /*
  4260. * we charged both to->res and to->memsw, so we should
  4261. * uncharge to->res.
  4262. */
  4263. res_counter_uncharge(&mc.to->res,
  4264. PAGE_SIZE * mc.moved_swap);
  4265. }
  4266. /* we've already done mem_cgroup_get(mc.to) */
  4267. mc.moved_swap = 0;
  4268. }
  4269. memcg_oom_recover(from);
  4270. memcg_oom_recover(to);
  4271. wake_up_all(&mc.waitq);
  4272. }
  4273. static void mem_cgroup_clear_mc(void)
  4274. {
  4275. struct mem_cgroup *from = mc.from;
  4276. /*
  4277. * we must clear moving_task before waking up waiters at the end of
  4278. * task migration.
  4279. */
  4280. mc.moving_task = NULL;
  4281. __mem_cgroup_clear_mc();
  4282. spin_lock(&mc.lock);
  4283. mc.from = NULL;
  4284. mc.to = NULL;
  4285. spin_unlock(&mc.lock);
  4286. mem_cgroup_end_move(from);
  4287. }
  4288. static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
  4289. struct cgroup *cgroup,
  4290. struct task_struct *p,
  4291. bool threadgroup)
  4292. {
  4293. int ret = 0;
  4294. struct mem_cgroup *mem = mem_cgroup_from_cont(cgroup);
  4295. if (mem->move_charge_at_immigrate) {
  4296. struct mm_struct *mm;
  4297. struct mem_cgroup *from = mem_cgroup_from_task(p);
  4298. VM_BUG_ON(from == mem);
  4299. mm = get_task_mm(p);
  4300. if (!mm)
  4301. return 0;
  4302. /* We move charges only when we move a owner of the mm */
  4303. if (mm->owner == p) {
  4304. VM_BUG_ON(mc.from);
  4305. VM_BUG_ON(mc.to);
  4306. VM_BUG_ON(mc.precharge);
  4307. VM_BUG_ON(mc.moved_charge);
  4308. VM_BUG_ON(mc.moved_swap);
  4309. mem_cgroup_start_move(from);
  4310. spin_lock(&mc.lock);
  4311. mc.from = from;
  4312. mc.to = mem;
  4313. spin_unlock(&mc.lock);
  4314. /* We set mc.moving_task later */
  4315. ret = mem_cgroup_precharge_mc(mm);
  4316. if (ret)
  4317. mem_cgroup_clear_mc();
  4318. }
  4319. mmput(mm);
  4320. }
  4321. return ret;
  4322. }
  4323. static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
  4324. struct cgroup *cgroup,
  4325. struct task_struct *p,
  4326. bool threadgroup)
  4327. {
  4328. mem_cgroup_clear_mc();
  4329. }
  4330. static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
  4331. unsigned long addr, unsigned long end,
  4332. struct mm_walk *walk)
  4333. {
  4334. int ret = 0;
  4335. struct vm_area_struct *vma = walk->private;
  4336. pte_t *pte;
  4337. spinlock_t *ptl;
  4338. split_huge_page_pmd(walk->mm, pmd);
  4339. retry:
  4340. pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
  4341. for (; addr != end; addr += PAGE_SIZE) {
  4342. pte_t ptent = *(pte++);
  4343. union mc_target target;
  4344. int type;
  4345. struct page *page;
  4346. struct page_cgroup *pc;
  4347. swp_entry_t ent;
  4348. if (!mc.precharge)
  4349. break;
  4350. type = is_target_pte_for_mc(vma, addr, ptent, &target);
  4351. switch (type) {
  4352. case MC_TARGET_PAGE:
  4353. page = target.page;
  4354. if (isolate_lru_page(page))
  4355. goto put;
  4356. pc = lookup_page_cgroup(page);
  4357. if (!mem_cgroup_move_account(page, pc,
  4358. mc.from, mc.to, false, PAGE_SIZE)) {
  4359. mc.precharge--;
  4360. /* we uncharge from mc.from later. */
  4361. mc.moved_charge++;
  4362. }
  4363. putback_lru_page(page);
  4364. put: /* is_target_pte_for_mc() gets the page */
  4365. put_page(page);
  4366. break;
  4367. case MC_TARGET_SWAP:
  4368. ent = target.ent;
  4369. if (!mem_cgroup_move_swap_account(ent,
  4370. mc.from, mc.to, false)) {
  4371. mc.precharge--;
  4372. /* we fixup refcnts and charges later. */
  4373. mc.moved_swap++;
  4374. }
  4375. break;
  4376. default:
  4377. break;
  4378. }
  4379. }
  4380. pte_unmap_unlock(pte - 1, ptl);
  4381. cond_resched();
  4382. if (addr != end) {
  4383. /*
  4384. * We have consumed all precharges we got in can_attach().
  4385. * We try charge one by one, but don't do any additional
  4386. * charges to mc.to if we have failed in charge once in attach()
  4387. * phase.
  4388. */
  4389. ret = mem_cgroup_do_precharge(1);
  4390. if (!ret)
  4391. goto retry;
  4392. }
  4393. return ret;
  4394. }
  4395. static void mem_cgroup_move_charge(struct mm_struct *mm)
  4396. {
  4397. struct vm_area_struct *vma;
  4398. lru_add_drain_all();
  4399. retry:
  4400. if (unlikely(!down_read_trylock(&mm->mmap_sem))) {
  4401. /*
  4402. * Someone who are holding the mmap_sem might be waiting in
  4403. * waitq. So we cancel all extra charges, wake up all waiters,
  4404. * and retry. Because we cancel precharges, we might not be able
  4405. * to move enough charges, but moving charge is a best-effort
  4406. * feature anyway, so it wouldn't be a big problem.
  4407. */
  4408. __mem_cgroup_clear_mc();
  4409. cond_resched();
  4410. goto retry;
  4411. }
  4412. for (vma = mm->mmap; vma; vma = vma->vm_next) {
  4413. int ret;
  4414. struct mm_walk mem_cgroup_move_charge_walk = {
  4415. .pmd_entry = mem_cgroup_move_charge_pte_range,
  4416. .mm = mm,
  4417. .private = vma,
  4418. };
  4419. if (is_vm_hugetlb_page(vma))
  4420. continue;
  4421. ret = walk_page_range(vma->vm_start, vma->vm_end,
  4422. &mem_cgroup_move_charge_walk);
  4423. if (ret)
  4424. /*
  4425. * means we have consumed all precharges and failed in
  4426. * doing additional charge. Just abandon here.
  4427. */
  4428. break;
  4429. }
  4430. up_read(&mm->mmap_sem);
  4431. }
  4432. static void mem_cgroup_move_task(struct cgroup_subsys *ss,
  4433. struct cgroup *cont,
  4434. struct cgroup *old_cont,
  4435. struct task_struct *p,
  4436. bool threadgroup)
  4437. {
  4438. struct mm_struct *mm;
  4439. if (!mc.to)
  4440. /* no need to move charge */
  4441. return;
  4442. mm = get_task_mm(p);
  4443. if (mm) {
  4444. mem_cgroup_move_charge(mm);
  4445. mmput(mm);
  4446. }
  4447. mem_cgroup_clear_mc();
  4448. }
  4449. #else /* !CONFIG_MMU */
  4450. static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
  4451. struct cgroup *cgroup,
  4452. struct task_struct *p,
  4453. bool threadgroup)
  4454. {
  4455. return 0;
  4456. }
  4457. static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
  4458. struct cgroup *cgroup,
  4459. struct task_struct *p,
  4460. bool threadgroup)
  4461. {
  4462. }
  4463. static void mem_cgroup_move_task(struct cgroup_subsys *ss,
  4464. struct cgroup *cont,
  4465. struct cgroup *old_cont,
  4466. struct task_struct *p,
  4467. bool threadgroup)
  4468. {
  4469. }
  4470. #endif
  4471. struct cgroup_subsys mem_cgroup_subsys = {
  4472. .name = "memory",
  4473. .subsys_id = mem_cgroup_subsys_id,
  4474. .create = mem_cgroup_create,
  4475. .pre_destroy = mem_cgroup_pre_destroy,
  4476. .destroy = mem_cgroup_destroy,
  4477. .populate = mem_cgroup_populate,
  4478. .can_attach = mem_cgroup_can_attach,
  4479. .cancel_attach = mem_cgroup_cancel_attach,
  4480. .attach = mem_cgroup_move_task,
  4481. .early_init = 0,
  4482. .use_id = 1,
  4483. };
  4484. #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
  4485. static int __init enable_swap_account(char *s)
  4486. {
  4487. /* consider enabled if no parameter or 1 is given */
  4488. if (!(*s) || !strcmp(s, "=1"))
  4489. really_do_swap_account = 1;
  4490. else if (!strcmp(s, "=0"))
  4491. really_do_swap_account = 0;
  4492. return 1;
  4493. }
  4494. __setup("swapaccount", enable_swap_account);
  4495. static int __init disable_swap_account(char *s)
  4496. {
  4497. printk_once("noswapaccount is deprecated and will be removed in 2.6.40. Use swapaccount=0 instead\n");
  4498. enable_swap_account("=0");
  4499. return 1;
  4500. }
  4501. __setup("noswapaccount", disable_swap_account);
  4502. #endif