memcontrol.c 144 KB

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