memcontrol.c 145 KB

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