memcontrol.c 145 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671
  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. /*
  1827. * Try to consume stocked charge on this cpu. If success, one page is consumed
  1828. * from local stock and true is returned. If the stock is 0 or charges from a
  1829. * cgroup which is not current target, returns false. This stock will be
  1830. * refilled.
  1831. */
  1832. static bool consume_stock(struct mem_cgroup *mem)
  1833. {
  1834. struct memcg_stock_pcp *stock;
  1835. bool ret = true;
  1836. stock = &get_cpu_var(memcg_stock);
  1837. if (mem == stock->cached && stock->nr_pages)
  1838. stock->nr_pages--;
  1839. else /* need to call res_counter_charge */
  1840. ret = false;
  1841. put_cpu_var(memcg_stock);
  1842. return ret;
  1843. }
  1844. /*
  1845. * Returns stocks cached in percpu to res_counter and reset cached information.
  1846. */
  1847. static void drain_stock(struct memcg_stock_pcp *stock)
  1848. {
  1849. struct mem_cgroup *old = stock->cached;
  1850. if (stock->nr_pages) {
  1851. unsigned long bytes = stock->nr_pages * PAGE_SIZE;
  1852. res_counter_uncharge(&old->res, bytes);
  1853. if (do_swap_account)
  1854. res_counter_uncharge(&old->memsw, bytes);
  1855. stock->nr_pages = 0;
  1856. }
  1857. stock->cached = NULL;
  1858. }
  1859. /*
  1860. * This must be called under preempt disabled or must be called by
  1861. * a thread which is pinned to local cpu.
  1862. */
  1863. static void drain_local_stock(struct work_struct *dummy)
  1864. {
  1865. struct memcg_stock_pcp *stock = &__get_cpu_var(memcg_stock);
  1866. drain_stock(stock);
  1867. clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
  1868. }
  1869. /*
  1870. * Cache charges(val) which is from res_counter, to local per_cpu area.
  1871. * This will be consumed by consume_stock() function, later.
  1872. */
  1873. static void refill_stock(struct mem_cgroup *mem, unsigned int nr_pages)
  1874. {
  1875. struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock);
  1876. if (stock->cached != mem) { /* reset if necessary */
  1877. drain_stock(stock);
  1878. stock->cached = mem;
  1879. }
  1880. stock->nr_pages += nr_pages;
  1881. put_cpu_var(memcg_stock);
  1882. }
  1883. /*
  1884. * Drains all per-CPU charge caches for given root_mem resp. subtree
  1885. * of the hierarchy under it. sync flag says whether we should block
  1886. * until the work is done.
  1887. */
  1888. static void drain_all_stock(struct mem_cgroup *root_mem, bool sync)
  1889. {
  1890. int cpu, curcpu;
  1891. /* Notify other cpus that system-wide "drain" is running */
  1892. get_online_cpus();
  1893. /*
  1894. * Get a hint for avoiding draining charges on the current cpu,
  1895. * which must be exhausted by our charging. It is not required that
  1896. * this be a precise check, so we use raw_smp_processor_id() instead of
  1897. * getcpu()/putcpu().
  1898. */
  1899. curcpu = raw_smp_processor_id();
  1900. for_each_online_cpu(cpu) {
  1901. struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
  1902. struct mem_cgroup *mem;
  1903. mem = stock->cached;
  1904. if (!mem || !stock->nr_pages)
  1905. continue;
  1906. if (!mem_cgroup_same_or_subtree(root_mem, mem))
  1907. continue;
  1908. if (!test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
  1909. if (cpu == curcpu)
  1910. drain_local_stock(&stock->work);
  1911. else
  1912. schedule_work_on(cpu, &stock->work);
  1913. }
  1914. }
  1915. if (!sync)
  1916. goto out;
  1917. for_each_online_cpu(cpu) {
  1918. struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
  1919. if (mem_cgroup_same_or_subtree(root_mem, stock->cached) &&
  1920. test_bit(FLUSHING_CACHED_CHARGE, &stock->flags))
  1921. flush_work(&stock->work);
  1922. }
  1923. out:
  1924. put_online_cpus();
  1925. }
  1926. /*
  1927. * Tries to drain stocked charges in other cpus. This function is asynchronous
  1928. * and just put a work per cpu for draining localy on each cpu. Caller can
  1929. * expects some charges will be back to res_counter later but cannot wait for
  1930. * it.
  1931. */
  1932. static void drain_all_stock_async(struct mem_cgroup *root_mem)
  1933. {
  1934. drain_all_stock(root_mem, false);
  1935. }
  1936. /* This is a synchronous drain interface. */
  1937. static void drain_all_stock_sync(struct mem_cgroup *root_mem)
  1938. {
  1939. /* called when force_empty is called */
  1940. drain_all_stock(root_mem, true);
  1941. }
  1942. /*
  1943. * This function drains percpu counter value from DEAD cpu and
  1944. * move it to local cpu. Note that this function can be preempted.
  1945. */
  1946. static void mem_cgroup_drain_pcp_counter(struct mem_cgroup *mem, int cpu)
  1947. {
  1948. int i;
  1949. spin_lock(&mem->pcp_counter_lock);
  1950. for (i = 0; i < MEM_CGROUP_STAT_DATA; i++) {
  1951. long x = per_cpu(mem->stat->count[i], cpu);
  1952. per_cpu(mem->stat->count[i], cpu) = 0;
  1953. mem->nocpu_base.count[i] += x;
  1954. }
  1955. for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
  1956. unsigned long x = per_cpu(mem->stat->events[i], cpu);
  1957. per_cpu(mem->stat->events[i], cpu) = 0;
  1958. mem->nocpu_base.events[i] += x;
  1959. }
  1960. /* need to clear ON_MOVE value, works as a kind of lock. */
  1961. per_cpu(mem->stat->count[MEM_CGROUP_ON_MOVE], cpu) = 0;
  1962. spin_unlock(&mem->pcp_counter_lock);
  1963. }
  1964. static void synchronize_mem_cgroup_on_move(struct mem_cgroup *mem, int cpu)
  1965. {
  1966. int idx = MEM_CGROUP_ON_MOVE;
  1967. spin_lock(&mem->pcp_counter_lock);
  1968. per_cpu(mem->stat->count[idx], cpu) = mem->nocpu_base.count[idx];
  1969. spin_unlock(&mem->pcp_counter_lock);
  1970. }
  1971. static int __cpuinit memcg_cpu_hotplug_callback(struct notifier_block *nb,
  1972. unsigned long action,
  1973. void *hcpu)
  1974. {
  1975. int cpu = (unsigned long)hcpu;
  1976. struct memcg_stock_pcp *stock;
  1977. struct mem_cgroup *iter;
  1978. if ((action == CPU_ONLINE)) {
  1979. for_each_mem_cgroup_all(iter)
  1980. synchronize_mem_cgroup_on_move(iter, cpu);
  1981. return NOTIFY_OK;
  1982. }
  1983. if ((action != CPU_DEAD) || action != CPU_DEAD_FROZEN)
  1984. return NOTIFY_OK;
  1985. for_each_mem_cgroup_all(iter)
  1986. mem_cgroup_drain_pcp_counter(iter, cpu);
  1987. stock = &per_cpu(memcg_stock, cpu);
  1988. drain_stock(stock);
  1989. return NOTIFY_OK;
  1990. }
  1991. /* See __mem_cgroup_try_charge() for details */
  1992. enum {
  1993. CHARGE_OK, /* success */
  1994. CHARGE_RETRY, /* need to retry but retry is not bad */
  1995. CHARGE_NOMEM, /* we can't do more. return -ENOMEM */
  1996. CHARGE_WOULDBLOCK, /* GFP_WAIT wasn't set and no enough res. */
  1997. CHARGE_OOM_DIE, /* the current is killed because of OOM */
  1998. };
  1999. static int mem_cgroup_do_charge(struct mem_cgroup *mem, gfp_t gfp_mask,
  2000. unsigned int nr_pages, bool oom_check)
  2001. {
  2002. unsigned long csize = nr_pages * PAGE_SIZE;
  2003. struct mem_cgroup *mem_over_limit;
  2004. struct res_counter *fail_res;
  2005. unsigned long flags = 0;
  2006. int ret;
  2007. ret = res_counter_charge(&mem->res, csize, &fail_res);
  2008. if (likely(!ret)) {
  2009. if (!do_swap_account)
  2010. return CHARGE_OK;
  2011. ret = res_counter_charge(&mem->memsw, csize, &fail_res);
  2012. if (likely(!ret))
  2013. return CHARGE_OK;
  2014. res_counter_uncharge(&mem->res, csize);
  2015. mem_over_limit = mem_cgroup_from_res_counter(fail_res, memsw);
  2016. flags |= MEM_CGROUP_RECLAIM_NOSWAP;
  2017. } else
  2018. mem_over_limit = mem_cgroup_from_res_counter(fail_res, res);
  2019. /*
  2020. * nr_pages can be either a huge page (HPAGE_PMD_NR), a batch
  2021. * of regular pages (CHARGE_BATCH), or a single regular page (1).
  2022. *
  2023. * Never reclaim on behalf of optional batching, retry with a
  2024. * single page instead.
  2025. */
  2026. if (nr_pages == CHARGE_BATCH)
  2027. return CHARGE_RETRY;
  2028. if (!(gfp_mask & __GFP_WAIT))
  2029. return CHARGE_WOULDBLOCK;
  2030. ret = mem_cgroup_hierarchical_reclaim(mem_over_limit, NULL,
  2031. gfp_mask, flags, NULL);
  2032. if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
  2033. return CHARGE_RETRY;
  2034. /*
  2035. * Even though the limit is exceeded at this point, reclaim
  2036. * may have been able to free some pages. Retry the charge
  2037. * before killing the task.
  2038. *
  2039. * Only for regular pages, though: huge pages are rather
  2040. * unlikely to succeed so close to the limit, and we fall back
  2041. * to regular pages anyway in case of failure.
  2042. */
  2043. if (nr_pages == 1 && ret)
  2044. return CHARGE_RETRY;
  2045. /*
  2046. * At task move, charge accounts can be doubly counted. So, it's
  2047. * better to wait until the end of task_move if something is going on.
  2048. */
  2049. if (mem_cgroup_wait_acct_move(mem_over_limit))
  2050. return CHARGE_RETRY;
  2051. /* If we don't need to call oom-killer at el, return immediately */
  2052. if (!oom_check)
  2053. return CHARGE_NOMEM;
  2054. /* check OOM */
  2055. if (!mem_cgroup_handle_oom(mem_over_limit, gfp_mask))
  2056. return CHARGE_OOM_DIE;
  2057. return CHARGE_RETRY;
  2058. }
  2059. /*
  2060. * Unlike exported interface, "oom" parameter is added. if oom==true,
  2061. * oom-killer can be invoked.
  2062. */
  2063. static int __mem_cgroup_try_charge(struct mm_struct *mm,
  2064. gfp_t gfp_mask,
  2065. unsigned int nr_pages,
  2066. struct mem_cgroup **memcg,
  2067. bool oom)
  2068. {
  2069. unsigned int batch = max(CHARGE_BATCH, nr_pages);
  2070. int nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
  2071. struct mem_cgroup *mem = NULL;
  2072. int ret;
  2073. /*
  2074. * Unlike gloval-vm's OOM-kill, we're not in memory shortage
  2075. * in system level. So, allow to go ahead dying process in addition to
  2076. * MEMDIE process.
  2077. */
  2078. if (unlikely(test_thread_flag(TIF_MEMDIE)
  2079. || fatal_signal_pending(current)))
  2080. goto bypass;
  2081. /*
  2082. * We always charge the cgroup the mm_struct belongs to.
  2083. * The mm_struct's mem_cgroup changes on task migration if the
  2084. * thread group leader migrates. It's possible that mm is not
  2085. * set, if so charge the init_mm (happens for pagecache usage).
  2086. */
  2087. if (!*memcg && !mm)
  2088. goto bypass;
  2089. again:
  2090. if (*memcg) { /* css should be a valid one */
  2091. mem = *memcg;
  2092. VM_BUG_ON(css_is_removed(&mem->css));
  2093. if (mem_cgroup_is_root(mem))
  2094. goto done;
  2095. if (nr_pages == 1 && consume_stock(mem))
  2096. goto done;
  2097. css_get(&mem->css);
  2098. } else {
  2099. struct task_struct *p;
  2100. rcu_read_lock();
  2101. p = rcu_dereference(mm->owner);
  2102. /*
  2103. * Because we don't have task_lock(), "p" can exit.
  2104. * In that case, "mem" can point to root or p can be NULL with
  2105. * race with swapoff. Then, we have small risk of mis-accouning.
  2106. * But such kind of mis-account by race always happens because
  2107. * we don't have cgroup_mutex(). It's overkill and we allo that
  2108. * small race, here.
  2109. * (*) swapoff at el will charge against mm-struct not against
  2110. * task-struct. So, mm->owner can be NULL.
  2111. */
  2112. mem = mem_cgroup_from_task(p);
  2113. if (!mem || mem_cgroup_is_root(mem)) {
  2114. rcu_read_unlock();
  2115. goto done;
  2116. }
  2117. if (nr_pages == 1 && consume_stock(mem)) {
  2118. /*
  2119. * It seems dagerous to access memcg without css_get().
  2120. * But considering how consume_stok works, it's not
  2121. * necessary. If consume_stock success, some charges
  2122. * from this memcg are cached on this cpu. So, we
  2123. * don't need to call css_get()/css_tryget() before
  2124. * calling consume_stock().
  2125. */
  2126. rcu_read_unlock();
  2127. goto done;
  2128. }
  2129. /* after here, we may be blocked. we need to get refcnt */
  2130. if (!css_tryget(&mem->css)) {
  2131. rcu_read_unlock();
  2132. goto again;
  2133. }
  2134. rcu_read_unlock();
  2135. }
  2136. do {
  2137. bool oom_check;
  2138. /* If killed, bypass charge */
  2139. if (fatal_signal_pending(current)) {
  2140. css_put(&mem->css);
  2141. goto bypass;
  2142. }
  2143. oom_check = false;
  2144. if (oom && !nr_oom_retries) {
  2145. oom_check = true;
  2146. nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
  2147. }
  2148. ret = mem_cgroup_do_charge(mem, gfp_mask, batch, oom_check);
  2149. switch (ret) {
  2150. case CHARGE_OK:
  2151. break;
  2152. case CHARGE_RETRY: /* not in OOM situation but retry */
  2153. batch = nr_pages;
  2154. css_put(&mem->css);
  2155. mem = NULL;
  2156. goto again;
  2157. case CHARGE_WOULDBLOCK: /* !__GFP_WAIT */
  2158. css_put(&mem->css);
  2159. goto nomem;
  2160. case CHARGE_NOMEM: /* OOM routine works */
  2161. if (!oom) {
  2162. css_put(&mem->css);
  2163. goto nomem;
  2164. }
  2165. /* If oom, we never return -ENOMEM */
  2166. nr_oom_retries--;
  2167. break;
  2168. case CHARGE_OOM_DIE: /* Killed by OOM Killer */
  2169. css_put(&mem->css);
  2170. goto bypass;
  2171. }
  2172. } while (ret != CHARGE_OK);
  2173. if (batch > nr_pages)
  2174. refill_stock(mem, batch - nr_pages);
  2175. css_put(&mem->css);
  2176. done:
  2177. *memcg = mem;
  2178. return 0;
  2179. nomem:
  2180. *memcg = NULL;
  2181. return -ENOMEM;
  2182. bypass:
  2183. *memcg = NULL;
  2184. return 0;
  2185. }
  2186. /*
  2187. * Somemtimes we have to undo a charge we got by try_charge().
  2188. * This function is for that and do uncharge, put css's refcnt.
  2189. * gotten by try_charge().
  2190. */
  2191. static void __mem_cgroup_cancel_charge(struct mem_cgroup *mem,
  2192. unsigned int nr_pages)
  2193. {
  2194. if (!mem_cgroup_is_root(mem)) {
  2195. unsigned long bytes = nr_pages * PAGE_SIZE;
  2196. res_counter_uncharge(&mem->res, bytes);
  2197. if (do_swap_account)
  2198. res_counter_uncharge(&mem->memsw, bytes);
  2199. }
  2200. }
  2201. /*
  2202. * A helper function to get mem_cgroup from ID. must be called under
  2203. * rcu_read_lock(). The caller must check css_is_removed() or some if
  2204. * it's concern. (dropping refcnt from swap can be called against removed
  2205. * memcg.)
  2206. */
  2207. static struct mem_cgroup *mem_cgroup_lookup(unsigned short id)
  2208. {
  2209. struct cgroup_subsys_state *css;
  2210. /* ID 0 is unused ID */
  2211. if (!id)
  2212. return NULL;
  2213. css = css_lookup(&mem_cgroup_subsys, id);
  2214. if (!css)
  2215. return NULL;
  2216. return container_of(css, struct mem_cgroup, css);
  2217. }
  2218. struct mem_cgroup *try_get_mem_cgroup_from_page(struct page *page)
  2219. {
  2220. struct mem_cgroup *mem = NULL;
  2221. struct page_cgroup *pc;
  2222. unsigned short id;
  2223. swp_entry_t ent;
  2224. VM_BUG_ON(!PageLocked(page));
  2225. pc = lookup_page_cgroup(page);
  2226. lock_page_cgroup(pc);
  2227. if (PageCgroupUsed(pc)) {
  2228. mem = pc->mem_cgroup;
  2229. if (mem && !css_tryget(&mem->css))
  2230. mem = NULL;
  2231. } else if (PageSwapCache(page)) {
  2232. ent.val = page_private(page);
  2233. id = lookup_swap_cgroup(ent);
  2234. rcu_read_lock();
  2235. mem = mem_cgroup_lookup(id);
  2236. if (mem && !css_tryget(&mem->css))
  2237. mem = NULL;
  2238. rcu_read_unlock();
  2239. }
  2240. unlock_page_cgroup(pc);
  2241. return mem;
  2242. }
  2243. static void __mem_cgroup_commit_charge(struct mem_cgroup *mem,
  2244. struct page *page,
  2245. unsigned int nr_pages,
  2246. struct page_cgroup *pc,
  2247. enum charge_type ctype)
  2248. {
  2249. lock_page_cgroup(pc);
  2250. if (unlikely(PageCgroupUsed(pc))) {
  2251. unlock_page_cgroup(pc);
  2252. __mem_cgroup_cancel_charge(mem, nr_pages);
  2253. return;
  2254. }
  2255. /*
  2256. * we don't need page_cgroup_lock about tail pages, becase they are not
  2257. * accessed by any other context at this point.
  2258. */
  2259. pc->mem_cgroup = mem;
  2260. /*
  2261. * We access a page_cgroup asynchronously without lock_page_cgroup().
  2262. * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
  2263. * is accessed after testing USED bit. To make pc->mem_cgroup visible
  2264. * before USED bit, we need memory barrier here.
  2265. * See mem_cgroup_add_lru_list(), etc.
  2266. */
  2267. smp_wmb();
  2268. switch (ctype) {
  2269. case MEM_CGROUP_CHARGE_TYPE_CACHE:
  2270. case MEM_CGROUP_CHARGE_TYPE_SHMEM:
  2271. SetPageCgroupCache(pc);
  2272. SetPageCgroupUsed(pc);
  2273. break;
  2274. case MEM_CGROUP_CHARGE_TYPE_MAPPED:
  2275. ClearPageCgroupCache(pc);
  2276. SetPageCgroupUsed(pc);
  2277. break;
  2278. default:
  2279. break;
  2280. }
  2281. mem_cgroup_charge_statistics(mem, PageCgroupCache(pc), nr_pages);
  2282. unlock_page_cgroup(pc);
  2283. /*
  2284. * "charge_statistics" updated event counter. Then, check it.
  2285. * Insert ancestor (and ancestor's ancestors), to softlimit RB-tree.
  2286. * if they exceeds softlimit.
  2287. */
  2288. memcg_check_events(mem, page);
  2289. }
  2290. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  2291. #define PCGF_NOCOPY_AT_SPLIT ((1 << PCG_LOCK) | (1 << PCG_MOVE_LOCK) |\
  2292. (1 << PCG_ACCT_LRU) | (1 << PCG_MIGRATION))
  2293. /*
  2294. * Because tail pages are not marked as "used", set it. We're under
  2295. * zone->lru_lock, 'splitting on pmd' and compund_lock.
  2296. */
  2297. void mem_cgroup_split_huge_fixup(struct page *head, struct page *tail)
  2298. {
  2299. struct page_cgroup *head_pc = lookup_page_cgroup(head);
  2300. struct page_cgroup *tail_pc = lookup_page_cgroup(tail);
  2301. unsigned long flags;
  2302. if (mem_cgroup_disabled())
  2303. return;
  2304. /*
  2305. * We have no races with charge/uncharge but will have races with
  2306. * page state accounting.
  2307. */
  2308. move_lock_page_cgroup(head_pc, &flags);
  2309. tail_pc->mem_cgroup = head_pc->mem_cgroup;
  2310. smp_wmb(); /* see __commit_charge() */
  2311. if (PageCgroupAcctLRU(head_pc)) {
  2312. enum lru_list lru;
  2313. struct mem_cgroup_per_zone *mz;
  2314. /*
  2315. * LRU flags cannot be copied because we need to add tail
  2316. *.page to LRU by generic call and our hook will be called.
  2317. * We hold lru_lock, then, reduce counter directly.
  2318. */
  2319. lru = page_lru(head);
  2320. mz = page_cgroup_zoneinfo(head_pc->mem_cgroup, head);
  2321. MEM_CGROUP_ZSTAT(mz, lru) -= 1;
  2322. }
  2323. tail_pc->flags = head_pc->flags & ~PCGF_NOCOPY_AT_SPLIT;
  2324. move_unlock_page_cgroup(head_pc, &flags);
  2325. }
  2326. #endif
  2327. /**
  2328. * mem_cgroup_move_account - move account of the page
  2329. * @page: the page
  2330. * @nr_pages: number of regular pages (>1 for huge pages)
  2331. * @pc: page_cgroup of the page.
  2332. * @from: mem_cgroup which the page is moved from.
  2333. * @to: mem_cgroup which the page is moved to. @from != @to.
  2334. * @uncharge: whether we should call uncharge and css_put against @from.
  2335. *
  2336. * The caller must confirm following.
  2337. * - page is not on LRU (isolate_page() is useful.)
  2338. * - compound_lock is held when nr_pages > 1
  2339. *
  2340. * This function doesn't do "charge" nor css_get to new cgroup. It should be
  2341. * done by a caller(__mem_cgroup_try_charge would be useful). If @uncharge is
  2342. * true, this function does "uncharge" from old cgroup, but it doesn't if
  2343. * @uncharge is false, so a caller should do "uncharge".
  2344. */
  2345. static int mem_cgroup_move_account(struct page *page,
  2346. unsigned int nr_pages,
  2347. struct page_cgroup *pc,
  2348. struct mem_cgroup *from,
  2349. struct mem_cgroup *to,
  2350. bool uncharge)
  2351. {
  2352. unsigned long flags;
  2353. int ret;
  2354. VM_BUG_ON(from == to);
  2355. VM_BUG_ON(PageLRU(page));
  2356. /*
  2357. * The page is isolated from LRU. So, collapse function
  2358. * will not handle this page. But page splitting can happen.
  2359. * Do this check under compound_page_lock(). The caller should
  2360. * hold it.
  2361. */
  2362. ret = -EBUSY;
  2363. if (nr_pages > 1 && !PageTransHuge(page))
  2364. goto out;
  2365. lock_page_cgroup(pc);
  2366. ret = -EINVAL;
  2367. if (!PageCgroupUsed(pc) || pc->mem_cgroup != from)
  2368. goto unlock;
  2369. move_lock_page_cgroup(pc, &flags);
  2370. if (PageCgroupFileMapped(pc)) {
  2371. /* Update mapped_file data for mem_cgroup */
  2372. preempt_disable();
  2373. __this_cpu_dec(from->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
  2374. __this_cpu_inc(to->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
  2375. preempt_enable();
  2376. }
  2377. mem_cgroup_charge_statistics(from, PageCgroupCache(pc), -nr_pages);
  2378. if (uncharge)
  2379. /* This is not "cancel", but cancel_charge does all we need. */
  2380. __mem_cgroup_cancel_charge(from, nr_pages);
  2381. /* caller should have done css_get */
  2382. pc->mem_cgroup = to;
  2383. mem_cgroup_charge_statistics(to, PageCgroupCache(pc), nr_pages);
  2384. /*
  2385. * We charges against "to" which may not have any tasks. Then, "to"
  2386. * can be under rmdir(). But in current implementation, caller of
  2387. * this function is just force_empty() and move charge, so it's
  2388. * guaranteed that "to" is never removed. So, we don't check rmdir
  2389. * status here.
  2390. */
  2391. move_unlock_page_cgroup(pc, &flags);
  2392. ret = 0;
  2393. unlock:
  2394. unlock_page_cgroup(pc);
  2395. /*
  2396. * check events
  2397. */
  2398. memcg_check_events(to, page);
  2399. memcg_check_events(from, page);
  2400. out:
  2401. return ret;
  2402. }
  2403. /*
  2404. * move charges to its parent.
  2405. */
  2406. static int mem_cgroup_move_parent(struct page *page,
  2407. struct page_cgroup *pc,
  2408. struct mem_cgroup *child,
  2409. gfp_t gfp_mask)
  2410. {
  2411. struct cgroup *cg = child->css.cgroup;
  2412. struct cgroup *pcg = cg->parent;
  2413. struct mem_cgroup *parent;
  2414. unsigned int nr_pages;
  2415. unsigned long uninitialized_var(flags);
  2416. int ret;
  2417. /* Is ROOT ? */
  2418. if (!pcg)
  2419. return -EINVAL;
  2420. ret = -EBUSY;
  2421. if (!get_page_unless_zero(page))
  2422. goto out;
  2423. if (isolate_lru_page(page))
  2424. goto put;
  2425. nr_pages = hpage_nr_pages(page);
  2426. parent = mem_cgroup_from_cont(pcg);
  2427. ret = __mem_cgroup_try_charge(NULL, gfp_mask, nr_pages, &parent, false);
  2428. if (ret || !parent)
  2429. goto put_back;
  2430. if (nr_pages > 1)
  2431. flags = compound_lock_irqsave(page);
  2432. ret = mem_cgroup_move_account(page, nr_pages, pc, child, parent, true);
  2433. if (ret)
  2434. __mem_cgroup_cancel_charge(parent, nr_pages);
  2435. if (nr_pages > 1)
  2436. compound_unlock_irqrestore(page, flags);
  2437. put_back:
  2438. putback_lru_page(page);
  2439. put:
  2440. put_page(page);
  2441. out:
  2442. return ret;
  2443. }
  2444. /*
  2445. * Charge the memory controller for page usage.
  2446. * Return
  2447. * 0 if the charge was successful
  2448. * < 0 if the cgroup is over its limit
  2449. */
  2450. static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
  2451. gfp_t gfp_mask, enum charge_type ctype)
  2452. {
  2453. struct mem_cgroup *mem = NULL;
  2454. unsigned int nr_pages = 1;
  2455. struct page_cgroup *pc;
  2456. bool oom = true;
  2457. int ret;
  2458. if (PageTransHuge(page)) {
  2459. nr_pages <<= compound_order(page);
  2460. VM_BUG_ON(!PageTransHuge(page));
  2461. /*
  2462. * Never OOM-kill a process for a huge page. The
  2463. * fault handler will fall back to regular pages.
  2464. */
  2465. oom = false;
  2466. }
  2467. pc = lookup_page_cgroup(page);
  2468. BUG_ON(!pc); /* XXX: remove this and move pc lookup into commit */
  2469. ret = __mem_cgroup_try_charge(mm, gfp_mask, nr_pages, &mem, oom);
  2470. if (ret || !mem)
  2471. return ret;
  2472. __mem_cgroup_commit_charge(mem, page, nr_pages, pc, ctype);
  2473. return 0;
  2474. }
  2475. int mem_cgroup_newpage_charge(struct page *page,
  2476. struct mm_struct *mm, gfp_t gfp_mask)
  2477. {
  2478. if (mem_cgroup_disabled())
  2479. return 0;
  2480. /*
  2481. * If already mapped, we don't have to account.
  2482. * If page cache, page->mapping has address_space.
  2483. * But page->mapping may have out-of-use anon_vma pointer,
  2484. * detecit it by PageAnon() check. newly-mapped-anon's page->mapping
  2485. * is NULL.
  2486. */
  2487. if (page_mapped(page) || (page->mapping && !PageAnon(page)))
  2488. return 0;
  2489. if (unlikely(!mm))
  2490. mm = &init_mm;
  2491. return mem_cgroup_charge_common(page, mm, gfp_mask,
  2492. MEM_CGROUP_CHARGE_TYPE_MAPPED);
  2493. }
  2494. static void
  2495. __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
  2496. enum charge_type ctype);
  2497. static void
  2498. __mem_cgroup_commit_charge_lrucare(struct page *page, struct mem_cgroup *mem,
  2499. enum charge_type ctype)
  2500. {
  2501. struct page_cgroup *pc = lookup_page_cgroup(page);
  2502. /*
  2503. * In some case, SwapCache, FUSE(splice_buf->radixtree), the page
  2504. * is already on LRU. It means the page may on some other page_cgroup's
  2505. * LRU. Take care of it.
  2506. */
  2507. mem_cgroup_lru_del_before_commit(page);
  2508. __mem_cgroup_commit_charge(mem, page, 1, pc, ctype);
  2509. mem_cgroup_lru_add_after_commit(page);
  2510. return;
  2511. }
  2512. int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
  2513. gfp_t gfp_mask)
  2514. {
  2515. struct mem_cgroup *mem = NULL;
  2516. int ret;
  2517. if (mem_cgroup_disabled())
  2518. return 0;
  2519. if (PageCompound(page))
  2520. return 0;
  2521. if (unlikely(!mm))
  2522. mm = &init_mm;
  2523. if (page_is_file_cache(page)) {
  2524. ret = __mem_cgroup_try_charge(mm, gfp_mask, 1, &mem, true);
  2525. if (ret || !mem)
  2526. return ret;
  2527. /*
  2528. * FUSE reuses pages without going through the final
  2529. * put that would remove them from the LRU list, make
  2530. * sure that they get relinked properly.
  2531. */
  2532. __mem_cgroup_commit_charge_lrucare(page, mem,
  2533. MEM_CGROUP_CHARGE_TYPE_CACHE);
  2534. return ret;
  2535. }
  2536. /* shmem */
  2537. if (PageSwapCache(page)) {
  2538. ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &mem);
  2539. if (!ret)
  2540. __mem_cgroup_commit_charge_swapin(page, mem,
  2541. MEM_CGROUP_CHARGE_TYPE_SHMEM);
  2542. } else
  2543. ret = mem_cgroup_charge_common(page, mm, gfp_mask,
  2544. MEM_CGROUP_CHARGE_TYPE_SHMEM);
  2545. return ret;
  2546. }
  2547. /*
  2548. * While swap-in, try_charge -> commit or cancel, the page is locked.
  2549. * And when try_charge() successfully returns, one refcnt to memcg without
  2550. * struct page_cgroup is acquired. This refcnt will be consumed by
  2551. * "commit()" or removed by "cancel()"
  2552. */
  2553. int mem_cgroup_try_charge_swapin(struct mm_struct *mm,
  2554. struct page *page,
  2555. gfp_t mask, struct mem_cgroup **ptr)
  2556. {
  2557. struct mem_cgroup *mem;
  2558. int ret;
  2559. *ptr = NULL;
  2560. if (mem_cgroup_disabled())
  2561. return 0;
  2562. if (!do_swap_account)
  2563. goto charge_cur_mm;
  2564. /*
  2565. * A racing thread's fault, or swapoff, may have already updated
  2566. * the pte, and even removed page from swap cache: in those cases
  2567. * do_swap_page()'s pte_same() test will fail; but there's also a
  2568. * KSM case which does need to charge the page.
  2569. */
  2570. if (!PageSwapCache(page))
  2571. goto charge_cur_mm;
  2572. mem = try_get_mem_cgroup_from_page(page);
  2573. if (!mem)
  2574. goto charge_cur_mm;
  2575. *ptr = mem;
  2576. ret = __mem_cgroup_try_charge(NULL, mask, 1, ptr, true);
  2577. css_put(&mem->css);
  2578. return ret;
  2579. charge_cur_mm:
  2580. if (unlikely(!mm))
  2581. mm = &init_mm;
  2582. return __mem_cgroup_try_charge(mm, mask, 1, ptr, true);
  2583. }
  2584. static void
  2585. __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
  2586. enum charge_type ctype)
  2587. {
  2588. if (mem_cgroup_disabled())
  2589. return;
  2590. if (!ptr)
  2591. return;
  2592. cgroup_exclude_rmdir(&ptr->css);
  2593. __mem_cgroup_commit_charge_lrucare(page, ptr, ctype);
  2594. /*
  2595. * Now swap is on-memory. This means this page may be
  2596. * counted both as mem and swap....double count.
  2597. * Fix it by uncharging from memsw. Basically, this SwapCache is stable
  2598. * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
  2599. * may call delete_from_swap_cache() before reach here.
  2600. */
  2601. if (do_swap_account && PageSwapCache(page)) {
  2602. swp_entry_t ent = {.val = page_private(page)};
  2603. unsigned short id;
  2604. struct mem_cgroup *memcg;
  2605. id = swap_cgroup_record(ent, 0);
  2606. rcu_read_lock();
  2607. memcg = mem_cgroup_lookup(id);
  2608. if (memcg) {
  2609. /*
  2610. * This recorded memcg can be obsolete one. So, avoid
  2611. * calling css_tryget
  2612. */
  2613. if (!mem_cgroup_is_root(memcg))
  2614. res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
  2615. mem_cgroup_swap_statistics(memcg, false);
  2616. mem_cgroup_put(memcg);
  2617. }
  2618. rcu_read_unlock();
  2619. }
  2620. /*
  2621. * At swapin, we may charge account against cgroup which has no tasks.
  2622. * So, rmdir()->pre_destroy() can be called while we do this charge.
  2623. * In that case, we need to call pre_destroy() again. check it here.
  2624. */
  2625. cgroup_release_and_wakeup_rmdir(&ptr->css);
  2626. }
  2627. void mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr)
  2628. {
  2629. __mem_cgroup_commit_charge_swapin(page, ptr,
  2630. MEM_CGROUP_CHARGE_TYPE_MAPPED);
  2631. }
  2632. void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *mem)
  2633. {
  2634. if (mem_cgroup_disabled())
  2635. return;
  2636. if (!mem)
  2637. return;
  2638. __mem_cgroup_cancel_charge(mem, 1);
  2639. }
  2640. static void mem_cgroup_do_uncharge(struct mem_cgroup *mem,
  2641. unsigned int nr_pages,
  2642. const enum charge_type ctype)
  2643. {
  2644. struct memcg_batch_info *batch = NULL;
  2645. bool uncharge_memsw = true;
  2646. /* If swapout, usage of swap doesn't decrease */
  2647. if (!do_swap_account || ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
  2648. uncharge_memsw = false;
  2649. batch = &current->memcg_batch;
  2650. /*
  2651. * In usual, we do css_get() when we remember memcg pointer.
  2652. * But in this case, we keep res->usage until end of a series of
  2653. * uncharges. Then, it's ok to ignore memcg's refcnt.
  2654. */
  2655. if (!batch->memcg)
  2656. batch->memcg = mem;
  2657. /*
  2658. * do_batch > 0 when unmapping pages or inode invalidate/truncate.
  2659. * In those cases, all pages freed continuously can be expected to be in
  2660. * the same cgroup and we have chance to coalesce uncharges.
  2661. * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE)
  2662. * because we want to do uncharge as soon as possible.
  2663. */
  2664. if (!batch->do_batch || test_thread_flag(TIF_MEMDIE))
  2665. goto direct_uncharge;
  2666. if (nr_pages > 1)
  2667. goto direct_uncharge;
  2668. /*
  2669. * In typical case, batch->memcg == mem. This means we can
  2670. * merge a series of uncharges to an uncharge of res_counter.
  2671. * If not, we uncharge res_counter ony by one.
  2672. */
  2673. if (batch->memcg != mem)
  2674. goto direct_uncharge;
  2675. /* remember freed charge and uncharge it later */
  2676. batch->nr_pages++;
  2677. if (uncharge_memsw)
  2678. batch->memsw_nr_pages++;
  2679. return;
  2680. direct_uncharge:
  2681. res_counter_uncharge(&mem->res, nr_pages * PAGE_SIZE);
  2682. if (uncharge_memsw)
  2683. res_counter_uncharge(&mem->memsw, nr_pages * PAGE_SIZE);
  2684. if (unlikely(batch->memcg != mem))
  2685. memcg_oom_recover(mem);
  2686. return;
  2687. }
  2688. /*
  2689. * uncharge if !page_mapped(page)
  2690. */
  2691. static struct mem_cgroup *
  2692. __mem_cgroup_uncharge_common(struct page *page, enum charge_type ctype)
  2693. {
  2694. struct mem_cgroup *mem = NULL;
  2695. unsigned int nr_pages = 1;
  2696. struct page_cgroup *pc;
  2697. if (mem_cgroup_disabled())
  2698. return NULL;
  2699. if (PageSwapCache(page))
  2700. return NULL;
  2701. if (PageTransHuge(page)) {
  2702. nr_pages <<= compound_order(page);
  2703. VM_BUG_ON(!PageTransHuge(page));
  2704. }
  2705. /*
  2706. * Check if our page_cgroup is valid
  2707. */
  2708. pc = lookup_page_cgroup(page);
  2709. if (unlikely(!pc || !PageCgroupUsed(pc)))
  2710. return NULL;
  2711. lock_page_cgroup(pc);
  2712. mem = pc->mem_cgroup;
  2713. if (!PageCgroupUsed(pc))
  2714. goto unlock_out;
  2715. switch (ctype) {
  2716. case MEM_CGROUP_CHARGE_TYPE_MAPPED:
  2717. case MEM_CGROUP_CHARGE_TYPE_DROP:
  2718. /* See mem_cgroup_prepare_migration() */
  2719. if (page_mapped(page) || PageCgroupMigration(pc))
  2720. goto unlock_out;
  2721. break;
  2722. case MEM_CGROUP_CHARGE_TYPE_SWAPOUT:
  2723. if (!PageAnon(page)) { /* Shared memory */
  2724. if (page->mapping && !page_is_file_cache(page))
  2725. goto unlock_out;
  2726. } else if (page_mapped(page)) /* Anon */
  2727. goto unlock_out;
  2728. break;
  2729. default:
  2730. break;
  2731. }
  2732. mem_cgroup_charge_statistics(mem, PageCgroupCache(pc), -nr_pages);
  2733. ClearPageCgroupUsed(pc);
  2734. /*
  2735. * pc->mem_cgroup is not cleared here. It will be accessed when it's
  2736. * freed from LRU. This is safe because uncharged page is expected not
  2737. * to be reused (freed soon). Exception is SwapCache, it's handled by
  2738. * special functions.
  2739. */
  2740. unlock_page_cgroup(pc);
  2741. /*
  2742. * even after unlock, we have mem->res.usage here and this memcg
  2743. * will never be freed.
  2744. */
  2745. memcg_check_events(mem, page);
  2746. if (do_swap_account && ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT) {
  2747. mem_cgroup_swap_statistics(mem, true);
  2748. mem_cgroup_get(mem);
  2749. }
  2750. if (!mem_cgroup_is_root(mem))
  2751. mem_cgroup_do_uncharge(mem, nr_pages, ctype);
  2752. return mem;
  2753. unlock_out:
  2754. unlock_page_cgroup(pc);
  2755. return NULL;
  2756. }
  2757. void mem_cgroup_uncharge_page(struct page *page)
  2758. {
  2759. /* early check. */
  2760. if (page_mapped(page))
  2761. return;
  2762. if (page->mapping && !PageAnon(page))
  2763. return;
  2764. __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_MAPPED);
  2765. }
  2766. void mem_cgroup_uncharge_cache_page(struct page *page)
  2767. {
  2768. VM_BUG_ON(page_mapped(page));
  2769. VM_BUG_ON(page->mapping);
  2770. __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_CACHE);
  2771. }
  2772. /*
  2773. * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate.
  2774. * In that cases, pages are freed continuously and we can expect pages
  2775. * are in the same memcg. All these calls itself limits the number of
  2776. * pages freed at once, then uncharge_start/end() is called properly.
  2777. * This may be called prural(2) times in a context,
  2778. */
  2779. void mem_cgroup_uncharge_start(void)
  2780. {
  2781. current->memcg_batch.do_batch++;
  2782. /* We can do nest. */
  2783. if (current->memcg_batch.do_batch == 1) {
  2784. current->memcg_batch.memcg = NULL;
  2785. current->memcg_batch.nr_pages = 0;
  2786. current->memcg_batch.memsw_nr_pages = 0;
  2787. }
  2788. }
  2789. void mem_cgroup_uncharge_end(void)
  2790. {
  2791. struct memcg_batch_info *batch = &current->memcg_batch;
  2792. if (!batch->do_batch)
  2793. return;
  2794. batch->do_batch--;
  2795. if (batch->do_batch) /* If stacked, do nothing. */
  2796. return;
  2797. if (!batch->memcg)
  2798. return;
  2799. /*
  2800. * This "batch->memcg" is valid without any css_get/put etc...
  2801. * bacause we hide charges behind us.
  2802. */
  2803. if (batch->nr_pages)
  2804. res_counter_uncharge(&batch->memcg->res,
  2805. batch->nr_pages * PAGE_SIZE);
  2806. if (batch->memsw_nr_pages)
  2807. res_counter_uncharge(&batch->memcg->memsw,
  2808. batch->memsw_nr_pages * PAGE_SIZE);
  2809. memcg_oom_recover(batch->memcg);
  2810. /* forget this pointer (for sanity check) */
  2811. batch->memcg = NULL;
  2812. }
  2813. #ifdef CONFIG_SWAP
  2814. /*
  2815. * called after __delete_from_swap_cache() and drop "page" account.
  2816. * memcg information is recorded to swap_cgroup of "ent"
  2817. */
  2818. void
  2819. mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout)
  2820. {
  2821. struct mem_cgroup *memcg;
  2822. int ctype = MEM_CGROUP_CHARGE_TYPE_SWAPOUT;
  2823. if (!swapout) /* this was a swap cache but the swap is unused ! */
  2824. ctype = MEM_CGROUP_CHARGE_TYPE_DROP;
  2825. memcg = __mem_cgroup_uncharge_common(page, ctype);
  2826. /*
  2827. * record memcg information, if swapout && memcg != NULL,
  2828. * mem_cgroup_get() was called in uncharge().
  2829. */
  2830. if (do_swap_account && swapout && memcg)
  2831. swap_cgroup_record(ent, css_id(&memcg->css));
  2832. }
  2833. #endif
  2834. #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
  2835. /*
  2836. * called from swap_entry_free(). remove record in swap_cgroup and
  2837. * uncharge "memsw" account.
  2838. */
  2839. void mem_cgroup_uncharge_swap(swp_entry_t ent)
  2840. {
  2841. struct mem_cgroup *memcg;
  2842. unsigned short id;
  2843. if (!do_swap_account)
  2844. return;
  2845. id = swap_cgroup_record(ent, 0);
  2846. rcu_read_lock();
  2847. memcg = mem_cgroup_lookup(id);
  2848. if (memcg) {
  2849. /*
  2850. * We uncharge this because swap is freed.
  2851. * This memcg can be obsolete one. We avoid calling css_tryget
  2852. */
  2853. if (!mem_cgroup_is_root(memcg))
  2854. res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
  2855. mem_cgroup_swap_statistics(memcg, false);
  2856. mem_cgroup_put(memcg);
  2857. }
  2858. rcu_read_unlock();
  2859. }
  2860. /**
  2861. * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
  2862. * @entry: swap entry to be moved
  2863. * @from: mem_cgroup which the entry is moved from
  2864. * @to: mem_cgroup which the entry is moved to
  2865. * @need_fixup: whether we should fixup res_counters and refcounts.
  2866. *
  2867. * It succeeds only when the swap_cgroup's record for this entry is the same
  2868. * as the mem_cgroup's id of @from.
  2869. *
  2870. * Returns 0 on success, -EINVAL on failure.
  2871. *
  2872. * The caller must have charged to @to, IOW, called res_counter_charge() about
  2873. * both res and memsw, and called css_get().
  2874. */
  2875. static int mem_cgroup_move_swap_account(swp_entry_t entry,
  2876. struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
  2877. {
  2878. unsigned short old_id, new_id;
  2879. old_id = css_id(&from->css);
  2880. new_id = css_id(&to->css);
  2881. if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
  2882. mem_cgroup_swap_statistics(from, false);
  2883. mem_cgroup_swap_statistics(to, true);
  2884. /*
  2885. * This function is only called from task migration context now.
  2886. * It postpones res_counter and refcount handling till the end
  2887. * of task migration(mem_cgroup_clear_mc()) for performance
  2888. * improvement. But we cannot postpone mem_cgroup_get(to)
  2889. * because if the process that has been moved to @to does
  2890. * swap-in, the refcount of @to might be decreased to 0.
  2891. */
  2892. mem_cgroup_get(to);
  2893. if (need_fixup) {
  2894. if (!mem_cgroup_is_root(from))
  2895. res_counter_uncharge(&from->memsw, PAGE_SIZE);
  2896. mem_cgroup_put(from);
  2897. /*
  2898. * we charged both to->res and to->memsw, so we should
  2899. * uncharge to->res.
  2900. */
  2901. if (!mem_cgroup_is_root(to))
  2902. res_counter_uncharge(&to->res, PAGE_SIZE);
  2903. }
  2904. return 0;
  2905. }
  2906. return -EINVAL;
  2907. }
  2908. #else
  2909. static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
  2910. struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
  2911. {
  2912. return -EINVAL;
  2913. }
  2914. #endif
  2915. /*
  2916. * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
  2917. * page belongs to.
  2918. */
  2919. int mem_cgroup_prepare_migration(struct page *page,
  2920. struct page *newpage, struct mem_cgroup **ptr, gfp_t gfp_mask)
  2921. {
  2922. struct mem_cgroup *mem = NULL;
  2923. struct page_cgroup *pc;
  2924. enum charge_type ctype;
  2925. int ret = 0;
  2926. *ptr = NULL;
  2927. VM_BUG_ON(PageTransHuge(page));
  2928. if (mem_cgroup_disabled())
  2929. return 0;
  2930. pc = lookup_page_cgroup(page);
  2931. lock_page_cgroup(pc);
  2932. if (PageCgroupUsed(pc)) {
  2933. mem = pc->mem_cgroup;
  2934. css_get(&mem->css);
  2935. /*
  2936. * At migrating an anonymous page, its mapcount goes down
  2937. * to 0 and uncharge() will be called. But, even if it's fully
  2938. * unmapped, migration may fail and this page has to be
  2939. * charged again. We set MIGRATION flag here and delay uncharge
  2940. * until end_migration() is called
  2941. *
  2942. * Corner Case Thinking
  2943. * A)
  2944. * When the old page was mapped as Anon and it's unmap-and-freed
  2945. * while migration was ongoing.
  2946. * If unmap finds the old page, uncharge() of it will be delayed
  2947. * until end_migration(). If unmap finds a new page, it's
  2948. * uncharged when it make mapcount to be 1->0. If unmap code
  2949. * finds swap_migration_entry, the new page will not be mapped
  2950. * and end_migration() will find it(mapcount==0).
  2951. *
  2952. * B)
  2953. * When the old page was mapped but migraion fails, the kernel
  2954. * remaps it. A charge for it is kept by MIGRATION flag even
  2955. * if mapcount goes down to 0. We can do remap successfully
  2956. * without charging it again.
  2957. *
  2958. * C)
  2959. * The "old" page is under lock_page() until the end of
  2960. * migration, so, the old page itself will not be swapped-out.
  2961. * If the new page is swapped out before end_migraton, our
  2962. * hook to usual swap-out path will catch the event.
  2963. */
  2964. if (PageAnon(page))
  2965. SetPageCgroupMigration(pc);
  2966. }
  2967. unlock_page_cgroup(pc);
  2968. /*
  2969. * If the page is not charged at this point,
  2970. * we return here.
  2971. */
  2972. if (!mem)
  2973. return 0;
  2974. *ptr = mem;
  2975. ret = __mem_cgroup_try_charge(NULL, gfp_mask, 1, ptr, false);
  2976. css_put(&mem->css);/* drop extra refcnt */
  2977. if (ret || *ptr == NULL) {
  2978. if (PageAnon(page)) {
  2979. lock_page_cgroup(pc);
  2980. ClearPageCgroupMigration(pc);
  2981. unlock_page_cgroup(pc);
  2982. /*
  2983. * The old page may be fully unmapped while we kept it.
  2984. */
  2985. mem_cgroup_uncharge_page(page);
  2986. }
  2987. return -ENOMEM;
  2988. }
  2989. /*
  2990. * We charge new page before it's used/mapped. So, even if unlock_page()
  2991. * is called before end_migration, we can catch all events on this new
  2992. * page. In the case new page is migrated but not remapped, new page's
  2993. * mapcount will be finally 0 and we call uncharge in end_migration().
  2994. */
  2995. pc = lookup_page_cgroup(newpage);
  2996. if (PageAnon(page))
  2997. ctype = MEM_CGROUP_CHARGE_TYPE_MAPPED;
  2998. else if (page_is_file_cache(page))
  2999. ctype = MEM_CGROUP_CHARGE_TYPE_CACHE;
  3000. else
  3001. ctype = MEM_CGROUP_CHARGE_TYPE_SHMEM;
  3002. __mem_cgroup_commit_charge(mem, page, 1, pc, ctype);
  3003. return ret;
  3004. }
  3005. /* remove redundant charge if migration failed*/
  3006. void mem_cgroup_end_migration(struct mem_cgroup *mem,
  3007. struct page *oldpage, struct page *newpage, bool migration_ok)
  3008. {
  3009. struct page *used, *unused;
  3010. struct page_cgroup *pc;
  3011. if (!mem)
  3012. return;
  3013. /* blocks rmdir() */
  3014. cgroup_exclude_rmdir(&mem->css);
  3015. if (!migration_ok) {
  3016. used = oldpage;
  3017. unused = newpage;
  3018. } else {
  3019. used = newpage;
  3020. unused = oldpage;
  3021. }
  3022. /*
  3023. * We disallowed uncharge of pages under migration because mapcount
  3024. * of the page goes down to zero, temporarly.
  3025. * Clear the flag and check the page should be charged.
  3026. */
  3027. pc = lookup_page_cgroup(oldpage);
  3028. lock_page_cgroup(pc);
  3029. ClearPageCgroupMigration(pc);
  3030. unlock_page_cgroup(pc);
  3031. __mem_cgroup_uncharge_common(unused, MEM_CGROUP_CHARGE_TYPE_FORCE);
  3032. /*
  3033. * If a page is a file cache, radix-tree replacement is very atomic
  3034. * and we can skip this check. When it was an Anon page, its mapcount
  3035. * goes down to 0. But because we added MIGRATION flage, it's not
  3036. * uncharged yet. There are several case but page->mapcount check
  3037. * and USED bit check in mem_cgroup_uncharge_page() will do enough
  3038. * check. (see prepare_charge() also)
  3039. */
  3040. if (PageAnon(used))
  3041. mem_cgroup_uncharge_page(used);
  3042. /*
  3043. * At migration, we may charge account against cgroup which has no
  3044. * tasks.
  3045. * So, rmdir()->pre_destroy() can be called while we do this charge.
  3046. * In that case, we need to call pre_destroy() again. check it here.
  3047. */
  3048. cgroup_release_and_wakeup_rmdir(&mem->css);
  3049. }
  3050. #ifdef CONFIG_DEBUG_VM
  3051. static struct page_cgroup *lookup_page_cgroup_used(struct page *page)
  3052. {
  3053. struct page_cgroup *pc;
  3054. pc = lookup_page_cgroup(page);
  3055. if (likely(pc) && PageCgroupUsed(pc))
  3056. return pc;
  3057. return NULL;
  3058. }
  3059. bool mem_cgroup_bad_page_check(struct page *page)
  3060. {
  3061. if (mem_cgroup_disabled())
  3062. return false;
  3063. return lookup_page_cgroup_used(page) != NULL;
  3064. }
  3065. void mem_cgroup_print_bad_page(struct page *page)
  3066. {
  3067. struct page_cgroup *pc;
  3068. pc = lookup_page_cgroup_used(page);
  3069. if (pc) {
  3070. int ret = -1;
  3071. char *path;
  3072. printk(KERN_ALERT "pc:%p pc->flags:%lx pc->mem_cgroup:%p",
  3073. pc, pc->flags, pc->mem_cgroup);
  3074. path = kmalloc(PATH_MAX, GFP_KERNEL);
  3075. if (path) {
  3076. rcu_read_lock();
  3077. ret = cgroup_path(pc->mem_cgroup->css.cgroup,
  3078. path, PATH_MAX);
  3079. rcu_read_unlock();
  3080. }
  3081. printk(KERN_CONT "(%s)\n",
  3082. (ret < 0) ? "cannot get the path" : path);
  3083. kfree(path);
  3084. }
  3085. }
  3086. #endif
  3087. static DEFINE_MUTEX(set_limit_mutex);
  3088. static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
  3089. unsigned long long val)
  3090. {
  3091. int retry_count;
  3092. u64 memswlimit, memlimit;
  3093. int ret = 0;
  3094. int children = mem_cgroup_count_children(memcg);
  3095. u64 curusage, oldusage;
  3096. int enlarge;
  3097. /*
  3098. * For keeping hierarchical_reclaim simple, how long we should retry
  3099. * is depends on callers. We set our retry-count to be function
  3100. * of # of children which we should visit in this loop.
  3101. */
  3102. retry_count = MEM_CGROUP_RECLAIM_RETRIES * children;
  3103. oldusage = res_counter_read_u64(&memcg->res, RES_USAGE);
  3104. enlarge = 0;
  3105. while (retry_count) {
  3106. if (signal_pending(current)) {
  3107. ret = -EINTR;
  3108. break;
  3109. }
  3110. /*
  3111. * Rather than hide all in some function, I do this in
  3112. * open coded manner. You see what this really does.
  3113. * We have to guarantee mem->res.limit < mem->memsw.limit.
  3114. */
  3115. mutex_lock(&set_limit_mutex);
  3116. memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
  3117. if (memswlimit < val) {
  3118. ret = -EINVAL;
  3119. mutex_unlock(&set_limit_mutex);
  3120. break;
  3121. }
  3122. memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
  3123. if (memlimit < val)
  3124. enlarge = 1;
  3125. ret = res_counter_set_limit(&memcg->res, val);
  3126. if (!ret) {
  3127. if (memswlimit == val)
  3128. memcg->memsw_is_minimum = true;
  3129. else
  3130. memcg->memsw_is_minimum = false;
  3131. }
  3132. mutex_unlock(&set_limit_mutex);
  3133. if (!ret)
  3134. break;
  3135. mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
  3136. MEM_CGROUP_RECLAIM_SHRINK,
  3137. NULL);
  3138. curusage = res_counter_read_u64(&memcg->res, RES_USAGE);
  3139. /* Usage is reduced ? */
  3140. if (curusage >= oldusage)
  3141. retry_count--;
  3142. else
  3143. oldusage = curusage;
  3144. }
  3145. if (!ret && enlarge)
  3146. memcg_oom_recover(memcg);
  3147. return ret;
  3148. }
  3149. static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
  3150. unsigned long long val)
  3151. {
  3152. int retry_count;
  3153. u64 memlimit, memswlimit, oldusage, curusage;
  3154. int children = mem_cgroup_count_children(memcg);
  3155. int ret = -EBUSY;
  3156. int enlarge = 0;
  3157. /* see mem_cgroup_resize_res_limit */
  3158. retry_count = children * MEM_CGROUP_RECLAIM_RETRIES;
  3159. oldusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
  3160. while (retry_count) {
  3161. if (signal_pending(current)) {
  3162. ret = -EINTR;
  3163. break;
  3164. }
  3165. /*
  3166. * Rather than hide all in some function, I do this in
  3167. * open coded manner. You see what this really does.
  3168. * We have to guarantee mem->res.limit < mem->memsw.limit.
  3169. */
  3170. mutex_lock(&set_limit_mutex);
  3171. memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
  3172. if (memlimit > val) {
  3173. ret = -EINVAL;
  3174. mutex_unlock(&set_limit_mutex);
  3175. break;
  3176. }
  3177. memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
  3178. if (memswlimit < val)
  3179. enlarge = 1;
  3180. ret = res_counter_set_limit(&memcg->memsw, val);
  3181. if (!ret) {
  3182. if (memlimit == val)
  3183. memcg->memsw_is_minimum = true;
  3184. else
  3185. memcg->memsw_is_minimum = false;
  3186. }
  3187. mutex_unlock(&set_limit_mutex);
  3188. if (!ret)
  3189. break;
  3190. mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
  3191. MEM_CGROUP_RECLAIM_NOSWAP |
  3192. MEM_CGROUP_RECLAIM_SHRINK,
  3193. NULL);
  3194. curusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
  3195. /* Usage is reduced ? */
  3196. if (curusage >= oldusage)
  3197. retry_count--;
  3198. else
  3199. oldusage = curusage;
  3200. }
  3201. if (!ret && enlarge)
  3202. memcg_oom_recover(memcg);
  3203. return ret;
  3204. }
  3205. unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
  3206. gfp_t gfp_mask,
  3207. unsigned long *total_scanned)
  3208. {
  3209. unsigned long nr_reclaimed = 0;
  3210. struct mem_cgroup_per_zone *mz, *next_mz = NULL;
  3211. unsigned long reclaimed;
  3212. int loop = 0;
  3213. struct mem_cgroup_tree_per_zone *mctz;
  3214. unsigned long long excess;
  3215. unsigned long nr_scanned;
  3216. if (order > 0)
  3217. return 0;
  3218. mctz = soft_limit_tree_node_zone(zone_to_nid(zone), zone_idx(zone));
  3219. /*
  3220. * This loop can run a while, specially if mem_cgroup's continuously
  3221. * keep exceeding their soft limit and putting the system under
  3222. * pressure
  3223. */
  3224. do {
  3225. if (next_mz)
  3226. mz = next_mz;
  3227. else
  3228. mz = mem_cgroup_largest_soft_limit_node(mctz);
  3229. if (!mz)
  3230. break;
  3231. nr_scanned = 0;
  3232. reclaimed = mem_cgroup_hierarchical_reclaim(mz->mem, zone,
  3233. gfp_mask,
  3234. MEM_CGROUP_RECLAIM_SOFT,
  3235. &nr_scanned);
  3236. nr_reclaimed += reclaimed;
  3237. *total_scanned += nr_scanned;
  3238. spin_lock(&mctz->lock);
  3239. /*
  3240. * If we failed to reclaim anything from this memory cgroup
  3241. * it is time to move on to the next cgroup
  3242. */
  3243. next_mz = NULL;
  3244. if (!reclaimed) {
  3245. do {
  3246. /*
  3247. * Loop until we find yet another one.
  3248. *
  3249. * By the time we get the soft_limit lock
  3250. * again, someone might have aded the
  3251. * group back on the RB tree. Iterate to
  3252. * make sure we get a different mem.
  3253. * mem_cgroup_largest_soft_limit_node returns
  3254. * NULL if no other cgroup is present on
  3255. * the tree
  3256. */
  3257. next_mz =
  3258. __mem_cgroup_largest_soft_limit_node(mctz);
  3259. if (next_mz == mz)
  3260. css_put(&next_mz->mem->css);
  3261. else /* next_mz == NULL or other memcg */
  3262. break;
  3263. } while (1);
  3264. }
  3265. __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
  3266. excess = res_counter_soft_limit_excess(&mz->mem->res);
  3267. /*
  3268. * One school of thought says that we should not add
  3269. * back the node to the tree if reclaim returns 0.
  3270. * But our reclaim could return 0, simply because due
  3271. * to priority we are exposing a smaller subset of
  3272. * memory to reclaim from. Consider this as a longer
  3273. * term TODO.
  3274. */
  3275. /* If excess == 0, no tree ops */
  3276. __mem_cgroup_insert_exceeded(mz->mem, mz, mctz, excess);
  3277. spin_unlock(&mctz->lock);
  3278. css_put(&mz->mem->css);
  3279. loop++;
  3280. /*
  3281. * Could not reclaim anything and there are no more
  3282. * mem cgroups to try or we seem to be looping without
  3283. * reclaiming anything.
  3284. */
  3285. if (!nr_reclaimed &&
  3286. (next_mz == NULL ||
  3287. loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
  3288. break;
  3289. } while (!nr_reclaimed);
  3290. if (next_mz)
  3291. css_put(&next_mz->mem->css);
  3292. return nr_reclaimed;
  3293. }
  3294. /*
  3295. * This routine traverse page_cgroup in given list and drop them all.
  3296. * *And* this routine doesn't reclaim page itself, just removes page_cgroup.
  3297. */
  3298. static int mem_cgroup_force_empty_list(struct mem_cgroup *mem,
  3299. int node, int zid, enum lru_list lru)
  3300. {
  3301. struct zone *zone;
  3302. struct mem_cgroup_per_zone *mz;
  3303. struct page_cgroup *pc, *busy;
  3304. unsigned long flags, loop;
  3305. struct list_head *list;
  3306. int ret = 0;
  3307. zone = &NODE_DATA(node)->node_zones[zid];
  3308. mz = mem_cgroup_zoneinfo(mem, node, zid);
  3309. list = &mz->lists[lru];
  3310. loop = MEM_CGROUP_ZSTAT(mz, lru);
  3311. /* give some margin against EBUSY etc...*/
  3312. loop += 256;
  3313. busy = NULL;
  3314. while (loop--) {
  3315. struct page *page;
  3316. ret = 0;
  3317. spin_lock_irqsave(&zone->lru_lock, flags);
  3318. if (list_empty(list)) {
  3319. spin_unlock_irqrestore(&zone->lru_lock, flags);
  3320. break;
  3321. }
  3322. pc = list_entry(list->prev, struct page_cgroup, lru);
  3323. if (busy == pc) {
  3324. list_move(&pc->lru, list);
  3325. busy = NULL;
  3326. spin_unlock_irqrestore(&zone->lru_lock, flags);
  3327. continue;
  3328. }
  3329. spin_unlock_irqrestore(&zone->lru_lock, flags);
  3330. page = lookup_cgroup_page(pc);
  3331. ret = mem_cgroup_move_parent(page, pc, mem, GFP_KERNEL);
  3332. if (ret == -ENOMEM)
  3333. break;
  3334. if (ret == -EBUSY || ret == -EINVAL) {
  3335. /* found lock contention or "pc" is obsolete. */
  3336. busy = pc;
  3337. cond_resched();
  3338. } else
  3339. busy = NULL;
  3340. }
  3341. if (!ret && !list_empty(list))
  3342. return -EBUSY;
  3343. return ret;
  3344. }
  3345. /*
  3346. * make mem_cgroup's charge to be 0 if there is no task.
  3347. * This enables deleting this mem_cgroup.
  3348. */
  3349. static int mem_cgroup_force_empty(struct mem_cgroup *mem, bool free_all)
  3350. {
  3351. int ret;
  3352. int node, zid, shrink;
  3353. int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
  3354. struct cgroup *cgrp = mem->css.cgroup;
  3355. css_get(&mem->css);
  3356. shrink = 0;
  3357. /* should free all ? */
  3358. if (free_all)
  3359. goto try_to_free;
  3360. move_account:
  3361. do {
  3362. ret = -EBUSY;
  3363. if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children))
  3364. goto out;
  3365. ret = -EINTR;
  3366. if (signal_pending(current))
  3367. goto out;
  3368. /* This is for making all *used* pages to be on LRU. */
  3369. lru_add_drain_all();
  3370. drain_all_stock_sync(mem);
  3371. ret = 0;
  3372. mem_cgroup_start_move(mem);
  3373. for_each_node_state(node, N_HIGH_MEMORY) {
  3374. for (zid = 0; !ret && zid < MAX_NR_ZONES; zid++) {
  3375. enum lru_list l;
  3376. for_each_lru(l) {
  3377. ret = mem_cgroup_force_empty_list(mem,
  3378. node, zid, l);
  3379. if (ret)
  3380. break;
  3381. }
  3382. }
  3383. if (ret)
  3384. break;
  3385. }
  3386. mem_cgroup_end_move(mem);
  3387. memcg_oom_recover(mem);
  3388. /* it seems parent cgroup doesn't have enough mem */
  3389. if (ret == -ENOMEM)
  3390. goto try_to_free;
  3391. cond_resched();
  3392. /* "ret" should also be checked to ensure all lists are empty. */
  3393. } while (mem->res.usage > 0 || ret);
  3394. out:
  3395. css_put(&mem->css);
  3396. return ret;
  3397. try_to_free:
  3398. /* returns EBUSY if there is a task or if we come here twice. */
  3399. if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children) || shrink) {
  3400. ret = -EBUSY;
  3401. goto out;
  3402. }
  3403. /* we call try-to-free pages for make this cgroup empty */
  3404. lru_add_drain_all();
  3405. /* try to free all pages in this cgroup */
  3406. shrink = 1;
  3407. while (nr_retries && mem->res.usage > 0) {
  3408. struct memcg_scanrecord rec;
  3409. int progress;
  3410. if (signal_pending(current)) {
  3411. ret = -EINTR;
  3412. goto out;
  3413. }
  3414. rec.context = SCAN_BY_SHRINK;
  3415. rec.mem = mem;
  3416. rec.root = mem;
  3417. progress = try_to_free_mem_cgroup_pages(mem, GFP_KERNEL,
  3418. false, &rec);
  3419. if (!progress) {
  3420. nr_retries--;
  3421. /* maybe some writeback is necessary */
  3422. congestion_wait(BLK_RW_ASYNC, HZ/10);
  3423. }
  3424. }
  3425. lru_add_drain();
  3426. /* try move_account...there may be some *locked* pages. */
  3427. goto move_account;
  3428. }
  3429. int mem_cgroup_force_empty_write(struct cgroup *cont, unsigned int event)
  3430. {
  3431. return mem_cgroup_force_empty(mem_cgroup_from_cont(cont), true);
  3432. }
  3433. static u64 mem_cgroup_hierarchy_read(struct cgroup *cont, struct cftype *cft)
  3434. {
  3435. return mem_cgroup_from_cont(cont)->use_hierarchy;
  3436. }
  3437. static int mem_cgroup_hierarchy_write(struct cgroup *cont, struct cftype *cft,
  3438. u64 val)
  3439. {
  3440. int retval = 0;
  3441. struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
  3442. struct cgroup *parent = cont->parent;
  3443. struct mem_cgroup *parent_mem = NULL;
  3444. if (parent)
  3445. parent_mem = mem_cgroup_from_cont(parent);
  3446. cgroup_lock();
  3447. /*
  3448. * If parent's use_hierarchy is set, we can't make any modifications
  3449. * in the child subtrees. If it is unset, then the change can
  3450. * occur, provided the current cgroup has no children.
  3451. *
  3452. * For the root cgroup, parent_mem is NULL, we allow value to be
  3453. * set if there are no children.
  3454. */
  3455. if ((!parent_mem || !parent_mem->use_hierarchy) &&
  3456. (val == 1 || val == 0)) {
  3457. if (list_empty(&cont->children))
  3458. mem->use_hierarchy = val;
  3459. else
  3460. retval = -EBUSY;
  3461. } else
  3462. retval = -EINVAL;
  3463. cgroup_unlock();
  3464. return retval;
  3465. }
  3466. static unsigned long mem_cgroup_recursive_stat(struct mem_cgroup *mem,
  3467. enum mem_cgroup_stat_index idx)
  3468. {
  3469. struct mem_cgroup *iter;
  3470. long val = 0;
  3471. /* Per-cpu values can be negative, use a signed accumulator */
  3472. for_each_mem_cgroup_tree(iter, mem)
  3473. val += mem_cgroup_read_stat(iter, idx);
  3474. if (val < 0) /* race ? */
  3475. val = 0;
  3476. return val;
  3477. }
  3478. static inline u64 mem_cgroup_usage(struct mem_cgroup *mem, bool swap)
  3479. {
  3480. u64 val;
  3481. if (!mem_cgroup_is_root(mem)) {
  3482. if (!swap)
  3483. return res_counter_read_u64(&mem->res, RES_USAGE);
  3484. else
  3485. return res_counter_read_u64(&mem->memsw, RES_USAGE);
  3486. }
  3487. val = mem_cgroup_recursive_stat(mem, MEM_CGROUP_STAT_CACHE);
  3488. val += mem_cgroup_recursive_stat(mem, MEM_CGROUP_STAT_RSS);
  3489. if (swap)
  3490. val += mem_cgroup_recursive_stat(mem, MEM_CGROUP_STAT_SWAPOUT);
  3491. return val << PAGE_SHIFT;
  3492. }
  3493. static u64 mem_cgroup_read(struct cgroup *cont, struct cftype *cft)
  3494. {
  3495. struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
  3496. u64 val;
  3497. int type, name;
  3498. type = MEMFILE_TYPE(cft->private);
  3499. name = MEMFILE_ATTR(cft->private);
  3500. switch (type) {
  3501. case _MEM:
  3502. if (name == RES_USAGE)
  3503. val = mem_cgroup_usage(mem, false);
  3504. else
  3505. val = res_counter_read_u64(&mem->res, name);
  3506. break;
  3507. case _MEMSWAP:
  3508. if (name == RES_USAGE)
  3509. val = mem_cgroup_usage(mem, true);
  3510. else
  3511. val = res_counter_read_u64(&mem->memsw, name);
  3512. break;
  3513. default:
  3514. BUG();
  3515. break;
  3516. }
  3517. return val;
  3518. }
  3519. /*
  3520. * The user of this function is...
  3521. * RES_LIMIT.
  3522. */
  3523. static int mem_cgroup_write(struct cgroup *cont, struct cftype *cft,
  3524. const char *buffer)
  3525. {
  3526. struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
  3527. int type, name;
  3528. unsigned long long val;
  3529. int ret;
  3530. type = MEMFILE_TYPE(cft->private);
  3531. name = MEMFILE_ATTR(cft->private);
  3532. switch (name) {
  3533. case RES_LIMIT:
  3534. if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
  3535. ret = -EINVAL;
  3536. break;
  3537. }
  3538. /* This function does all necessary parse...reuse it */
  3539. ret = res_counter_memparse_write_strategy(buffer, &val);
  3540. if (ret)
  3541. break;
  3542. if (type == _MEM)
  3543. ret = mem_cgroup_resize_limit(memcg, val);
  3544. else
  3545. ret = mem_cgroup_resize_memsw_limit(memcg, val);
  3546. break;
  3547. case RES_SOFT_LIMIT:
  3548. ret = res_counter_memparse_write_strategy(buffer, &val);
  3549. if (ret)
  3550. break;
  3551. /*
  3552. * For memsw, soft limits are hard to implement in terms
  3553. * of semantics, for now, we support soft limits for
  3554. * control without swap
  3555. */
  3556. if (type == _MEM)
  3557. ret = res_counter_set_soft_limit(&memcg->res, val);
  3558. else
  3559. ret = -EINVAL;
  3560. break;
  3561. default:
  3562. ret = -EINVAL; /* should be BUG() ? */
  3563. break;
  3564. }
  3565. return ret;
  3566. }
  3567. static void memcg_get_hierarchical_limit(struct mem_cgroup *memcg,
  3568. unsigned long long *mem_limit, unsigned long long *memsw_limit)
  3569. {
  3570. struct cgroup *cgroup;
  3571. unsigned long long min_limit, min_memsw_limit, tmp;
  3572. min_limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
  3573. min_memsw_limit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
  3574. cgroup = memcg->css.cgroup;
  3575. if (!memcg->use_hierarchy)
  3576. goto out;
  3577. while (cgroup->parent) {
  3578. cgroup = cgroup->parent;
  3579. memcg = mem_cgroup_from_cont(cgroup);
  3580. if (!memcg->use_hierarchy)
  3581. break;
  3582. tmp = res_counter_read_u64(&memcg->res, RES_LIMIT);
  3583. min_limit = min(min_limit, tmp);
  3584. tmp = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
  3585. min_memsw_limit = min(min_memsw_limit, tmp);
  3586. }
  3587. out:
  3588. *mem_limit = min_limit;
  3589. *memsw_limit = min_memsw_limit;
  3590. return;
  3591. }
  3592. static int mem_cgroup_reset(struct cgroup *cont, unsigned int event)
  3593. {
  3594. struct mem_cgroup *mem;
  3595. int type, name;
  3596. mem = mem_cgroup_from_cont(cont);
  3597. type = MEMFILE_TYPE(event);
  3598. name = MEMFILE_ATTR(event);
  3599. switch (name) {
  3600. case RES_MAX_USAGE:
  3601. if (type == _MEM)
  3602. res_counter_reset_max(&mem->res);
  3603. else
  3604. res_counter_reset_max(&mem->memsw);
  3605. break;
  3606. case RES_FAILCNT:
  3607. if (type == _MEM)
  3608. res_counter_reset_failcnt(&mem->res);
  3609. else
  3610. res_counter_reset_failcnt(&mem->memsw);
  3611. break;
  3612. }
  3613. return 0;
  3614. }
  3615. static u64 mem_cgroup_move_charge_read(struct cgroup *cgrp,
  3616. struct cftype *cft)
  3617. {
  3618. return mem_cgroup_from_cont(cgrp)->move_charge_at_immigrate;
  3619. }
  3620. #ifdef CONFIG_MMU
  3621. static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
  3622. struct cftype *cft, u64 val)
  3623. {
  3624. struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
  3625. if (val >= (1 << NR_MOVE_TYPE))
  3626. return -EINVAL;
  3627. /*
  3628. * We check this value several times in both in can_attach() and
  3629. * attach(), so we need cgroup lock to prevent this value from being
  3630. * inconsistent.
  3631. */
  3632. cgroup_lock();
  3633. mem->move_charge_at_immigrate = val;
  3634. cgroup_unlock();
  3635. return 0;
  3636. }
  3637. #else
  3638. static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
  3639. struct cftype *cft, u64 val)
  3640. {
  3641. return -ENOSYS;
  3642. }
  3643. #endif
  3644. /* For read statistics */
  3645. enum {
  3646. MCS_CACHE,
  3647. MCS_RSS,
  3648. MCS_FILE_MAPPED,
  3649. MCS_PGPGIN,
  3650. MCS_PGPGOUT,
  3651. MCS_SWAP,
  3652. MCS_PGFAULT,
  3653. MCS_PGMAJFAULT,
  3654. MCS_INACTIVE_ANON,
  3655. MCS_ACTIVE_ANON,
  3656. MCS_INACTIVE_FILE,
  3657. MCS_ACTIVE_FILE,
  3658. MCS_UNEVICTABLE,
  3659. NR_MCS_STAT,
  3660. };
  3661. struct mcs_total_stat {
  3662. s64 stat[NR_MCS_STAT];
  3663. };
  3664. struct {
  3665. char *local_name;
  3666. char *total_name;
  3667. } memcg_stat_strings[NR_MCS_STAT] = {
  3668. {"cache", "total_cache"},
  3669. {"rss", "total_rss"},
  3670. {"mapped_file", "total_mapped_file"},
  3671. {"pgpgin", "total_pgpgin"},
  3672. {"pgpgout", "total_pgpgout"},
  3673. {"swap", "total_swap"},
  3674. {"pgfault", "total_pgfault"},
  3675. {"pgmajfault", "total_pgmajfault"},
  3676. {"inactive_anon", "total_inactive_anon"},
  3677. {"active_anon", "total_active_anon"},
  3678. {"inactive_file", "total_inactive_file"},
  3679. {"active_file", "total_active_file"},
  3680. {"unevictable", "total_unevictable"}
  3681. };
  3682. static void
  3683. mem_cgroup_get_local_stat(struct mem_cgroup *mem, struct mcs_total_stat *s)
  3684. {
  3685. s64 val;
  3686. /* per cpu stat */
  3687. val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_CACHE);
  3688. s->stat[MCS_CACHE] += val * PAGE_SIZE;
  3689. val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_RSS);
  3690. s->stat[MCS_RSS] += val * PAGE_SIZE;
  3691. val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_FILE_MAPPED);
  3692. s->stat[MCS_FILE_MAPPED] += val * PAGE_SIZE;
  3693. val = mem_cgroup_read_events(mem, MEM_CGROUP_EVENTS_PGPGIN);
  3694. s->stat[MCS_PGPGIN] += val;
  3695. val = mem_cgroup_read_events(mem, MEM_CGROUP_EVENTS_PGPGOUT);
  3696. s->stat[MCS_PGPGOUT] += val;
  3697. if (do_swap_account) {
  3698. val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_SWAPOUT);
  3699. s->stat[MCS_SWAP] += val * PAGE_SIZE;
  3700. }
  3701. val = mem_cgroup_read_events(mem, MEM_CGROUP_EVENTS_PGFAULT);
  3702. s->stat[MCS_PGFAULT] += val;
  3703. val = mem_cgroup_read_events(mem, MEM_CGROUP_EVENTS_PGMAJFAULT);
  3704. s->stat[MCS_PGMAJFAULT] += val;
  3705. /* per zone stat */
  3706. val = mem_cgroup_nr_lru_pages(mem, BIT(LRU_INACTIVE_ANON));
  3707. s->stat[MCS_INACTIVE_ANON] += val * PAGE_SIZE;
  3708. val = mem_cgroup_nr_lru_pages(mem, BIT(LRU_ACTIVE_ANON));
  3709. s->stat[MCS_ACTIVE_ANON] += val * PAGE_SIZE;
  3710. val = mem_cgroup_nr_lru_pages(mem, BIT(LRU_INACTIVE_FILE));
  3711. s->stat[MCS_INACTIVE_FILE] += val * PAGE_SIZE;
  3712. val = mem_cgroup_nr_lru_pages(mem, BIT(LRU_ACTIVE_FILE));
  3713. s->stat[MCS_ACTIVE_FILE] += val * PAGE_SIZE;
  3714. val = mem_cgroup_nr_lru_pages(mem, BIT(LRU_UNEVICTABLE));
  3715. s->stat[MCS_UNEVICTABLE] += val * PAGE_SIZE;
  3716. }
  3717. static void
  3718. mem_cgroup_get_total_stat(struct mem_cgroup *mem, struct mcs_total_stat *s)
  3719. {
  3720. struct mem_cgroup *iter;
  3721. for_each_mem_cgroup_tree(iter, mem)
  3722. mem_cgroup_get_local_stat(iter, s);
  3723. }
  3724. #ifdef CONFIG_NUMA
  3725. static int mem_control_numa_stat_show(struct seq_file *m, void *arg)
  3726. {
  3727. int nid;
  3728. unsigned long total_nr, file_nr, anon_nr, unevictable_nr;
  3729. unsigned long node_nr;
  3730. struct cgroup *cont = m->private;
  3731. struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
  3732. total_nr = mem_cgroup_nr_lru_pages(mem_cont, LRU_ALL);
  3733. seq_printf(m, "total=%lu", total_nr);
  3734. for_each_node_state(nid, N_HIGH_MEMORY) {
  3735. node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid, LRU_ALL);
  3736. seq_printf(m, " N%d=%lu", nid, node_nr);
  3737. }
  3738. seq_putc(m, '\n');
  3739. file_nr = mem_cgroup_nr_lru_pages(mem_cont, LRU_ALL_FILE);
  3740. seq_printf(m, "file=%lu", file_nr);
  3741. for_each_node_state(nid, N_HIGH_MEMORY) {
  3742. node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid,
  3743. LRU_ALL_FILE);
  3744. seq_printf(m, " N%d=%lu", nid, node_nr);
  3745. }
  3746. seq_putc(m, '\n');
  3747. anon_nr = mem_cgroup_nr_lru_pages(mem_cont, LRU_ALL_ANON);
  3748. seq_printf(m, "anon=%lu", anon_nr);
  3749. for_each_node_state(nid, N_HIGH_MEMORY) {
  3750. node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid,
  3751. LRU_ALL_ANON);
  3752. seq_printf(m, " N%d=%lu", nid, node_nr);
  3753. }
  3754. seq_putc(m, '\n');
  3755. unevictable_nr = mem_cgroup_nr_lru_pages(mem_cont, BIT(LRU_UNEVICTABLE));
  3756. seq_printf(m, "unevictable=%lu", unevictable_nr);
  3757. for_each_node_state(nid, N_HIGH_MEMORY) {
  3758. node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid,
  3759. BIT(LRU_UNEVICTABLE));
  3760. seq_printf(m, " N%d=%lu", nid, node_nr);
  3761. }
  3762. seq_putc(m, '\n');
  3763. return 0;
  3764. }
  3765. #endif /* CONFIG_NUMA */
  3766. static int mem_control_stat_show(struct cgroup *cont, struct cftype *cft,
  3767. struct cgroup_map_cb *cb)
  3768. {
  3769. struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
  3770. struct mcs_total_stat mystat;
  3771. int i;
  3772. memset(&mystat, 0, sizeof(mystat));
  3773. mem_cgroup_get_local_stat(mem_cont, &mystat);
  3774. for (i = 0; i < NR_MCS_STAT; i++) {
  3775. if (i == MCS_SWAP && !do_swap_account)
  3776. continue;
  3777. cb->fill(cb, memcg_stat_strings[i].local_name, mystat.stat[i]);
  3778. }
  3779. /* Hierarchical information */
  3780. {
  3781. unsigned long long limit, memsw_limit;
  3782. memcg_get_hierarchical_limit(mem_cont, &limit, &memsw_limit);
  3783. cb->fill(cb, "hierarchical_memory_limit", limit);
  3784. if (do_swap_account)
  3785. cb->fill(cb, "hierarchical_memsw_limit", memsw_limit);
  3786. }
  3787. memset(&mystat, 0, sizeof(mystat));
  3788. mem_cgroup_get_total_stat(mem_cont, &mystat);
  3789. for (i = 0; i < NR_MCS_STAT; i++) {
  3790. if (i == MCS_SWAP && !do_swap_account)
  3791. continue;
  3792. cb->fill(cb, memcg_stat_strings[i].total_name, mystat.stat[i]);
  3793. }
  3794. #ifdef CONFIG_DEBUG_VM
  3795. cb->fill(cb, "inactive_ratio", calc_inactive_ratio(mem_cont, NULL));
  3796. {
  3797. int nid, zid;
  3798. struct mem_cgroup_per_zone *mz;
  3799. unsigned long recent_rotated[2] = {0, 0};
  3800. unsigned long recent_scanned[2] = {0, 0};
  3801. for_each_online_node(nid)
  3802. for (zid = 0; zid < MAX_NR_ZONES; zid++) {
  3803. mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
  3804. recent_rotated[0] +=
  3805. mz->reclaim_stat.recent_rotated[0];
  3806. recent_rotated[1] +=
  3807. mz->reclaim_stat.recent_rotated[1];
  3808. recent_scanned[0] +=
  3809. mz->reclaim_stat.recent_scanned[0];
  3810. recent_scanned[1] +=
  3811. mz->reclaim_stat.recent_scanned[1];
  3812. }
  3813. cb->fill(cb, "recent_rotated_anon", recent_rotated[0]);
  3814. cb->fill(cb, "recent_rotated_file", recent_rotated[1]);
  3815. cb->fill(cb, "recent_scanned_anon", recent_scanned[0]);
  3816. cb->fill(cb, "recent_scanned_file", recent_scanned[1]);
  3817. }
  3818. #endif
  3819. return 0;
  3820. }
  3821. static u64 mem_cgroup_swappiness_read(struct cgroup *cgrp, struct cftype *cft)
  3822. {
  3823. struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
  3824. return mem_cgroup_swappiness(memcg);
  3825. }
  3826. static int mem_cgroup_swappiness_write(struct cgroup *cgrp, struct cftype *cft,
  3827. u64 val)
  3828. {
  3829. struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
  3830. struct mem_cgroup *parent;
  3831. if (val > 100)
  3832. return -EINVAL;
  3833. if (cgrp->parent == NULL)
  3834. return -EINVAL;
  3835. parent = mem_cgroup_from_cont(cgrp->parent);
  3836. cgroup_lock();
  3837. /* If under hierarchy, only empty-root can set this value */
  3838. if ((parent->use_hierarchy) ||
  3839. (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
  3840. cgroup_unlock();
  3841. return -EINVAL;
  3842. }
  3843. memcg->swappiness = val;
  3844. cgroup_unlock();
  3845. return 0;
  3846. }
  3847. static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
  3848. {
  3849. struct mem_cgroup_threshold_ary *t;
  3850. u64 usage;
  3851. int i;
  3852. rcu_read_lock();
  3853. if (!swap)
  3854. t = rcu_dereference(memcg->thresholds.primary);
  3855. else
  3856. t = rcu_dereference(memcg->memsw_thresholds.primary);
  3857. if (!t)
  3858. goto unlock;
  3859. usage = mem_cgroup_usage(memcg, swap);
  3860. /*
  3861. * current_threshold points to threshold just below usage.
  3862. * If it's not true, a threshold was crossed after last
  3863. * call of __mem_cgroup_threshold().
  3864. */
  3865. i = t->current_threshold;
  3866. /*
  3867. * Iterate backward over array of thresholds starting from
  3868. * current_threshold and check if a threshold is crossed.
  3869. * If none of thresholds below usage is crossed, we read
  3870. * only one element of the array here.
  3871. */
  3872. for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
  3873. eventfd_signal(t->entries[i].eventfd, 1);
  3874. /* i = current_threshold + 1 */
  3875. i++;
  3876. /*
  3877. * Iterate forward over array of thresholds starting from
  3878. * current_threshold+1 and check if a threshold is crossed.
  3879. * If none of thresholds above usage is crossed, we read
  3880. * only one element of the array here.
  3881. */
  3882. for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
  3883. eventfd_signal(t->entries[i].eventfd, 1);
  3884. /* Update current_threshold */
  3885. t->current_threshold = i - 1;
  3886. unlock:
  3887. rcu_read_unlock();
  3888. }
  3889. static void mem_cgroup_threshold(struct mem_cgroup *memcg)
  3890. {
  3891. while (memcg) {
  3892. __mem_cgroup_threshold(memcg, false);
  3893. if (do_swap_account)
  3894. __mem_cgroup_threshold(memcg, true);
  3895. memcg = parent_mem_cgroup(memcg);
  3896. }
  3897. }
  3898. static int compare_thresholds(const void *a, const void *b)
  3899. {
  3900. const struct mem_cgroup_threshold *_a = a;
  3901. const struct mem_cgroup_threshold *_b = b;
  3902. return _a->threshold - _b->threshold;
  3903. }
  3904. static int mem_cgroup_oom_notify_cb(struct mem_cgroup *mem)
  3905. {
  3906. struct mem_cgroup_eventfd_list *ev;
  3907. list_for_each_entry(ev, &mem->oom_notify, list)
  3908. eventfd_signal(ev->eventfd, 1);
  3909. return 0;
  3910. }
  3911. static void mem_cgroup_oom_notify(struct mem_cgroup *mem)
  3912. {
  3913. struct mem_cgroup *iter;
  3914. for_each_mem_cgroup_tree(iter, mem)
  3915. mem_cgroup_oom_notify_cb(iter);
  3916. }
  3917. static int mem_cgroup_usage_register_event(struct cgroup *cgrp,
  3918. struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
  3919. {
  3920. struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
  3921. struct mem_cgroup_thresholds *thresholds;
  3922. struct mem_cgroup_threshold_ary *new;
  3923. int type = MEMFILE_TYPE(cft->private);
  3924. u64 threshold, usage;
  3925. int i, size, ret;
  3926. ret = res_counter_memparse_write_strategy(args, &threshold);
  3927. if (ret)
  3928. return ret;
  3929. mutex_lock(&memcg->thresholds_lock);
  3930. if (type == _MEM)
  3931. thresholds = &memcg->thresholds;
  3932. else if (type == _MEMSWAP)
  3933. thresholds = &memcg->memsw_thresholds;
  3934. else
  3935. BUG();
  3936. usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
  3937. /* Check if a threshold crossed before adding a new one */
  3938. if (thresholds->primary)
  3939. __mem_cgroup_threshold(memcg, type == _MEMSWAP);
  3940. size = thresholds->primary ? thresholds->primary->size + 1 : 1;
  3941. /* Allocate memory for new array of thresholds */
  3942. new = kmalloc(sizeof(*new) + size * sizeof(struct mem_cgroup_threshold),
  3943. GFP_KERNEL);
  3944. if (!new) {
  3945. ret = -ENOMEM;
  3946. goto unlock;
  3947. }
  3948. new->size = size;
  3949. /* Copy thresholds (if any) to new array */
  3950. if (thresholds->primary) {
  3951. memcpy(new->entries, thresholds->primary->entries, (size - 1) *
  3952. sizeof(struct mem_cgroup_threshold));
  3953. }
  3954. /* Add new threshold */
  3955. new->entries[size - 1].eventfd = eventfd;
  3956. new->entries[size - 1].threshold = threshold;
  3957. /* Sort thresholds. Registering of new threshold isn't time-critical */
  3958. sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
  3959. compare_thresholds, NULL);
  3960. /* Find current threshold */
  3961. new->current_threshold = -1;
  3962. for (i = 0; i < size; i++) {
  3963. if (new->entries[i].threshold < usage) {
  3964. /*
  3965. * new->current_threshold will not be used until
  3966. * rcu_assign_pointer(), so it's safe to increment
  3967. * it here.
  3968. */
  3969. ++new->current_threshold;
  3970. }
  3971. }
  3972. /* Free old spare buffer and save old primary buffer as spare */
  3973. kfree(thresholds->spare);
  3974. thresholds->spare = thresholds->primary;
  3975. rcu_assign_pointer(thresholds->primary, new);
  3976. /* To be sure that nobody uses thresholds */
  3977. synchronize_rcu();
  3978. unlock:
  3979. mutex_unlock(&memcg->thresholds_lock);
  3980. return ret;
  3981. }
  3982. static void mem_cgroup_usage_unregister_event(struct cgroup *cgrp,
  3983. struct cftype *cft, struct eventfd_ctx *eventfd)
  3984. {
  3985. struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
  3986. struct mem_cgroup_thresholds *thresholds;
  3987. struct mem_cgroup_threshold_ary *new;
  3988. int type = MEMFILE_TYPE(cft->private);
  3989. u64 usage;
  3990. int i, j, size;
  3991. mutex_lock(&memcg->thresholds_lock);
  3992. if (type == _MEM)
  3993. thresholds = &memcg->thresholds;
  3994. else if (type == _MEMSWAP)
  3995. thresholds = &memcg->memsw_thresholds;
  3996. else
  3997. BUG();
  3998. /*
  3999. * Something went wrong if we trying to unregister a threshold
  4000. * if we don't have thresholds
  4001. */
  4002. BUG_ON(!thresholds);
  4003. usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
  4004. /* Check if a threshold crossed before removing */
  4005. __mem_cgroup_threshold(memcg, type == _MEMSWAP);
  4006. /* Calculate new number of threshold */
  4007. size = 0;
  4008. for (i = 0; i < thresholds->primary->size; i++) {
  4009. if (thresholds->primary->entries[i].eventfd != eventfd)
  4010. size++;
  4011. }
  4012. new = thresholds->spare;
  4013. /* Set thresholds array to NULL if we don't have thresholds */
  4014. if (!size) {
  4015. kfree(new);
  4016. new = NULL;
  4017. goto swap_buffers;
  4018. }
  4019. new->size = size;
  4020. /* Copy thresholds and find current threshold */
  4021. new->current_threshold = -1;
  4022. for (i = 0, j = 0; i < thresholds->primary->size; i++) {
  4023. if (thresholds->primary->entries[i].eventfd == eventfd)
  4024. continue;
  4025. new->entries[j] = thresholds->primary->entries[i];
  4026. if (new->entries[j].threshold < usage) {
  4027. /*
  4028. * new->current_threshold will not be used
  4029. * until rcu_assign_pointer(), so it's safe to increment
  4030. * it here.
  4031. */
  4032. ++new->current_threshold;
  4033. }
  4034. j++;
  4035. }
  4036. swap_buffers:
  4037. /* Swap primary and spare array */
  4038. thresholds->spare = thresholds->primary;
  4039. rcu_assign_pointer(thresholds->primary, new);
  4040. /* To be sure that nobody uses thresholds */
  4041. synchronize_rcu();
  4042. mutex_unlock(&memcg->thresholds_lock);
  4043. }
  4044. static int mem_cgroup_oom_register_event(struct cgroup *cgrp,
  4045. struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
  4046. {
  4047. struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
  4048. struct mem_cgroup_eventfd_list *event;
  4049. int type = MEMFILE_TYPE(cft->private);
  4050. BUG_ON(type != _OOM_TYPE);
  4051. event = kmalloc(sizeof(*event), GFP_KERNEL);
  4052. if (!event)
  4053. return -ENOMEM;
  4054. spin_lock(&memcg_oom_lock);
  4055. event->eventfd = eventfd;
  4056. list_add(&event->list, &memcg->oom_notify);
  4057. /* already in OOM ? */
  4058. if (atomic_read(&memcg->under_oom))
  4059. eventfd_signal(eventfd, 1);
  4060. spin_unlock(&memcg_oom_lock);
  4061. return 0;
  4062. }
  4063. static void mem_cgroup_oom_unregister_event(struct cgroup *cgrp,
  4064. struct cftype *cft, struct eventfd_ctx *eventfd)
  4065. {
  4066. struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
  4067. struct mem_cgroup_eventfd_list *ev, *tmp;
  4068. int type = MEMFILE_TYPE(cft->private);
  4069. BUG_ON(type != _OOM_TYPE);
  4070. spin_lock(&memcg_oom_lock);
  4071. list_for_each_entry_safe(ev, tmp, &mem->oom_notify, list) {
  4072. if (ev->eventfd == eventfd) {
  4073. list_del(&ev->list);
  4074. kfree(ev);
  4075. }
  4076. }
  4077. spin_unlock(&memcg_oom_lock);
  4078. }
  4079. static int mem_cgroup_oom_control_read(struct cgroup *cgrp,
  4080. struct cftype *cft, struct cgroup_map_cb *cb)
  4081. {
  4082. struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
  4083. cb->fill(cb, "oom_kill_disable", mem->oom_kill_disable);
  4084. if (atomic_read(&mem->under_oom))
  4085. cb->fill(cb, "under_oom", 1);
  4086. else
  4087. cb->fill(cb, "under_oom", 0);
  4088. return 0;
  4089. }
  4090. static int mem_cgroup_oom_control_write(struct cgroup *cgrp,
  4091. struct cftype *cft, u64 val)
  4092. {
  4093. struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
  4094. struct mem_cgroup *parent;
  4095. /* cannot set to root cgroup and only 0 and 1 are allowed */
  4096. if (!cgrp->parent || !((val == 0) || (val == 1)))
  4097. return -EINVAL;
  4098. parent = mem_cgroup_from_cont(cgrp->parent);
  4099. cgroup_lock();
  4100. /* oom-kill-disable is a flag for subhierarchy. */
  4101. if ((parent->use_hierarchy) ||
  4102. (mem->use_hierarchy && !list_empty(&cgrp->children))) {
  4103. cgroup_unlock();
  4104. return -EINVAL;
  4105. }
  4106. mem->oom_kill_disable = val;
  4107. if (!val)
  4108. memcg_oom_recover(mem);
  4109. cgroup_unlock();
  4110. return 0;
  4111. }
  4112. #ifdef CONFIG_NUMA
  4113. static const struct file_operations mem_control_numa_stat_file_operations = {
  4114. .read = seq_read,
  4115. .llseek = seq_lseek,
  4116. .release = single_release,
  4117. };
  4118. static int mem_control_numa_stat_open(struct inode *unused, struct file *file)
  4119. {
  4120. struct cgroup *cont = file->f_dentry->d_parent->d_fsdata;
  4121. file->f_op = &mem_control_numa_stat_file_operations;
  4122. return single_open(file, mem_control_numa_stat_show, cont);
  4123. }
  4124. #endif /* CONFIG_NUMA */
  4125. static int mem_cgroup_vmscan_stat_read(struct cgroup *cgrp,
  4126. struct cftype *cft,
  4127. struct cgroup_map_cb *cb)
  4128. {
  4129. struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
  4130. char string[64];
  4131. int i;
  4132. for (i = 0; i < NR_SCANSTATS; i++) {
  4133. strcpy(string, scanstat_string[i]);
  4134. strcat(string, SCANSTAT_WORD_LIMIT);
  4135. cb->fill(cb, string, mem->scanstat.stats[SCAN_BY_LIMIT][i]);
  4136. }
  4137. for (i = 0; i < NR_SCANSTATS; i++) {
  4138. strcpy(string, scanstat_string[i]);
  4139. strcat(string, SCANSTAT_WORD_SYSTEM);
  4140. cb->fill(cb, string, mem->scanstat.stats[SCAN_BY_SYSTEM][i]);
  4141. }
  4142. for (i = 0; i < NR_SCANSTATS; i++) {
  4143. strcpy(string, scanstat_string[i]);
  4144. strcat(string, SCANSTAT_WORD_LIMIT);
  4145. strcat(string, SCANSTAT_WORD_HIERARCHY);
  4146. cb->fill(cb, string, mem->scanstat.rootstats[SCAN_BY_LIMIT][i]);
  4147. }
  4148. for (i = 0; i < NR_SCANSTATS; i++) {
  4149. strcpy(string, scanstat_string[i]);
  4150. strcat(string, SCANSTAT_WORD_SYSTEM);
  4151. strcat(string, SCANSTAT_WORD_HIERARCHY);
  4152. cb->fill(cb, string, mem->scanstat.rootstats[SCAN_BY_SYSTEM][i]);
  4153. }
  4154. return 0;
  4155. }
  4156. static int mem_cgroup_reset_vmscan_stat(struct cgroup *cgrp,
  4157. unsigned int event)
  4158. {
  4159. struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
  4160. spin_lock(&mem->scanstat.lock);
  4161. memset(&mem->scanstat.stats, 0, sizeof(mem->scanstat.stats));
  4162. memset(&mem->scanstat.rootstats, 0, sizeof(mem->scanstat.rootstats));
  4163. spin_unlock(&mem->scanstat.lock);
  4164. return 0;
  4165. }
  4166. static struct cftype mem_cgroup_files[] = {
  4167. {
  4168. .name = "usage_in_bytes",
  4169. .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
  4170. .read_u64 = mem_cgroup_read,
  4171. .register_event = mem_cgroup_usage_register_event,
  4172. .unregister_event = mem_cgroup_usage_unregister_event,
  4173. },
  4174. {
  4175. .name = "max_usage_in_bytes",
  4176. .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
  4177. .trigger = mem_cgroup_reset,
  4178. .read_u64 = mem_cgroup_read,
  4179. },
  4180. {
  4181. .name = "limit_in_bytes",
  4182. .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
  4183. .write_string = mem_cgroup_write,
  4184. .read_u64 = mem_cgroup_read,
  4185. },
  4186. {
  4187. .name = "soft_limit_in_bytes",
  4188. .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
  4189. .write_string = mem_cgroup_write,
  4190. .read_u64 = mem_cgroup_read,
  4191. },
  4192. {
  4193. .name = "failcnt",
  4194. .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
  4195. .trigger = mem_cgroup_reset,
  4196. .read_u64 = mem_cgroup_read,
  4197. },
  4198. {
  4199. .name = "stat",
  4200. .read_map = mem_control_stat_show,
  4201. },
  4202. {
  4203. .name = "force_empty",
  4204. .trigger = mem_cgroup_force_empty_write,
  4205. },
  4206. {
  4207. .name = "use_hierarchy",
  4208. .write_u64 = mem_cgroup_hierarchy_write,
  4209. .read_u64 = mem_cgroup_hierarchy_read,
  4210. },
  4211. {
  4212. .name = "swappiness",
  4213. .read_u64 = mem_cgroup_swappiness_read,
  4214. .write_u64 = mem_cgroup_swappiness_write,
  4215. },
  4216. {
  4217. .name = "move_charge_at_immigrate",
  4218. .read_u64 = mem_cgroup_move_charge_read,
  4219. .write_u64 = mem_cgroup_move_charge_write,
  4220. },
  4221. {
  4222. .name = "oom_control",
  4223. .read_map = mem_cgroup_oom_control_read,
  4224. .write_u64 = mem_cgroup_oom_control_write,
  4225. .register_event = mem_cgroup_oom_register_event,
  4226. .unregister_event = mem_cgroup_oom_unregister_event,
  4227. .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
  4228. },
  4229. #ifdef CONFIG_NUMA
  4230. {
  4231. .name = "numa_stat",
  4232. .open = mem_control_numa_stat_open,
  4233. .mode = S_IRUGO,
  4234. },
  4235. #endif
  4236. {
  4237. .name = "vmscan_stat",
  4238. .read_map = mem_cgroup_vmscan_stat_read,
  4239. .trigger = mem_cgroup_reset_vmscan_stat,
  4240. },
  4241. };
  4242. #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
  4243. static struct cftype memsw_cgroup_files[] = {
  4244. {
  4245. .name = "memsw.usage_in_bytes",
  4246. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
  4247. .read_u64 = mem_cgroup_read,
  4248. .register_event = mem_cgroup_usage_register_event,
  4249. .unregister_event = mem_cgroup_usage_unregister_event,
  4250. },
  4251. {
  4252. .name = "memsw.max_usage_in_bytes",
  4253. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
  4254. .trigger = mem_cgroup_reset,
  4255. .read_u64 = mem_cgroup_read,
  4256. },
  4257. {
  4258. .name = "memsw.limit_in_bytes",
  4259. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
  4260. .write_string = mem_cgroup_write,
  4261. .read_u64 = mem_cgroup_read,
  4262. },
  4263. {
  4264. .name = "memsw.failcnt",
  4265. .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
  4266. .trigger = mem_cgroup_reset,
  4267. .read_u64 = mem_cgroup_read,
  4268. },
  4269. };
  4270. static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
  4271. {
  4272. if (!do_swap_account)
  4273. return 0;
  4274. return cgroup_add_files(cont, ss, memsw_cgroup_files,
  4275. ARRAY_SIZE(memsw_cgroup_files));
  4276. };
  4277. #else
  4278. static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
  4279. {
  4280. return 0;
  4281. }
  4282. #endif
  4283. static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
  4284. {
  4285. struct mem_cgroup_per_node *pn;
  4286. struct mem_cgroup_per_zone *mz;
  4287. enum lru_list l;
  4288. int zone, tmp = node;
  4289. /*
  4290. * This routine is called against possible nodes.
  4291. * But it's BUG to call kmalloc() against offline node.
  4292. *
  4293. * TODO: this routine can waste much memory for nodes which will
  4294. * never be onlined. It's better to use memory hotplug callback
  4295. * function.
  4296. */
  4297. if (!node_state(node, N_NORMAL_MEMORY))
  4298. tmp = -1;
  4299. pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
  4300. if (!pn)
  4301. return 1;
  4302. mem->info.nodeinfo[node] = pn;
  4303. for (zone = 0; zone < MAX_NR_ZONES; zone++) {
  4304. mz = &pn->zoneinfo[zone];
  4305. for_each_lru(l)
  4306. INIT_LIST_HEAD(&mz->lists[l]);
  4307. mz->usage_in_excess = 0;
  4308. mz->on_tree = false;
  4309. mz->mem = mem;
  4310. }
  4311. return 0;
  4312. }
  4313. static void free_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
  4314. {
  4315. kfree(mem->info.nodeinfo[node]);
  4316. }
  4317. static struct mem_cgroup *mem_cgroup_alloc(void)
  4318. {
  4319. struct mem_cgroup *mem;
  4320. int size = sizeof(struct mem_cgroup);
  4321. /* Can be very big if MAX_NUMNODES is very big */
  4322. if (size < PAGE_SIZE)
  4323. mem = kzalloc(size, GFP_KERNEL);
  4324. else
  4325. mem = vzalloc(size);
  4326. if (!mem)
  4327. return NULL;
  4328. mem->stat = alloc_percpu(struct mem_cgroup_stat_cpu);
  4329. if (!mem->stat)
  4330. goto out_free;
  4331. spin_lock_init(&mem->pcp_counter_lock);
  4332. return mem;
  4333. out_free:
  4334. if (size < PAGE_SIZE)
  4335. kfree(mem);
  4336. else
  4337. vfree(mem);
  4338. return NULL;
  4339. }
  4340. /*
  4341. * At destroying mem_cgroup, references from swap_cgroup can remain.
  4342. * (scanning all at force_empty is too costly...)
  4343. *
  4344. * Instead of clearing all references at force_empty, we remember
  4345. * the number of reference from swap_cgroup and free mem_cgroup when
  4346. * it goes down to 0.
  4347. *
  4348. * Removal of cgroup itself succeeds regardless of refs from swap.
  4349. */
  4350. static void __mem_cgroup_free(struct mem_cgroup *mem)
  4351. {
  4352. int node;
  4353. mem_cgroup_remove_from_trees(mem);
  4354. free_css_id(&mem_cgroup_subsys, &mem->css);
  4355. for_each_node_state(node, N_POSSIBLE)
  4356. free_mem_cgroup_per_zone_info(mem, node);
  4357. free_percpu(mem->stat);
  4358. if (sizeof(struct mem_cgroup) < PAGE_SIZE)
  4359. kfree(mem);
  4360. else
  4361. vfree(mem);
  4362. }
  4363. static void mem_cgroup_get(struct mem_cgroup *mem)
  4364. {
  4365. atomic_inc(&mem->refcnt);
  4366. }
  4367. static void __mem_cgroup_put(struct mem_cgroup *mem, int count)
  4368. {
  4369. if (atomic_sub_and_test(count, &mem->refcnt)) {
  4370. struct mem_cgroup *parent = parent_mem_cgroup(mem);
  4371. __mem_cgroup_free(mem);
  4372. if (parent)
  4373. mem_cgroup_put(parent);
  4374. }
  4375. }
  4376. static void mem_cgroup_put(struct mem_cgroup *mem)
  4377. {
  4378. __mem_cgroup_put(mem, 1);
  4379. }
  4380. /*
  4381. * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
  4382. */
  4383. static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *mem)
  4384. {
  4385. if (!mem->res.parent)
  4386. return NULL;
  4387. return mem_cgroup_from_res_counter(mem->res.parent, res);
  4388. }
  4389. #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
  4390. static void __init enable_swap_cgroup(void)
  4391. {
  4392. if (!mem_cgroup_disabled() && really_do_swap_account)
  4393. do_swap_account = 1;
  4394. }
  4395. #else
  4396. static void __init enable_swap_cgroup(void)
  4397. {
  4398. }
  4399. #endif
  4400. static int mem_cgroup_soft_limit_tree_init(void)
  4401. {
  4402. struct mem_cgroup_tree_per_node *rtpn;
  4403. struct mem_cgroup_tree_per_zone *rtpz;
  4404. int tmp, node, zone;
  4405. for_each_node_state(node, N_POSSIBLE) {
  4406. tmp = node;
  4407. if (!node_state(node, N_NORMAL_MEMORY))
  4408. tmp = -1;
  4409. rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, tmp);
  4410. if (!rtpn)
  4411. return 1;
  4412. soft_limit_tree.rb_tree_per_node[node] = rtpn;
  4413. for (zone = 0; zone < MAX_NR_ZONES; zone++) {
  4414. rtpz = &rtpn->rb_tree_per_zone[zone];
  4415. rtpz->rb_root = RB_ROOT;
  4416. spin_lock_init(&rtpz->lock);
  4417. }
  4418. }
  4419. return 0;
  4420. }
  4421. static struct cgroup_subsys_state * __ref
  4422. mem_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cont)
  4423. {
  4424. struct mem_cgroup *mem, *parent;
  4425. long error = -ENOMEM;
  4426. int node;
  4427. mem = mem_cgroup_alloc();
  4428. if (!mem)
  4429. return ERR_PTR(error);
  4430. for_each_node_state(node, N_POSSIBLE)
  4431. if (alloc_mem_cgroup_per_zone_info(mem, node))
  4432. goto free_out;
  4433. /* root ? */
  4434. if (cont->parent == NULL) {
  4435. int cpu;
  4436. enable_swap_cgroup();
  4437. parent = NULL;
  4438. root_mem_cgroup = mem;
  4439. if (mem_cgroup_soft_limit_tree_init())
  4440. goto free_out;
  4441. for_each_possible_cpu(cpu) {
  4442. struct memcg_stock_pcp *stock =
  4443. &per_cpu(memcg_stock, cpu);
  4444. INIT_WORK(&stock->work, drain_local_stock);
  4445. }
  4446. hotcpu_notifier(memcg_cpu_hotplug_callback, 0);
  4447. } else {
  4448. parent = mem_cgroup_from_cont(cont->parent);
  4449. mem->use_hierarchy = parent->use_hierarchy;
  4450. mem->oom_kill_disable = parent->oom_kill_disable;
  4451. }
  4452. if (parent && parent->use_hierarchy) {
  4453. res_counter_init(&mem->res, &parent->res);
  4454. res_counter_init(&mem->memsw, &parent->memsw);
  4455. /*
  4456. * We increment refcnt of the parent to ensure that we can
  4457. * safely access it on res_counter_charge/uncharge.
  4458. * This refcnt will be decremented when freeing this
  4459. * mem_cgroup(see mem_cgroup_put).
  4460. */
  4461. mem_cgroup_get(parent);
  4462. } else {
  4463. res_counter_init(&mem->res, NULL);
  4464. res_counter_init(&mem->memsw, NULL);
  4465. }
  4466. mem->last_scanned_child = 0;
  4467. mem->last_scanned_node = MAX_NUMNODES;
  4468. INIT_LIST_HEAD(&mem->oom_notify);
  4469. if (parent)
  4470. mem->swappiness = mem_cgroup_swappiness(parent);
  4471. atomic_set(&mem->refcnt, 1);
  4472. mem->move_charge_at_immigrate = 0;
  4473. mutex_init(&mem->thresholds_lock);
  4474. spin_lock_init(&mem->scanstat.lock);
  4475. return &mem->css;
  4476. free_out:
  4477. __mem_cgroup_free(mem);
  4478. root_mem_cgroup = NULL;
  4479. return ERR_PTR(error);
  4480. }
  4481. static int mem_cgroup_pre_destroy(struct cgroup_subsys *ss,
  4482. struct cgroup *cont)
  4483. {
  4484. struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
  4485. return mem_cgroup_force_empty(mem, false);
  4486. }
  4487. static void mem_cgroup_destroy(struct cgroup_subsys *ss,
  4488. struct cgroup *cont)
  4489. {
  4490. struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
  4491. mem_cgroup_put(mem);
  4492. }
  4493. static int mem_cgroup_populate(struct cgroup_subsys *ss,
  4494. struct cgroup *cont)
  4495. {
  4496. int ret;
  4497. ret = cgroup_add_files(cont, ss, mem_cgroup_files,
  4498. ARRAY_SIZE(mem_cgroup_files));
  4499. if (!ret)
  4500. ret = register_memsw_files(cont, ss);
  4501. return ret;
  4502. }
  4503. #ifdef CONFIG_MMU
  4504. /* Handlers for move charge at task migration. */
  4505. #define PRECHARGE_COUNT_AT_ONCE 256
  4506. static int mem_cgroup_do_precharge(unsigned long count)
  4507. {
  4508. int ret = 0;
  4509. int batch_count = PRECHARGE_COUNT_AT_ONCE;
  4510. struct mem_cgroup *mem = mc.to;
  4511. if (mem_cgroup_is_root(mem)) {
  4512. mc.precharge += count;
  4513. /* we don't need css_get for root */
  4514. return ret;
  4515. }
  4516. /* try to charge at once */
  4517. if (count > 1) {
  4518. struct res_counter *dummy;
  4519. /*
  4520. * "mem" cannot be under rmdir() because we've already checked
  4521. * by cgroup_lock_live_cgroup() that it is not removed and we
  4522. * are still under the same cgroup_mutex. So we can postpone
  4523. * css_get().
  4524. */
  4525. if (res_counter_charge(&mem->res, PAGE_SIZE * count, &dummy))
  4526. goto one_by_one;
  4527. if (do_swap_account && res_counter_charge(&mem->memsw,
  4528. PAGE_SIZE * count, &dummy)) {
  4529. res_counter_uncharge(&mem->res, PAGE_SIZE * count);
  4530. goto one_by_one;
  4531. }
  4532. mc.precharge += count;
  4533. return ret;
  4534. }
  4535. one_by_one:
  4536. /* fall back to one by one charge */
  4537. while (count--) {
  4538. if (signal_pending(current)) {
  4539. ret = -EINTR;
  4540. break;
  4541. }
  4542. if (!batch_count--) {
  4543. batch_count = PRECHARGE_COUNT_AT_ONCE;
  4544. cond_resched();
  4545. }
  4546. ret = __mem_cgroup_try_charge(NULL, GFP_KERNEL, 1, &mem, false);
  4547. if (ret || !mem)
  4548. /* mem_cgroup_clear_mc() will do uncharge later */
  4549. return -ENOMEM;
  4550. mc.precharge++;
  4551. }
  4552. return ret;
  4553. }
  4554. /**
  4555. * is_target_pte_for_mc - check a pte whether it is valid for move charge
  4556. * @vma: the vma the pte to be checked belongs
  4557. * @addr: the address corresponding to the pte to be checked
  4558. * @ptent: the pte to be checked
  4559. * @target: the pointer the target page or swap ent will be stored(can be NULL)
  4560. *
  4561. * Returns
  4562. * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
  4563. * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
  4564. * move charge. if @target is not NULL, the page is stored in target->page
  4565. * with extra refcnt got(Callers should handle it).
  4566. * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
  4567. * target for charge migration. if @target is not NULL, the entry is stored
  4568. * in target->ent.
  4569. *
  4570. * Called with pte lock held.
  4571. */
  4572. union mc_target {
  4573. struct page *page;
  4574. swp_entry_t ent;
  4575. };
  4576. enum mc_target_type {
  4577. MC_TARGET_NONE, /* not used */
  4578. MC_TARGET_PAGE,
  4579. MC_TARGET_SWAP,
  4580. };
  4581. static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
  4582. unsigned long addr, pte_t ptent)
  4583. {
  4584. struct page *page = vm_normal_page(vma, addr, ptent);
  4585. if (!page || !page_mapped(page))
  4586. return NULL;
  4587. if (PageAnon(page)) {
  4588. /* we don't move shared anon */
  4589. if (!move_anon() || page_mapcount(page) > 2)
  4590. return NULL;
  4591. } else if (!move_file())
  4592. /* we ignore mapcount for file pages */
  4593. return NULL;
  4594. if (!get_page_unless_zero(page))
  4595. return NULL;
  4596. return page;
  4597. }
  4598. static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
  4599. unsigned long addr, pte_t ptent, swp_entry_t *entry)
  4600. {
  4601. int usage_count;
  4602. struct page *page = NULL;
  4603. swp_entry_t ent = pte_to_swp_entry(ptent);
  4604. if (!move_anon() || non_swap_entry(ent))
  4605. return NULL;
  4606. usage_count = mem_cgroup_count_swap_user(ent, &page);
  4607. if (usage_count > 1) { /* we don't move shared anon */
  4608. if (page)
  4609. put_page(page);
  4610. return NULL;
  4611. }
  4612. if (do_swap_account)
  4613. entry->val = ent.val;
  4614. return page;
  4615. }
  4616. static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
  4617. unsigned long addr, pte_t ptent, swp_entry_t *entry)
  4618. {
  4619. struct page *page = NULL;
  4620. struct inode *inode;
  4621. struct address_space *mapping;
  4622. pgoff_t pgoff;
  4623. if (!vma->vm_file) /* anonymous vma */
  4624. return NULL;
  4625. if (!move_file())
  4626. return NULL;
  4627. inode = vma->vm_file->f_path.dentry->d_inode;
  4628. mapping = vma->vm_file->f_mapping;
  4629. if (pte_none(ptent))
  4630. pgoff = linear_page_index(vma, addr);
  4631. else /* pte_file(ptent) is true */
  4632. pgoff = pte_to_pgoff(ptent);
  4633. /* page is moved even if it's not RSS of this task(page-faulted). */
  4634. page = find_get_page(mapping, pgoff);
  4635. #ifdef CONFIG_SWAP
  4636. /* shmem/tmpfs may report page out on swap: account for that too. */
  4637. if (radix_tree_exceptional_entry(page)) {
  4638. swp_entry_t swap = radix_to_swp_entry(page);
  4639. if (do_swap_account)
  4640. *entry = swap;
  4641. page = find_get_page(&swapper_space, swap.val);
  4642. }
  4643. #endif
  4644. return page;
  4645. }
  4646. static int is_target_pte_for_mc(struct vm_area_struct *vma,
  4647. unsigned long addr, pte_t ptent, union mc_target *target)
  4648. {
  4649. struct page *page = NULL;
  4650. struct page_cgroup *pc;
  4651. int ret = 0;
  4652. swp_entry_t ent = { .val = 0 };
  4653. if (pte_present(ptent))
  4654. page = mc_handle_present_pte(vma, addr, ptent);
  4655. else if (is_swap_pte(ptent))
  4656. page = mc_handle_swap_pte(vma, addr, ptent, &ent);
  4657. else if (pte_none(ptent) || pte_file(ptent))
  4658. page = mc_handle_file_pte(vma, addr, ptent, &ent);
  4659. if (!page && !ent.val)
  4660. return 0;
  4661. if (page) {
  4662. pc = lookup_page_cgroup(page);
  4663. /*
  4664. * Do only loose check w/o page_cgroup lock.
  4665. * mem_cgroup_move_account() checks the pc is valid or not under
  4666. * the lock.
  4667. */
  4668. if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
  4669. ret = MC_TARGET_PAGE;
  4670. if (target)
  4671. target->page = page;
  4672. }
  4673. if (!ret || !target)
  4674. put_page(page);
  4675. }
  4676. /* There is a swap entry and a page doesn't exist or isn't charged */
  4677. if (ent.val && !ret &&
  4678. css_id(&mc.from->css) == lookup_swap_cgroup(ent)) {
  4679. ret = MC_TARGET_SWAP;
  4680. if (target)
  4681. target->ent = ent;
  4682. }
  4683. return ret;
  4684. }
  4685. static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
  4686. unsigned long addr, unsigned long end,
  4687. struct mm_walk *walk)
  4688. {
  4689. struct vm_area_struct *vma = walk->private;
  4690. pte_t *pte;
  4691. spinlock_t *ptl;
  4692. split_huge_page_pmd(walk->mm, pmd);
  4693. pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
  4694. for (; addr != end; pte++, addr += PAGE_SIZE)
  4695. if (is_target_pte_for_mc(vma, addr, *pte, NULL))
  4696. mc.precharge++; /* increment precharge temporarily */
  4697. pte_unmap_unlock(pte - 1, ptl);
  4698. cond_resched();
  4699. return 0;
  4700. }
  4701. static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
  4702. {
  4703. unsigned long precharge;
  4704. struct vm_area_struct *vma;
  4705. down_read(&mm->mmap_sem);
  4706. for (vma = mm->mmap; vma; vma = vma->vm_next) {
  4707. struct mm_walk mem_cgroup_count_precharge_walk = {
  4708. .pmd_entry = mem_cgroup_count_precharge_pte_range,
  4709. .mm = mm,
  4710. .private = vma,
  4711. };
  4712. if (is_vm_hugetlb_page(vma))
  4713. continue;
  4714. walk_page_range(vma->vm_start, vma->vm_end,
  4715. &mem_cgroup_count_precharge_walk);
  4716. }
  4717. up_read(&mm->mmap_sem);
  4718. precharge = mc.precharge;
  4719. mc.precharge = 0;
  4720. return precharge;
  4721. }
  4722. static int mem_cgroup_precharge_mc(struct mm_struct *mm)
  4723. {
  4724. unsigned long precharge = mem_cgroup_count_precharge(mm);
  4725. VM_BUG_ON(mc.moving_task);
  4726. mc.moving_task = current;
  4727. return mem_cgroup_do_precharge(precharge);
  4728. }
  4729. /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
  4730. static void __mem_cgroup_clear_mc(void)
  4731. {
  4732. struct mem_cgroup *from = mc.from;
  4733. struct mem_cgroup *to = mc.to;
  4734. /* we must uncharge all the leftover precharges from mc.to */
  4735. if (mc.precharge) {
  4736. __mem_cgroup_cancel_charge(mc.to, mc.precharge);
  4737. mc.precharge = 0;
  4738. }
  4739. /*
  4740. * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
  4741. * we must uncharge here.
  4742. */
  4743. if (mc.moved_charge) {
  4744. __mem_cgroup_cancel_charge(mc.from, mc.moved_charge);
  4745. mc.moved_charge = 0;
  4746. }
  4747. /* we must fixup refcnts and charges */
  4748. if (mc.moved_swap) {
  4749. /* uncharge swap account from the old cgroup */
  4750. if (!mem_cgroup_is_root(mc.from))
  4751. res_counter_uncharge(&mc.from->memsw,
  4752. PAGE_SIZE * mc.moved_swap);
  4753. __mem_cgroup_put(mc.from, mc.moved_swap);
  4754. if (!mem_cgroup_is_root(mc.to)) {
  4755. /*
  4756. * we charged both to->res and to->memsw, so we should
  4757. * uncharge to->res.
  4758. */
  4759. res_counter_uncharge(&mc.to->res,
  4760. PAGE_SIZE * mc.moved_swap);
  4761. }
  4762. /* we've already done mem_cgroup_get(mc.to) */
  4763. mc.moved_swap = 0;
  4764. }
  4765. memcg_oom_recover(from);
  4766. memcg_oom_recover(to);
  4767. wake_up_all(&mc.waitq);
  4768. }
  4769. static void mem_cgroup_clear_mc(void)
  4770. {
  4771. struct mem_cgroup *from = mc.from;
  4772. /*
  4773. * we must clear moving_task before waking up waiters at the end of
  4774. * task migration.
  4775. */
  4776. mc.moving_task = NULL;
  4777. __mem_cgroup_clear_mc();
  4778. spin_lock(&mc.lock);
  4779. mc.from = NULL;
  4780. mc.to = NULL;
  4781. spin_unlock(&mc.lock);
  4782. mem_cgroup_end_move(from);
  4783. }
  4784. static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
  4785. struct cgroup *cgroup,
  4786. struct task_struct *p)
  4787. {
  4788. int ret = 0;
  4789. struct mem_cgroup *mem = mem_cgroup_from_cont(cgroup);
  4790. if (mem->move_charge_at_immigrate) {
  4791. struct mm_struct *mm;
  4792. struct mem_cgroup *from = mem_cgroup_from_task(p);
  4793. VM_BUG_ON(from == mem);
  4794. mm = get_task_mm(p);
  4795. if (!mm)
  4796. return 0;
  4797. /* We move charges only when we move a owner of the mm */
  4798. if (mm->owner == p) {
  4799. VM_BUG_ON(mc.from);
  4800. VM_BUG_ON(mc.to);
  4801. VM_BUG_ON(mc.precharge);
  4802. VM_BUG_ON(mc.moved_charge);
  4803. VM_BUG_ON(mc.moved_swap);
  4804. mem_cgroup_start_move(from);
  4805. spin_lock(&mc.lock);
  4806. mc.from = from;
  4807. mc.to = mem;
  4808. spin_unlock(&mc.lock);
  4809. /* We set mc.moving_task later */
  4810. ret = mem_cgroup_precharge_mc(mm);
  4811. if (ret)
  4812. mem_cgroup_clear_mc();
  4813. }
  4814. mmput(mm);
  4815. }
  4816. return ret;
  4817. }
  4818. static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
  4819. struct cgroup *cgroup,
  4820. struct task_struct *p)
  4821. {
  4822. mem_cgroup_clear_mc();
  4823. }
  4824. static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
  4825. unsigned long addr, unsigned long end,
  4826. struct mm_walk *walk)
  4827. {
  4828. int ret = 0;
  4829. struct vm_area_struct *vma = walk->private;
  4830. pte_t *pte;
  4831. spinlock_t *ptl;
  4832. split_huge_page_pmd(walk->mm, pmd);
  4833. retry:
  4834. pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
  4835. for (; addr != end; addr += PAGE_SIZE) {
  4836. pte_t ptent = *(pte++);
  4837. union mc_target target;
  4838. int type;
  4839. struct page *page;
  4840. struct page_cgroup *pc;
  4841. swp_entry_t ent;
  4842. if (!mc.precharge)
  4843. break;
  4844. type = is_target_pte_for_mc(vma, addr, ptent, &target);
  4845. switch (type) {
  4846. case MC_TARGET_PAGE:
  4847. page = target.page;
  4848. if (isolate_lru_page(page))
  4849. goto put;
  4850. pc = lookup_page_cgroup(page);
  4851. if (!mem_cgroup_move_account(page, 1, pc,
  4852. mc.from, mc.to, false)) {
  4853. mc.precharge--;
  4854. /* we uncharge from mc.from later. */
  4855. mc.moved_charge++;
  4856. }
  4857. putback_lru_page(page);
  4858. put: /* is_target_pte_for_mc() gets the page */
  4859. put_page(page);
  4860. break;
  4861. case MC_TARGET_SWAP:
  4862. ent = target.ent;
  4863. if (!mem_cgroup_move_swap_account(ent,
  4864. mc.from, mc.to, false)) {
  4865. mc.precharge--;
  4866. /* we fixup refcnts and charges later. */
  4867. mc.moved_swap++;
  4868. }
  4869. break;
  4870. default:
  4871. break;
  4872. }
  4873. }
  4874. pte_unmap_unlock(pte - 1, ptl);
  4875. cond_resched();
  4876. if (addr != end) {
  4877. /*
  4878. * We have consumed all precharges we got in can_attach().
  4879. * We try charge one by one, but don't do any additional
  4880. * charges to mc.to if we have failed in charge once in attach()
  4881. * phase.
  4882. */
  4883. ret = mem_cgroup_do_precharge(1);
  4884. if (!ret)
  4885. goto retry;
  4886. }
  4887. return ret;
  4888. }
  4889. static void mem_cgroup_move_charge(struct mm_struct *mm)
  4890. {
  4891. struct vm_area_struct *vma;
  4892. lru_add_drain_all();
  4893. retry:
  4894. if (unlikely(!down_read_trylock(&mm->mmap_sem))) {
  4895. /*
  4896. * Someone who are holding the mmap_sem might be waiting in
  4897. * waitq. So we cancel all extra charges, wake up all waiters,
  4898. * and retry. Because we cancel precharges, we might not be able
  4899. * to move enough charges, but moving charge is a best-effort
  4900. * feature anyway, so it wouldn't be a big problem.
  4901. */
  4902. __mem_cgroup_clear_mc();
  4903. cond_resched();
  4904. goto retry;
  4905. }
  4906. for (vma = mm->mmap; vma; vma = vma->vm_next) {
  4907. int ret;
  4908. struct mm_walk mem_cgroup_move_charge_walk = {
  4909. .pmd_entry = mem_cgroup_move_charge_pte_range,
  4910. .mm = mm,
  4911. .private = vma,
  4912. };
  4913. if (is_vm_hugetlb_page(vma))
  4914. continue;
  4915. ret = walk_page_range(vma->vm_start, vma->vm_end,
  4916. &mem_cgroup_move_charge_walk);
  4917. if (ret)
  4918. /*
  4919. * means we have consumed all precharges and failed in
  4920. * doing additional charge. Just abandon here.
  4921. */
  4922. break;
  4923. }
  4924. up_read(&mm->mmap_sem);
  4925. }
  4926. static void mem_cgroup_move_task(struct cgroup_subsys *ss,
  4927. struct cgroup *cont,
  4928. struct cgroup *old_cont,
  4929. struct task_struct *p)
  4930. {
  4931. struct mm_struct *mm = get_task_mm(p);
  4932. if (mm) {
  4933. if (mc.to)
  4934. mem_cgroup_move_charge(mm);
  4935. put_swap_token(mm);
  4936. mmput(mm);
  4937. }
  4938. if (mc.to)
  4939. mem_cgroup_clear_mc();
  4940. }
  4941. #else /* !CONFIG_MMU */
  4942. static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
  4943. struct cgroup *cgroup,
  4944. struct task_struct *p)
  4945. {
  4946. return 0;
  4947. }
  4948. static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
  4949. struct cgroup *cgroup,
  4950. struct task_struct *p)
  4951. {
  4952. }
  4953. static void mem_cgroup_move_task(struct cgroup_subsys *ss,
  4954. struct cgroup *cont,
  4955. struct cgroup *old_cont,
  4956. struct task_struct *p)
  4957. {
  4958. }
  4959. #endif
  4960. struct cgroup_subsys mem_cgroup_subsys = {
  4961. .name = "memory",
  4962. .subsys_id = mem_cgroup_subsys_id,
  4963. .create = mem_cgroup_create,
  4964. .pre_destroy = mem_cgroup_pre_destroy,
  4965. .destroy = mem_cgroup_destroy,
  4966. .populate = mem_cgroup_populate,
  4967. .can_attach = mem_cgroup_can_attach,
  4968. .cancel_attach = mem_cgroup_cancel_attach,
  4969. .attach = mem_cgroup_move_task,
  4970. .early_init = 0,
  4971. .use_id = 1,
  4972. };
  4973. #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
  4974. static int __init enable_swap_account(char *s)
  4975. {
  4976. /* consider enabled if no parameter or 1 is given */
  4977. if (!strcmp(s, "1"))
  4978. really_do_swap_account = 1;
  4979. else if (!strcmp(s, "0"))
  4980. really_do_swap_account = 0;
  4981. return 1;
  4982. }
  4983. __setup("swapaccount=", enable_swap_account);
  4984. #endif