memcontrol.c 147 KB

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