memcontrol.c 147 KB

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