memcontrol.c 143 KB

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