memcontrol.c 142 KB

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