memcontrol.c 143 KB

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